-
Notifications
You must be signed in to change notification settings - Fork 0
/
length.go
99 lines (83 loc) · 1.69 KB
/
length.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
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
package jq
import (
"unicode/utf8"
"nikand.dev/go/cbor"
)
type (
Length struct {
CountRunes bool
}
)
func NewLength() Length { return Length{} }
func (f Length) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
if next {
return None, false, nil
}
te := NewTypeError(b.Reader().TagRaw(off))
if off < 0 {
switch off {
case Zero, One:
return off, false, nil
case Null, EmptyString, EmptyArray:
return Zero, false, nil
default:
return off, false, te
}
}
tag, sub, l, _, _ := b.Decoder.Tag(b.Buf(off))
switch tag {
case cbor.Int:
res = off
case cbor.Neg:
v := b.Reader().Unsigned(off)
res = b.Writer().Uint64(v)
case cbor.Bytes:
res = b.Writer().Int(int(sub))
case cbor.String:
if f.CountRunes {
s := b.Reader().Bytes(off)
res = b.Writer().Int(utf8.RuneCount(s))
} else {
res = b.Writer().Int(int(sub))
}
case cbor.Array, cbor.Map:
res = b.Writer().Int(l)
case cbor.Simple:
switch sub {
case cbor.Null:
res = Zero
case cbor.Float8:
if b.B[off+1]&0x80 == 0 {
res = off
break
}
res = b.Writer().Off()
f := b.B[off+1]
if int8(f) == -128 {
b.B = append(b.B, byte(cbor.Simple|cbor.Float32), 0x43, 0x00, 0x00, 0x00)
} else {
b.B = append(b.B, b.B[off], -f)
}
case cbor.Float16, cbor.Float32, cbor.Float64:
if b.B[off+1]&0x80 == 0 {
res = off
break
}
res = b.Writer().Off()
sz := Off(1 + 1<<(sub-cbor.Float8))
b.B = append(b.B, b.B[off:off+sz]...)
b.B[res+1] &^= 0x80
default:
return off, false, te
}
default:
return off, false, te
}
return res, false, nil
}
func (f Length) String() string {
if f.CountRunes {
return "length_utf8"
}
return "length"
}