- Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathencode.go
More file actions
Latest commit
322 lines (273 loc) · 7.6 KB
/
Copy pathencode.go
File metadata and controls
322 lines (273 loc) · 7.6 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package bencode
import (
"bytes"
"encoding"
"fmt"
"io"
"reflect"
"sort"
)
typesortValues []reflect.Value
func (psortValues) Len() int { returnlen(p) }
func (psortValues) Less(i, jint) bool { returnp[i].String() <p[j].String() }
func (psortValues) Swap(i, jint) { p[i], p[j] =p[j], p[i] }
// Marshaler is the interface implemented by types
// that can marshal themselves into valid bencode.
typeMarshalerinterface {
MarshalBencode() ([]byte, error)
}
// An Encoder writes bencoded objects to an output stream.
typeEncoderstruct {
w io.Writer
}
// NewEncoder returns a new encoder that writes to w.
funcNewEncoder(w io.Writer) *Encoder {
return&Encoder{w}
}
// Encode writes the bencoded data of val to its output stream.
// If an encountered value implements the Marshaler interface,
// its MarshalBencode method is called to produce the bencode output for this value.
// If no MarshalBencode method is present but the value implements encoding.TextMarshaler instead,
// its MarshalText method is called, which encodes the result as a bencode string.
// See the documentation for Decode about the conversion of Go values to
// bencoded data.
func (e*Encoder) Encode(valinterface{}) error {
returnencodeValue(e.w, reflect.ValueOf(val))
}
// EncodeString returns the bencoded data of val as a string.
funcEncodeString(valinterface{}) (string, error) {
buf:=new(bytes.Buffer)
e:=NewEncoder(buf)
iferr:=e.Encode(val); err!=nil {
return"", err
}
returnbuf.String(), nil
}
// EncodeBytes returns the bencoded data of val as a slice of bytes.
funcEncodeBytes(valinterface{}) ([]byte, error) {
buf:=new(bytes.Buffer)
e:=NewEncoder(buf)
iferr:=e.Encode(val); err!=nil {
returnnil, err
}
returnbuf.Bytes(), nil
}
funcisNilValue(v reflect.Value) bool {
return (v.Kind() ==reflect.Interface||v.Kind() ==reflect.Ptr) &&
v.IsNil()
}
funcencodeValue(w io.Writer, val reflect.Value) error {
marshaler, textMarshaler, v:=indirectEncodeValue(val)
// marshal a type using the Marshaler type
// if it implements that interface.
ifmarshaler!=nil {
bytes, err:=marshaler.MarshalBencode()
iferr!=nil {
returnerr
}
_, err=w.Write(bytes)
returnerr
}
// marshal a type using the TextMarshaler type
// if it implements that interface.
iftextMarshaler!=nil {
bytes, err:=textMarshaler.MarshalText()
iferr!=nil {
returnerr
}
_, err=fmt.Fprintf(w, "%d:%s", len(bytes), bytes)
returnerr
}
// if indirection returns us an invalid value that means there was a nil
// pointer in the path somewhere.
if!v.IsValid() {
returnnil
}
// send in a raw message if we have that type
ifrm, ok:=v.Interface().(RawMessage); ok {
_, err:=io.Copy(w, bytes.NewReader(rm))
returnerr
}
switchv.Kind() {
casereflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
_, err:=fmt.Fprintf(w, "i%de", v.Int())
returnerr
casereflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
_, err:=fmt.Fprintf(w, "i%de", v.Uint())
returnerr
casereflect.Bool:
i:=0
ifv.Bool() {
i=1
}
_, err:=fmt.Fprintf(w, "i%de", i)
returnerr
casereflect.String:
_, err:=fmt.Fprintf(w, "%d:%s", len(v.String()), v.String())
returnerr
casereflect.Slice, reflect.Array:
// handle byte slices like strings
ifbyteSlice, ok:=val.Interface().([]byte); ok {
_, err:=fmt.Fprintf(w, "%d:", len(byteSlice))
iferr==nil {
_, err=w.Write(byteSlice)
}
returnerr
}
if_, err:=fmt.Fprint(w, "l"); err!=nil {
returnerr
}
fori:=0; i<v.Len(); i++ {
iferr:=encodeValue(w, v.Index(i)); err!=nil {
returnerr
}
}
_, err:=fmt.Fprint(w, "e")
returnerr
casereflect.Map:
if_, err:=fmt.Fprint(w, "d"); err!=nil {
returnerr
}
var (
keyssortValues=v.MapKeys()
mval reflect.Value
)
sort.Sort(keys)
fori:=rangekeys {
mval=v.MapIndex(keys[i])
ifisNilValue(mval) {
continue
}
iferr:=encodeValue(w, keys[i]); err!=nil {
returnerr
}
iferr:=encodeValue(w, mval); err!=nil {
returnerr
}
}
_, err:=fmt.Fprint(w, "e")
returnerr
casereflect.Struct:
if_, err:=fmt.Fprint(w, "d"); err!=nil {
returnerr
}
// add embedded structs to the dictionary
dict:=make(dictionary, 0, v.NumField())
dict, err:=readStruct(dict, v)
iferr!=nil {
returnerr
}
// sort the dictionary by keys
sort.Sort(dict)
// encode the dictionary in order
for_, def:=rangedict {
// encode the key
err:=encodeValue(w, reflect.ValueOf(def.key))
iferr!=nil {
returnerr
}
// encode the value
err=encodeValue(w, def.value)
iferr!=nil {
returnerr
}
}
_, err=fmt.Fprint(w, "e")
returnerr
}
returnfmt.Errorf("Can't encode type: %s", v.Type())
}
// indirectEncodeValue walks down v allocating pointers as needed,
// until it gets to a non-pointer.
// if it encounters an (Text)Marshaler, indirect stops and returns that.
funcindirectEncodeValue(v reflect.Value) (Marshaler, encoding.TextMarshaler, reflect.Value) {
// If v is a named type and is addressable,
// start with its address, so that if the type has pointer methods,
// we find them.
ifv.Kind() !=reflect.Ptr&&v.Type().Name() !=""&&v.CanAddr() {
v=v.Addr()
}
for {
ifv.Kind() ==reflect.Ptr&&v.IsNil() {
break
}
vi:=v.Interface()
ifm, ok:=vi.(Marshaler); ok {
returnm, nil, reflect.Value{}
}
ifm, ok:=vi.(encoding.TextMarshaler); ok {
returnnil, m, reflect.Value{}
}
ifv.Kind() !=reflect.Ptr {
break
}
v=v.Elem()
}
returnnil, nil, indirect(v, false)
}
typedefinitionstruct {
keystring
value reflect.Value
}
typedictionary []definition
func (ddictionary) Len() int { returnlen(d) }
func (ddictionary) Less(i, jint) bool { returnd[i].key<d[j].key }
func (ddictionary) Swap(i, jint) { d[i], d[j] =d[j], d[i] }
funcreadStruct(dictdictionary, v reflect.Value) (dictionary, error) {
t:=v.Type()
var (
fieldValue reflect.Value
rkeystring
)
fori:=0; i<t.NumField(); i++ {
key:=t.Field(i)
rkey=key.Name
fieldValue=v.FieldByIndex(key.Index)
// filter out unexported values etc.
if!fieldValue.CanInterface() {
continue
}
// filter out nil pointer values
ifisNilValue(fieldValue) {
continue
}
// * Near identical to usage in JSON except with key 'bencode'
//
// * Struct values encode as BEncode dictionaries. Each exported
// struct field becomes a set in the dictionary unless
// - the field's tag is "-", or
// - the field is empty and its tag specifies the "omitempty"
// option.
//
// * The default key string is the struct field name but can be
// specified in the struct field's tag value. The "bencode"
// key in struct field's tag value is the key name, followed
// by an optional comma and options.
tagValue:=key.Tag.Get("bencode")
iftagValue!="" {
// Keys with '-' are omit from output
iftagValue=="-" {
continue
}
name, options:=parseTag(tagValue)
// Keys with 'omitempty' are omitted if the field is empty
ifoptions.Contains("omitempty") &&isEmptyValue(fieldValue) {
continue
}
// All other values are treated as the key string
ifisValidTag(name) {
rkey=name
}
}
ifkey.Anonymous&&key.Type.Kind() ==reflect.Struct&&tagValue=="" {
varerrerror
dict, err=readStruct(dict, fieldValue)
iferr!=nil {
returnnil, err
}
} else {
dict=append(dict, definition{rkey, fieldValue})
}
}
returndict, nil
}