-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
binary.go
59 lines (47 loc) · 1.3 KB
/
binary.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
package httpsfv
import (
"encoding/base64"
"errors"
"strings"
)
// ErrInvalidBinaryFormat is returned when the binary format is invalid.
var ErrInvalidBinaryFormat = errors.New("invalid binary format")
// marshalBinary serializes as defined in
// https://httpwg.org/specs/rfc8941.html#ser-binary.
func marshalBinary(b *strings.Builder, bs []byte) error {
if err := b.WriteByte(':'); err != nil {
return err
}
buf := make([]byte, base64.StdEncoding.EncodedLen(len(bs)))
base64.StdEncoding.Encode(buf, bs)
if _, err := b.Write(buf); err != nil {
return err
}
return b.WriteByte(':')
}
// parseBinary parses as defined in
// https://httpwg.org/specs/rfc8941.html#parse-binary.
func parseBinary(s *scanner) ([]byte, error) {
if s.eof() || s.data[s.off] != ':' {
return nil, &UnmarshalError{s.off, ErrInvalidBinaryFormat}
}
s.off++
start := s.off
for !s.eof() {
c := s.data[s.off]
if c == ':' {
// base64decode
decoded, err := base64.StdEncoding.DecodeString(s.data[start:s.off])
if err != nil {
return nil, &UnmarshalError{s.off, err}
}
s.off++
return decoded, nil
}
if !isAlpha(c) && !isDigit(c) && c != '+' && c != '/' && c != '=' {
return nil, &UnmarshalError{s.off, ErrInvalidBinaryFormat}
}
s.off++
}
return nil, &UnmarshalError{s.off, ErrInvalidBinaryFormat}
}