-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
string.go
89 lines (72 loc) · 1.67 KB
/
string.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
package httpsfv
import (
"errors"
"io"
"strings"
"unicode"
)
// ErrInvalidStringFormat is returned when a string format is invalid.
var ErrInvalidStringFormat = errors.New("invalid string format")
// marshalSFV serializes as defined in
// https://httpwg.org/specs/rfc8941.html#ser-string.
func marshalString(b io.ByteWriter, s string) error {
if err := b.WriteByte('"'); err != nil {
return err
}
for i := 0; i < len(s); i++ {
if s[i] <= '\u001F' || s[i] >= unicode.MaxASCII {
return ErrInvalidStringFormat
}
switch s[i] {
case '"', '\\':
if err := b.WriteByte('\\'); err != nil {
return err
}
}
if err := b.WriteByte(s[i]); err != nil {
return err
}
}
if err := b.WriteByte('"'); err != nil {
return err
}
return nil
}
// parseString parses as defined in
// https://httpwg.org/specs/rfc8941.html#parse-string.
func parseString(s *scanner) (string, error) {
if s.eof() || s.data[s.off] != '"' {
return "", &UnmarshalError{s.off, ErrInvalidStringFormat}
}
s.off++
var b strings.Builder
for !s.eof() {
c := s.data[s.off]
s.off++
switch c {
case '\\':
if s.eof() {
return "", &UnmarshalError{s.off, ErrInvalidStringFormat}
}
n := s.data[s.off]
if n != '"' && n != '\\' {
return "", &UnmarshalError{s.off, ErrInvalidStringFormat}
}
s.off++
if err := b.WriteByte(n); err != nil {
return "", err
}
continue
case '"':
return b.String(), nil
default:
if c <= '\u001F' || c >= unicode.MaxASCII {
return "", &UnmarshalError{s.off, ErrInvalidStringFormat}
}
if err := b.WriteByte(c); err != nil {
return "", err
}
}
}
return "", &UnmarshalError{s.off, ErrInvalidStringFormat}
}