-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathencode.go
More file actions
executable file
·524 lines (442 loc) · 12.7 KB
/
Copy pathencode.go
File metadata and controls
executable file
·524 lines (442 loc) · 12.7 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package bertlv
import (
"fmt"
"reflect"
)
// Marshaler is the interface implemented by types that can marshal themselves into a valid BER-TLV value.
type Marshaler interface {
MarshalBERTLV() ([]byte, error)
}
// Marshal returns the BER-TLV encoding of v.
func Marshal(v interface{}) ([]byte, error) {
return MarshalWithOptions(v, DefaultOptions())
}
// MarshalWithOptions returns the BER-TLV encoding of v with custom options.
func MarshalWithOptions(v interface{}, opts Options) ([]byte, error) {
e := NewEncoderWithOptions(opts)
if err := e.Encode(v); err != nil {
return nil, err
}
return e.Bytes(), nil
}
// Encoder handles BER-TLV encoding with configurable options.
type Encoder struct {
bytes []byte
options Options
}
// NewEncoder creates a new encoder with default options.
func NewEncoder() *Encoder {
return NewEncoderWithOptions(DefaultOptions())
}
// NewEncoderWithOptions creates a new encoder with custom options.
func NewEncoderWithOptions(opts Options) *Encoder {
return &Encoder{
bytes: make([]byte, 0, 64),
options: opts,
}
}
// Bytes returns the encoded bytes.
func (e *Encoder) Bytes() []byte {
return e.bytes
}
// Encode encodes v into BER-TLV format.
func (e *Encoder) Encode(v interface{}) error {
if v == nil {
return &EncodeError{Message: "cannot encode nil value"}
}
return e.encodeValue(reflect.ValueOf(v))
}
// encodeValue is the main dispatcher for encoding different value types
func (e *Encoder) encodeValue(v reflect.Value) error {
// Check for custom marshaler first
if v.CanInterface() {
if m, ok := v.Interface().(Marshaler); ok {
return e.encodeWithMarshaler(m)
}
}
// Handle pointers by dereferencing
if v.Kind() == reflect.Ptr {
return e.encodePointer(v)
}
switch v.Kind() {
case reflect.Struct:
return e.encodeStruct(v)
case reflect.Slice:
return e.encodeSlice(v)
case reflect.Interface:
return e.encodeInterface(v)
default:
return e.encodePrimitive(v)
}
}
// encodeWithMarshaler uses the Marshaler interface
func (e *Encoder) encodeWithMarshaler(m Marshaler) error {
data, err := m.MarshalBERTLV()
if err != nil {
return fmt.Errorf("custom marshaler: %w", err)
}
e.bytes = append(e.bytes, data...)
return nil
}
// encodePointer handles pointer values
func (e *Encoder) encodePointer(v reflect.Value) error {
if v.IsNil() {
return nil // Skip nil pointers
}
return e.encodeValue(v.Elem())
}
// encodeInterface handles interface{} values
func (e *Encoder) encodeInterface(v reflect.Value) error {
if v.IsNil() {
return nil
}
return e.encodeValue(v.Elem())
}
// encodeStruct encodes a struct with all its tagged fields
func (e *Encoder) encodeStruct(v reflect.Value) error {
fields := cachedTypeFields(v.Type())
for _, field := range fields.fields {
if err := e.encodeStructField(v, field); err != nil {
return err
}
}
return nil
}
// encodeStructField encodes a single struct field
func (e *Encoder) encodeStructField(structValue reflect.Value, field structField) error {
fieldValue := structValue.FieldByIndex(field.index)
if field.omitEmpty && isZeroValue(fieldValue) {
return nil
}
// For non-byte slices of structs, encode each element as its own TLV
if fieldValue.Kind() == reflect.Slice && fieldValue.Type().Elem().Kind() != reflect.Uint8 {
return e.encodeSliceField(fieldValue, field)
}
valueBytes, err := e.encodeFieldValue(fieldValue)
if err != nil {
return &EncodeError{
Type: fieldValue.Type(),
Field: field.name,
Message: err.Error(),
}
}
tagInfo := field.tagInfo
// Auto-set constructed bit for struct types
if shouldBeConstructed(fieldValue.Type()) {
tagInfo.Constructed = true
}
e.writeTagLengthValue(tagInfo, valueBytes)
return nil
}
// encodeSliceField encodes a slice field as repeated TLVs (one per element).
// The constructed bit is derived from the element type, since each emitted TLV
// carries a single element's value — not the slice as a whole.
func (e *Encoder) encodeSliceField(v reflect.Value, field structField) error {
tagInfo := field.tagInfo
if shouldBeConstructed(v.Type().Elem()) {
tagInfo.Constructed = true
}
for i := 0; i < v.Len(); i++ {
elem := v.Index(i)
valueBytes, err := e.encodeFieldValue(elem)
if err != nil {
return &EncodeError{
Type: elem.Type(),
Field: field.name,
Message: fmt.Sprintf("encoding slice element %d: %s", i, err.Error()),
}
}
e.writeTagLengthValue(tagInfo, valueBytes)
}
return nil
}
// encodeFieldValue encodes a field's value into bytes
func (e *Encoder) encodeFieldValue(v reflect.Value) ([]byte, error) {
tempEncoder := &Encoder{
bytes: make([]byte, 0),
options: e.options,
}
err := tempEncoder.encodeValue(v)
return tempEncoder.bytes, err
}
// writeTagLengthValue writes TLV to the encoder's buffer
func (e *Encoder) writeTagLengthValue(tagInfo TagInfo, valueBytes []byte) {
e.writeTag(tagInfo)
e.writeLength(len(valueBytes))
e.bytes = append(e.bytes, valueBytes...)
}
// writeTag encodes and writes a tag
func (e *Encoder) writeTag(tagInfo TagInfo) {
firstByte := byte(tagInfo.Class)
if tagInfo.Constructed {
firstByte |= 0x20
}
if tagInfo.Number >= 31 {
e.writeLongFormTag(firstByte, tagInfo.Number)
} else {
e.bytes = append(e.bytes, firstByte|byte(tagInfo.Number))
}
}
// writeLongFormTag writes a long form tag
func (e *Encoder) writeLongFormTag(firstByte byte, tagNum uint16) {
e.bytes = append(e.bytes, firstByte|0x1f)
e.bytes = appendBase128Int(e.bytes, tagNum)
}
// writeLength encodes and writes a length
func (e *Encoder) writeLength(length int) {
if length < 128 {
e.bytes = append(e.bytes, byte(length))
return
}
numBytes := calculateLengthBytes(length)
e.bytes = append(e.bytes, 0x80|byte(numBytes))
for i := numBytes; i > 0; i-- {
e.bytes = append(e.bytes, byte(length>>uint((i-1)*8)))
}
}
// encodeSlice handles slice encoding
func (e *Encoder) encodeSlice(v reflect.Value) error {
if v.Type().Elem().Kind() == reflect.Uint8 {
return e.encodePrimitive(v) // []byte as primitive
}
// Encode each slice element
for i := 0; i < v.Len(); i++ {
if err := e.encodeValue(v.Index(i)); err != nil {
return fmt.Errorf("encoding slice element %d: %w", i, err)
}
}
return nil
}
// encodePrimitive handles primitive value encoding (value bytes only, no TLV)
func (e *Encoder) encodePrimitive(v reflect.Value) error {
// Check for Marshaler interface first, even for primitives
if v.CanInterface() {
if m, ok := v.Interface().(Marshaler); ok {
return e.encodeWithMarshaler(m)
}
}
valueBytes, err := e.getPrimitiveBytes(v)
if err != nil {
return err
}
e.bytes = append(e.bytes, valueBytes...)
return nil
}
// getPrimitiveBytes converts a primitive value to bytes
func (e *Encoder) getPrimitiveBytes(v reflect.Value) ([]byte, error) {
switch v.Kind() {
case reflect.String:
return []byte(v.String()), nil
case reflect.Bool:
return e.encodeBool(v.Bool()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return encodeSignedInteger(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return encodeUnsignedInteger(v.Uint()), nil
case reflect.Slice:
return e.encodeByteSlice(v)
default:
return nil, &EncodeError{
Type: v.Type(),
Message: fmt.Sprintf("unsupported type %s", v.Kind()),
}
}
}
// encodeBool converts a boolean to bytes
func (e *Encoder) encodeBool(b bool) []byte {
if b {
return []byte{0x01}
}
return []byte{0x00}
}
// encodeByteSlice handles []byte encoding
func (e *Encoder) encodeByteSlice(v reflect.Value) ([]byte, error) {
if v.Type().Elem().Kind() != reflect.Uint8 {
return nil, &EncodeError{
Type: v.Type(),
Message: "unsupported slice type for primitive encoding",
}
}
if v.IsNil() {
return []byte{}, nil
}
return v.Bytes(), nil
}
var marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
// shouldBeConstructed determines if a type should be encoded as constructed.
// Types implementing Marshaler handle their own encoding and are not forced to constructed.
func shouldBeConstructed(t reflect.Type) bool {
// Check both value and pointer receiver
if t.Implements(marshalerType) || reflect.PointerTo(t).Implements(marshalerType) {
return false
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
switch t.Kind() {
case reflect.Struct:
return true
case reflect.Slice:
return !isByteSlice(t)
case reflect.Interface:
return true
default:
return false
}
}
// isByteSlice reports whether t is a slice of bytes (named or not),
// e.g. []byte or `type AID []byte`.
func isByteSlice(t reflect.Type) bool {
return t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8
}
// isZeroValue checks if a value is the zero value for its type
func isZeroValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.String:
return v.String() == ""
case reflect.Slice, reflect.Map:
return v.IsNil() || v.Len() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Struct:
return isZeroStruct(v)
default:
return false
}
}
// isZeroStruct checks if all struct fields are zero values
func isZeroStruct(v reflect.Value) bool {
for i := 0; i < v.NumField(); i++ {
if !isZeroValue(v.Field(i)) {
return false
}
}
return true
}
// Integer encoding functions
// encodeSignedInteger encodes a signed integer using minimal two's complement representation
func encodeSignedInteger(n int64) []byte {
if n == 0 {
return []byte{0}
}
bytes := make([]byte, 0, 8)
negative := n < 0
// Convert to bytes
for n != 0 && n != -1 {
bytes = append([]byte{byte(n)}, bytes...)
n >>= 8
}
return addSignPadding(bytes, negative)
}
// addSignPadding adds necessary padding bytes for proper sign representation
func addSignPadding(bytes []byte, negative bool) []byte {
if len(bytes) == 0 {
if negative {
return []byte{0xFF}
}
return []byte{0x00}
}
if negative && bytes[0]&0x80 == 0 {
// Negative number but high bit is 0, need 0xFF padding
return append([]byte{0xFF}, bytes...)
}
if !negative && bytes[0]&0x80 != 0 {
// Positive number but high bit is 1, need 0x00 padding
return append([]byte{0x00}, bytes...)
}
return bytes
}
// encodeUnsignedInteger encodes an unsigned integer
func encodeUnsignedInteger(n uint64) []byte {
if n == 0 {
return []byte{0}
}
bytes := make([]byte, 0, 8)
for n > 0 {
bytes = append([]byte{byte(n)}, bytes...)
n >>= 8
}
// Add padding byte if high bit is set (to distinguish from negative)
if len(bytes) > 0 && bytes[0]&0x80 != 0 {
bytes = append([]byte{0x00}, bytes...)
}
return bytes
}
// Utility functions
// appendBase128Int appends a base-128 encoded integer
func appendBase128Int(dst []byte, n uint16) []byte {
if n == 0 {
return append(dst, 0)
}
numBytes := calculateBase128Bytes(n)
for i := numBytes - 1; i >= 0; i-- {
b := byte((n >> uint(i*7)) & 0x7F)
if i != 0 {
b |= 0x80 // Set continuation bit
}
dst = append(dst, b)
}
return dst
}
// calculateBase128Bytes calculates how many bytes needed for base-128 encoding
func calculateBase128Bytes(n uint16) int {
if n == 0 {
return 1
}
bytes := 0
for n > 0 {
bytes++
n >>= 7
}
return bytes
}
// calculateLengthBytes returns the number of bytes needed to encode a length
func calculateLengthBytes(n int) uint8 {
if n < 128 {
return 1
}
bytes := uint8(0)
for n > 0 {
bytes++
n >>= 8
}
return bytes
}
// MarshalWithTag returns the BER-TLV encoding of v wrapped in a TLV with the given tag.
func MarshalWithTag(v interface{}, tagStr string) ([]byte, error) {
return MarshalWithTagAndOptions(v, tagStr, DefaultOptions())
}
// MarshalWithTagAndOptions returns the BER-TLV encoding of v wrapped in a TLV with the given tag and custom options.
func MarshalWithTagAndOptions(v interface{}, tagStr string, opts Options) ([]byte, error) {
tagInfo, _, err := parseGoTag(tagStr)
if err != nil {
return nil, fmt.Errorf("parsing top-level tag: %w", err)
}
e := NewEncoderWithOptions(opts)
if err := e.EncodeWithTag(v, tagInfo); err != nil {
return nil, err
}
return e.Bytes(), nil
}
// EncodeWithTag encodes v into BER-TLV format wrapped in a TLV with the given tag.
func (e *Encoder) EncodeWithTag(v interface{}, tagInfo TagInfo) error {
if v == nil {
return &EncodeError{Message: "cannot encode nil value"}
}
// Encode the value content
tempEncoder := &Encoder{bytes: make([]byte, 0), options: e.options}
if err := tempEncoder.encodeValue(reflect.ValueOf(v)); err != nil {
return err
}
// Write TLV with specified tag
e.writeTagLengthValue(tagInfo, tempEncoder.bytes)
return nil
}