-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstrings.go
62 lines (49 loc) · 1.12 KB
/
strings.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
51
52
53
54
55
56
57
58
59
60
61
62
package ikea
import (
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"reflect"
"unicode/utf8"
)
var stringTypeHandler = new(stringReadWriter)
var _ variableReadWriter = (*stringReadWriter)(nil)
type stringReadWriter struct {
variable
}
func (s *stringReadWriter) readVariable(r io.Reader, v reflect.Value) error {
b := make([]byte, 4)
if _, err := io.ReadFull(r, b); err != nil {
return err
}
ul := binary.BigEndian.Uint32(b)
if ul > math.MaxInt32 {
return fmt.Errorf("transmitted string size too large (%d>%d)", ul, math.MaxInt32)
}
l := int(ul)
str := make([]byte, l)
if _, err := io.ReadFull(r, str); err != nil {
return err
}
if !utf8.Valid(str) {
return errors.New("invalid utf8 string")
}
v.SetString(string(str))
return nil
}
func (s *stringReadWriter) writeVariable(w io.Writer, v reflect.Value) error {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, uint32(v.Len()))
if _, err := w.Write(b); err != nil {
return err
}
if _, err := w.Write([]byte(v.String())); err != nil {
return err
}
return nil
}
func (s *stringReadWriter) vLength(v reflect.Value) int {
return 4 + v.Len()
}