helper: Add new bytesToString function and tests

Signed-off-by: David O'Rourke <david.orourke@gmail.com>
This commit is contained in:
David O'Rourke 2020-06-02 12:06:38 +01:00 committed by Johannes 'fish' Ziemke
commit d6fbce1529
2 changed files with 77 additions and 0 deletions

View file

@ -14,6 +14,7 @@
package collector
import (
"bytes"
"io/ioutil"
"strconv"
"strings"
@ -30,3 +31,16 @@ func readUintFromFile(path string) (uint64, error) {
}
return value, nil
}
// Take a []byte{} and return a string based on null termination.
// This is useful for situations where the OS has returned a null terminated
// string to use.
// If this function happens to receive a byteArray that contains no nulls, we
// simply convert the array to a string with no bounding.
func bytesToString(byteArray []byte) string {
n := bytes.IndexByte(byteArray, 0)
if n < 0 {
return string(byteArray)
}
return string(byteArray[:n])
}