1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-04-11 11:21:59 +02:00

Use ByteSliceToString from golang.org/x/sys/unix (#2924)

Use unix.ByteSliceToString to convert Utsname []byte fields to strings.

This also allows to drop the charsToString helper which serves the same
purpose and matches ByteSliceToString's implementation.

Signed-off-by: Tobias Klauser <tklauser@distanz.ch>

Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
This commit is contained in:
Tobias Klauser 2022-05-26 16:31:35 +02:00 committed by GitHub
parent 7458aa961b
commit 4155b35624
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 5 additions and 40 deletions

View File

@ -19,7 +19,6 @@ package resource // import "go.opentelemetry.io/otel/sdk/resource"
var (
Uname = uname
CharsToString = charsToString
GetFirstAvailableFile = getFirstAvailableFile
)

View File

@ -18,7 +18,6 @@
package resource // import "go.opentelemetry.io/otel/sdk/resource"
import (
"bytes"
"fmt"
"os"
@ -69,23 +68,14 @@ func uname() (string, error) {
}
return fmt.Sprintf("%s %s %s %s %s",
charsToString(utsName.Sysname[:]),
charsToString(utsName.Nodename[:]),
charsToString(utsName.Release[:]),
charsToString(utsName.Version[:]),
charsToString(utsName.Machine[:]),
unix.ByteSliceToString(utsName.Sysname[:]),
unix.ByteSliceToString(utsName.Nodename[:]),
unix.ByteSliceToString(utsName.Release[:]),
unix.ByteSliceToString(utsName.Version[:]),
unix.ByteSliceToString(utsName.Machine[:]),
), nil
}
// charsToString converts a C-like null-terminated char array to a Go string.
func charsToString(charArray []byte) string {
if i := bytes.IndexByte(charArray, 0); i >= 0 {
charArray = charArray[:i]
}
return string(charArray)
}
// getFirstAvailableFile returns an *os.File of the first available
// file from a list of candidate file paths.
func getFirstAvailableFile(candidates []string) (*os.File, error) {

View File

@ -64,30 +64,6 @@ func TestUnameError(t *testing.T) {
resource.SetDefaultUnameProvider()
}
func TestCharsToString(t *testing.T) {
tt := []struct {
Name string
Bytes []byte
Expected string
}{
{"Nil array", nil, ""},
{"Empty array", []byte{}, ""},
{"Empty string (null terminated)", []byte{0x00}, ""},
{"Nonempty string (null terminated)", []byte{0x31, 0x32, 0x33, 0x00}, "123"},
{"Nonempty string (non-null terminated)", []byte{0x31, 0x32, 0x33}, "123"},
{"Nonempty string with values after null", []byte{0x31, 0x32, 0x33, 0x00, 0x34}, "123"},
}
for _, tc := range tt {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
result := resource.CharsToString(tc.Bytes)
require.EqualValues(t, tc.Expected, result)
})
}
}
func TestGetFirstAvailableFile(t *testing.T) {
tempDir := t.TempDir()