This repository was archived by the owner on Jun 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
95 lines (77 loc) · 1.79 KB
/
string.go
File metadata and controls
95 lines (77 loc) · 1.79 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package amf0
import (
"bytes"
"io"
"reflect"
)
type (
String string
LongString string
)
var (
_ AmfType = new(String)
_ AmfType = new(LongString)
)
func NewString(str string) *String {
s := new(String)
*s = String(str)
return s
}
func NewLongString(str string) *LongString {
s := new(LongString)
*s = LongString(str)
return s
}
func (s *String) Marker() byte { return 0x02 }
func (s *String) Native() reflect.Type { return reflect.TypeOf("") }
func (s *String) Decode(r io.Reader) error {
if v, err := strDecode(r, 2); err != nil {
return err
} else {
*s = String(v)
}
return nil
}
func (s *String) Encode(w io.Writer) (int, error) {
return strEncode(string(*s), w, 2)
}
func (l *LongString) Marker() byte { return 0x0c }
func (l *LongString) Native() reflect.Type { return reflect.TypeOf(l) }
func (l *LongString) Decode(r io.Reader) error {
if v, err := strDecode(r, 4); err != nil {
return err
} else {
*l = LongString(v)
}
return nil
}
func (l *LongString) Encode(w io.Writer) (int, error) {
return strEncode(string(*l), w, 4)
}
func strDecode(r io.Reader, sizeLen int) (string, error) {
sizeBytes := make([]byte, sizeLen)
if _, err := io.ReadFull(r, sizeBytes); err != nil {
return "", err
}
var slen uint64
for i := 0; i < sizeLen; i++ {
slen |= uint64(sizeBytes[i]) << (uint(sizeLen-i-1) << 3)
}
str := make([]byte, int(slen))
if _, err := io.ReadFull(r, str); err != nil {
return "", err
}
return string(str), nil
}
func strEncode(str string, w io.Writer, sizeLen int) (int, error) {
b := new(bytes.Buffer)
strLen := len(str)
for i := 0; i < sizeLen; i++ {
b.WriteByte(byte(strLen >> (uint(sizeLen-i-1) << 3)))
}
b.WriteString(str)
if n, err := io.Copy(w, b); err != nil {
return int(n), err
}
return strLen + sizeLen, nil
}