Skip to content

Commit d6fbce1

Browse files
phyberdiscordianfish
authored andcommitted
helper: Add new bytesToString function and tests
Signed-off-by: David O'Rourke <david.orourke@gmail.com>
1 parent 4c06e33 commit d6fbce1

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

collector/helper.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
package collector
1515

1616
import (
17+
"bytes"
1718
"io/ioutil"
1819
"strconv"
1920
"strings"
@@ -30,3 +31,16 @@ func readUintFromFile(path string) (uint64, error) {
3031
}
3132
return value, nil
3233
}
34+
35+
// Take a []byte{} and return a string based on null termination.
36+
// This is useful for situations where the OS has returned a null terminated
37+
// string to use.
38+
// If this function happens to receive a byteArray that contains no nulls, we
39+
// simply convert the array to a string with no bounding.
40+
func bytesToString(byteArray []byte) string {
41+
n := bytes.IndexByte(byteArray, 0)
42+
if n < 0 {
43+
return string(byteArray)
44+
}
45+
return string(byteArray[:n])
46+
}

collector/helper_test.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Copyright 2015 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package collector
15+
16+
import (
17+
"testing"
18+
)
19+
20+
func TestBytesToString(t *testing.T) {
21+
tests := []struct {
22+
name string
23+
b []byte
24+
expected string
25+
}{
26+
{
27+
"Single null byte",
28+
[]byte{0},
29+
"",
30+
},
31+
{
32+
"Empty byte array",
33+
[]byte{},
34+
"",
35+
},
36+
{
37+
"Not null terminated",
38+
[]byte{65, 66, 67},
39+
"ABC",
40+
},
41+
{
42+
"Null randomly in array",
43+
[]byte{65, 66, 67, 0, 65, 0, 65},
44+
"ABC",
45+
},
46+
{
47+
"Array starts with null and contains other valid bytes",
48+
[]byte{0, 65, 66, 67, 0},
49+
"",
50+
},
51+
}
52+
53+
for _, tt := range tests {
54+
name := tt.name
55+
b := tt.b
56+
result := bytesToString(b)
57+
expected := tt.expected
58+
59+
if result != expected {
60+
t.Errorf("bytesToString(%#v): Name: %s, expected %#v, got %#v)", b, name, expected, result)
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)