forked from libgox/buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer_length_prefixed_string.go
50 lines (41 loc) · 1.3 KB
/
buffer_length_prefixed_string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package buffer
// ReadLengthPrefixedString reads a string in big-endian format. It first reads the length (uint32), then the string data.
func (b *Buffer) ReadLengthPrefixedString() (string, error) {
length, err := b.ReadUInt32()
if err != nil {
return "", err
}
return b.ReadString(int(length))
}
// WriteLengthPrefixedString writes a string in big-endian format. It writes the length (uint32), followed by the string data.
func (b *Buffer) WriteLengthPrefixedString(s string) error {
length := uint32(len(s))
err := b.WriteUInt32(length)
if err != nil {
return err
}
err = b.WriteString(s)
return err
}
// ReadLengthPrefixedStringLe reads a string in little-endian format. First, it reads the length (uint32), then the string data.
func (b *Buffer) ReadLengthPrefixedStringLe() (string, error) {
length, err := b.ReadUInt32Le()
if err != nil {
return "", err
}
data, err := b.ReadNBytes(int(length))
if err != nil {
return "", err
}
return string(data), nil
}
// WriteLengthPrefixedStringLe writes a string in little-endian format. It writes the length (uint32), followed by the string data.
func (b *Buffer) WriteLengthPrefixedStringLe(s string) error {
length := uint32(len(s))
err := b.WriteUInt32Le(length)
if err != nil {
return err
}
err = b.WriteExactly([]byte(s))
return err
}