4
4
5
5
package syscall
6
6
7
+ import "errors"
8
+
7
9
// clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte.
8
10
func clen (n []byte ) int {
9
11
for i := 0 ; i < len (n ); i ++ {
@@ -13,3 +15,39 @@ func clen(n []byte) int {
13
15
}
14
16
return len (n )
15
17
}
18
+
19
+ // BytePtrFromString returns a pointer to a NUL-terminated array of
20
+ // bytes containing the text of s. If s contains a NUL byte at any
21
+ // location, it returns (nil, [EINVAL]).
22
+ //
23
+ // For darwin || nintendoswitch || wasi || wasip1 this is already implemented in /src/syscall/syscall_libc.go:266:6
24
+ // func BytePtrFromString(s string) (*byte, error) {
25
+ // a, err := ByteSliceFromString(s)
26
+ // if err != nil {
27
+ // return nil, err
28
+ // }
29
+ // return &a[0], nil
30
+ // }
31
+
32
+ // copied from upstream src/internal/bytealg/indexbyte_generic.go since we cannot use the internal bytealg package
33
+ func IndexByteString (s string , c byte ) int {
34
+ for i := 0 ; i < len (s ); i ++ {
35
+ if s [i ] == c {
36
+ return i
37
+ }
38
+ }
39
+ return - 1
40
+ }
41
+
42
+ // ByteSliceFromString returns a NUL-terminated slice of bytes
43
+ // containing the text of s. If s contains a NUL byte at any
44
+ // location, it returns (nil, [EINVAL]).
45
+ // https://cs.opensource.google/go/go/+/master:src/syscall/syscall.go;l=45;drc=94982a07825aec711f11c97283e99e467838d616
46
+ func ByteSliceFromString (s string ) ([]byte , error ) {
47
+ if IndexByteString (s , 0 ) != - 1 {
48
+ return nil , errors .New ("contains NUL" )
49
+ }
50
+ a := make ([]byte , len (s )+ 1 )
51
+ copy (a , s )
52
+ return a , nil
53
+ }
0 commit comments