codekingpro commited on
Commit
bd21366
·
verified ·
1 Parent(s): dadc45e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. go/src/arena/arena.go +108 -0
  2. go/src/arena/arena_test.go +42 -0
  3. go/src/bufio/bufio.go +842 -0
  4. go/src/bufio/bufio_test.go +1999 -0
  5. go/src/bufio/example_test.go +200 -0
  6. go/src/bufio/export_test.go +29 -0
  7. go/src/bufio/net_test.go +96 -0
  8. go/src/bufio/scan.go +427 -0
  9. go/src/bufio/scan_test.go +596 -0
  10. go/src/builtin/builtin.go +319 -0
  11. go/src/bytes/boundary_test.go +115 -0
  12. go/src/bytes/buffer.go +500 -0
  13. go/src/bytes/buffer_test.go +781 -0
  14. go/src/bytes/bytes.go +1415 -0
  15. go/src/bytes/bytes_js_wasm_test.go +21 -0
  16. go/src/bytes/bytes_test.go +2501 -0
  17. go/src/bytes/compare_test.go +296 -0
  18. go/src/bytes/example_test.go +720 -0
  19. go/src/bytes/export_test.go +8 -0
  20. go/src/bytes/iter.go +137 -0
  21. go/src/bytes/iter_test.go +56 -0
  22. go/src/bytes/reader.go +159 -0
  23. go/src/bytes/reader_test.go +319 -0
  24. go/src/cmd/README.vendor +2 -0
  25. go/src/cmd/go.mod +21 -0
  26. go/src/cmd/go.sum +28 -0
  27. go/src/cmp/cmp.go +77 -0
  28. go/src/cmp/cmp_test.go +202 -0
  29. go/src/context/afterfunc_test.go +141 -0
  30. go/src/context/benchmark_test.go +210 -0
  31. go/src/context/context.go +806 -0
  32. go/src/context/context_test.go +297 -0
  33. go/src/context/example_test.go +263 -0
  34. go/src/context/net_test.go +21 -0
  35. go/src/context/x_test.go +1198 -0
  36. go/src/crypto/crypto.go +273 -0
  37. go/src/crypto/crypto_test.go +143 -0
  38. go/src/crypto/issue21104_test.go +61 -0
  39. go/src/crypto/purego_test.go +67 -0
  40. go/src/embed/embed.go +436 -0
  41. go/src/embed/example_test.go +23 -0
  42. go/src/encoding/encoding.go +78 -0
  43. go/src/errors/errors.go +90 -0
  44. go/src/errors/errors_test.go +33 -0
  45. go/src/errors/example_test.go +238 -0
  46. go/src/errors/join.go +63 -0
  47. go/src/errors/join_test.go +76 -0
  48. go/src/errors/wrap.go +209 -0
  49. go/src/errors/wrap_test.go +438 -0
  50. go/src/expvar/expvar.go +417 -0
go/src/arena/arena.go ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build goexperiment.arenas
6
+
7
+ /*
8
+ The arena package provides the ability to allocate memory for a collection
9
+ of Go values and free that space manually all at once, safely. The purpose
10
+ of this functionality is to improve efficiency: manually freeing memory
11
+ before a garbage collection delays that cycle. Less frequent cycles means
12
+ the CPU cost of the garbage collector is incurred less frequently.
13
+
14
+ This functionality in this package is mostly captured in the Arena type.
15
+ Arenas allocate large chunks of memory for Go values, so they're likely to
16
+ be inefficient for allocating only small amounts of small Go values. They're
17
+ best used in bulk, on the order of MiB of memory allocated on each use.
18
+
19
+ Note that by allowing for this limited form of manual memory allocation
20
+ that use-after-free bugs are possible with regular Go values. This package
21
+ limits the impact of these use-after-free bugs by preventing reuse of freed
22
+ memory regions until the garbage collector is able to determine that it is
23
+ safe. Typically, a use-after-free bug will result in a fault and a helpful
24
+ error message, but this package reserves the right to not force a fault on
25
+ freed memory. That means a valid implementation of this package is to just
26
+ allocate all memory the way the runtime normally would, and in fact, it
27
+ reserves the right to occasionally do so for some Go values.
28
+ */
29
+ package arena
30
+
31
+ import (
32
+ "internal/reflectlite"
33
+ "unsafe"
34
+ )
35
+
36
+ // Arena represents a collection of Go values allocated and freed together.
37
+ // Arenas are useful for improving efficiency as they may be freed back to
38
+ // the runtime manually, though any memory obtained from freed arenas must
39
+ // not be accessed once that happens. An Arena is automatically freed once
40
+ // it is no longer referenced, so it must be kept alive (see runtime.KeepAlive)
41
+ // until any memory allocated from it is no longer needed.
42
+ //
43
+ // An Arena must never be used concurrently by multiple goroutines.
44
+ type Arena struct {
45
+ a unsafe.Pointer
46
+ }
47
+
48
+ // NewArena allocates a new arena.
49
+ func NewArena() *Arena {
50
+ return &Arena{a: runtime_arena_newArena()}
51
+ }
52
+
53
+ // Free frees the arena (and all objects allocated from the arena) so that
54
+ // memory backing the arena can be reused fairly quickly without garbage
55
+ // collection overhead. Applications must not call any method on this
56
+ // arena after it has been freed.
57
+ func (a *Arena) Free() {
58
+ runtime_arena_arena_Free(a.a)
59
+ a.a = nil
60
+ }
61
+
62
+ // New creates a new *T in the provided arena. The *T must not be used after
63
+ // the arena is freed. Accessing the value after free may result in a fault,
64
+ // but this fault is also not guaranteed.
65
+ func New[T any](a *Arena) *T {
66
+ return runtime_arena_arena_New(a.a, reflectlite.TypeOf((*T)(nil))).(*T)
67
+ }
68
+
69
+ // MakeSlice creates a new []T with the provided capacity and length. The []T must
70
+ // not be used after the arena is freed. Accessing the underlying storage of the
71
+ // slice after free may result in a fault, but this fault is also not guaranteed.
72
+ func MakeSlice[T any](a *Arena, len, cap int) []T {
73
+ var sl []T
74
+ runtime_arena_arena_Slice(a.a, &sl, cap)
75
+ return sl[:len]
76
+ }
77
+
78
+ // Clone makes a shallow copy of the input value that is no longer bound to any
79
+ // arena it may have been allocated from, returning the copy. If it was not
80
+ // allocated from an arena, it is returned untouched. This function is useful
81
+ // to more easily let an arena-allocated value out-live its arena.
82
+ // T must be a pointer, a slice, or a string, otherwise this function will panic.
83
+ func Clone[T any](s T) T {
84
+ return runtime_arena_heapify(s).(T)
85
+ }
86
+
87
+ //go:linkname reflect_arena_New reflect.arena_New
88
+ func reflect_arena_New(a *Arena, typ any) any {
89
+ return runtime_arena_arena_New(a.a, typ)
90
+ }
91
+
92
+ //go:linkname runtime_arena_newArena
93
+ func runtime_arena_newArena() unsafe.Pointer
94
+
95
+ //go:linkname runtime_arena_arena_New
96
+ func runtime_arena_arena_New(arena unsafe.Pointer, typ any) any
97
+
98
+ // Mark as noescape to avoid escaping the slice header.
99
+ //
100
+ //go:noescape
101
+ //go:linkname runtime_arena_arena_Slice
102
+ func runtime_arena_arena_Slice(arena unsafe.Pointer, slice any, cap int)
103
+
104
+ //go:linkname runtime_arena_arena_Free
105
+ func runtime_arena_arena_Free(arena unsafe.Pointer)
106
+
107
+ //go:linkname runtime_arena_heapify
108
+ func runtime_arena_heapify(any) any
go/src/arena/arena_test.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build goexperiment.arenas
6
+
7
+ package arena_test
8
+
9
+ import (
10
+ "arena"
11
+ "testing"
12
+ )
13
+
14
+ type T1 struct {
15
+ n int
16
+ }
17
+ type T2 [1 << 20]byte // 1MiB
18
+
19
+ func TestSmoke(t *testing.T) {
20
+ a := arena.NewArena()
21
+ defer a.Free()
22
+
23
+ tt := arena.New[T1](a)
24
+ tt.n = 1
25
+
26
+ ts := arena.MakeSlice[T1](a, 99, 100)
27
+ if len(ts) != 99 {
28
+ t.Errorf("Slice() len = %d, want 99", len(ts))
29
+ }
30
+ if cap(ts) != 100 {
31
+ t.Errorf("Slice() cap = %d, want 100", cap(ts))
32
+ }
33
+ ts[1].n = 42
34
+ }
35
+
36
+ func TestSmokeLarge(t *testing.T) {
37
+ a := arena.NewArena()
38
+ defer a.Free()
39
+ for i := 0; i < 10*64; i++ {
40
+ _ = arena.New[T2](a)
41
+ }
42
+ }
go/src/bufio/bufio.go ADDED
@@ -0,0 +1,842 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer
6
+ // object, creating another object (Reader or Writer) that also implements
7
+ // the interface but provides buffering and some help for textual I/O.
8
+ package bufio
9
+
10
+ import (
11
+ "bytes"
12
+ "errors"
13
+ "io"
14
+ "strings"
15
+ "unicode/utf8"
16
+ )
17
+
18
+ const (
19
+ defaultBufSize = 4096
20
+ )
21
+
22
+ var (
23
+ ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
24
+ ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
25
+ ErrBufferFull = errors.New("bufio: buffer full")
26
+ ErrNegativeCount = errors.New("bufio: negative count")
27
+ )
28
+
29
+ // Buffered input.
30
+
31
+ // Reader implements buffering for an io.Reader object.
32
+ // A new Reader is created by calling [NewReader] or [NewReaderSize];
33
+ // alternatively the zero value of a Reader may be used after calling [Reset]
34
+ // on it.
35
+ type Reader struct {
36
+ buf []byte
37
+ rd io.Reader // reader provided by the client
38
+ r, w int // buf read and write positions
39
+ err error
40
+ lastByte int // last byte read for UnreadByte; -1 means invalid
41
+ lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
42
+ }
43
+
44
+ const minReadBufferSize = 16
45
+ const maxConsecutiveEmptyReads = 100
46
+
47
+ // NewReaderSize returns a new [Reader] whose buffer has at least the specified
48
+ // size. If the argument io.Reader is already a [Reader] with large enough
49
+ // size, it returns the underlying [Reader].
50
+ func NewReaderSize(rd io.Reader, size int) *Reader {
51
+ // Is it already a Reader?
52
+ b, ok := rd.(*Reader)
53
+ if ok && len(b.buf) >= size {
54
+ return b
55
+ }
56
+ r := new(Reader)
57
+ r.reset(make([]byte, max(size, minReadBufferSize)), rd)
58
+ return r
59
+ }
60
+
61
+ // NewReader returns a new [Reader] whose buffer has the default size.
62
+ func NewReader(rd io.Reader) *Reader {
63
+ return NewReaderSize(rd, defaultBufSize)
64
+ }
65
+
66
+ // Size returns the size of the underlying buffer in bytes.
67
+ func (b *Reader) Size() int { return len(b.buf) }
68
+
69
+ // Reset discards any buffered data, resets all state, and switches
70
+ // the buffered reader to read from r.
71
+ // Calling Reset on the zero value of [Reader] initializes the internal buffer
72
+ // to the default size.
73
+ // Calling b.Reset(b) (that is, resetting a [Reader] to itself) does nothing.
74
+ func (b *Reader) Reset(r io.Reader) {
75
+ // If a Reader r is passed to NewReader, NewReader will return r.
76
+ // Different layers of code may do that, and then later pass r
77
+ // to Reset. Avoid infinite recursion in that case.
78
+ if b == r {
79
+ return
80
+ }
81
+ if b.buf == nil {
82
+ b.buf = make([]byte, defaultBufSize)
83
+ }
84
+ b.reset(b.buf, r)
85
+ }
86
+
87
+ func (b *Reader) reset(buf []byte, r io.Reader) {
88
+ *b = Reader{
89
+ buf: buf,
90
+ rd: r,
91
+ lastByte: -1,
92
+ lastRuneSize: -1,
93
+ }
94
+ }
95
+
96
+ var errNegativeRead = errors.New("bufio: reader returned negative count from Read")
97
+
98
+ // fill reads a new chunk into the buffer.
99
+ func (b *Reader) fill() {
100
+ // Slide existing data to beginning.
101
+ if b.r > 0 {
102
+ copy(b.buf, b.buf[b.r:b.w])
103
+ b.w -= b.r
104
+ b.r = 0
105
+ }
106
+
107
+ if b.w >= len(b.buf) {
108
+ panic("bufio: tried to fill full buffer")
109
+ }
110
+
111
+ // Read new data: try a limited number of times.
112
+ for i := maxConsecutiveEmptyReads; i > 0; i-- {
113
+ n, err := b.rd.Read(b.buf[b.w:])
114
+ if n < 0 {
115
+ panic(errNegativeRead)
116
+ }
117
+ b.w += n
118
+ if err != nil {
119
+ b.err = err
120
+ return
121
+ }
122
+ if n > 0 {
123
+ return
124
+ }
125
+ }
126
+ b.err = io.ErrNoProgress
127
+ }
128
+
129
+ func (b *Reader) readErr() error {
130
+ err := b.err
131
+ b.err = nil
132
+ return err
133
+ }
134
+
135
+ // Peek returns the next n bytes without advancing the reader. The bytes stop
136
+ // being valid at the next read call. If necessary, Peek will read more bytes
137
+ // into the buffer in order to make n bytes available. If Peek returns fewer
138
+ // than n bytes, it also returns an error explaining why the read is short.
139
+ // The error is [ErrBufferFull] if n is larger than b's buffer size.
140
+ //
141
+ // Calling Peek prevents a [Reader.UnreadByte] or [Reader.UnreadRune] call from succeeding
142
+ // until the next read operation.
143
+ func (b *Reader) Peek(n int) ([]byte, error) {
144
+ if n < 0 {
145
+ return nil, ErrNegativeCount
146
+ }
147
+
148
+ b.lastByte = -1
149
+ b.lastRuneSize = -1
150
+
151
+ for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
152
+ b.fill() // b.w-b.r < len(b.buf) => buffer is not full
153
+ }
154
+
155
+ if n > len(b.buf) {
156
+ return b.buf[b.r:b.w], ErrBufferFull
157
+ }
158
+
159
+ // 0 <= n <= len(b.buf)
160
+ var err error
161
+ if avail := b.w - b.r; avail < n {
162
+ // not enough data in buffer
163
+ n = avail
164
+ err = b.readErr()
165
+ if err == nil {
166
+ err = ErrBufferFull
167
+ }
168
+ }
169
+ return b.buf[b.r : b.r+n], err
170
+ }
171
+
172
+ // Discard skips the next n bytes, returning the number of bytes discarded.
173
+ //
174
+ // If Discard skips fewer than n bytes, it also returns an error.
175
+ // If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without
176
+ // reading from the underlying io.Reader.
177
+ func (b *Reader) Discard(n int) (discarded int, err error) {
178
+ if n < 0 {
179
+ return 0, ErrNegativeCount
180
+ }
181
+ if n == 0 {
182
+ return
183
+ }
184
+
185
+ b.lastByte = -1
186
+ b.lastRuneSize = -1
187
+
188
+ remain := n
189
+ for {
190
+ skip := b.Buffered()
191
+ if skip == 0 {
192
+ b.fill()
193
+ skip = b.Buffered()
194
+ }
195
+ if skip > remain {
196
+ skip = remain
197
+ }
198
+ b.r += skip
199
+ remain -= skip
200
+ if remain == 0 {
201
+ return n, nil
202
+ }
203
+ if b.err != nil {
204
+ return n - remain, b.readErr()
205
+ }
206
+ }
207
+ }
208
+
209
+ // Read reads data into p.
210
+ // It returns the number of bytes read into p.
211
+ // The bytes are taken from at most one Read on the underlying [Reader],
212
+ // hence n may be less than len(p).
213
+ // To read exactly len(p) bytes, use io.ReadFull(b, p).
214
+ // If the underlying [Reader] can return a non-zero count with io.EOF,
215
+ // then this Read method can do so as well; see the [io.Reader] docs.
216
+ func (b *Reader) Read(p []byte) (n int, err error) {
217
+ n = len(p)
218
+ if n == 0 {
219
+ if b.Buffered() > 0 {
220
+ return 0, nil
221
+ }
222
+ return 0, b.readErr()
223
+ }
224
+ if b.r == b.w {
225
+ if b.err != nil {
226
+ return 0, b.readErr()
227
+ }
228
+ if len(p) >= len(b.buf) {
229
+ // Large read, empty buffer.
230
+ // Read directly into p to avoid copy.
231
+ n, b.err = b.rd.Read(p)
232
+ if n < 0 {
233
+ panic(errNegativeRead)
234
+ }
235
+ if n > 0 {
236
+ b.lastByte = int(p[n-1])
237
+ b.lastRuneSize = -1
238
+ }
239
+ return n, b.readErr()
240
+ }
241
+ // One read.
242
+ // Do not use b.fill, which will loop.
243
+ b.r = 0
244
+ b.w = 0
245
+ n, b.err = b.rd.Read(b.buf)
246
+ if n < 0 {
247
+ panic(errNegativeRead)
248
+ }
249
+ if n == 0 {
250
+ return 0, b.readErr()
251
+ }
252
+ b.w += n
253
+ }
254
+
255
+ // copy as much as we can
256
+ // Note: if the slice panics here, it is probably because
257
+ // the underlying reader returned a bad count. See issue 49795.
258
+ n = copy(p, b.buf[b.r:b.w])
259
+ b.r += n
260
+ b.lastByte = int(b.buf[b.r-1])
261
+ b.lastRuneSize = -1
262
+ return n, nil
263
+ }
264
+
265
+ // ReadByte reads and returns a single byte.
266
+ // If no byte is available, returns an error.
267
+ func (b *Reader) ReadByte() (byte, error) {
268
+ b.lastRuneSize = -1
269
+ for b.r == b.w {
270
+ if b.err != nil {
271
+ return 0, b.readErr()
272
+ }
273
+ b.fill() // buffer is empty
274
+ }
275
+ c := b.buf[b.r]
276
+ b.r++
277
+ b.lastByte = int(c)
278
+ return c, nil
279
+ }
280
+
281
+ // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
282
+ //
283
+ // UnreadByte returns an error if the most recent method called on the
284
+ // [Reader] was not a read operation. Notably, [Reader.Peek], [Reader.Discard], and [Reader.WriteTo] are not
285
+ // considered read operations.
286
+ func (b *Reader) UnreadByte() error {
287
+ if b.lastByte < 0 || b.r == 0 && b.w > 0 {
288
+ return ErrInvalidUnreadByte
289
+ }
290
+ // b.r > 0 || b.w == 0
291
+ if b.r > 0 {
292
+ b.r--
293
+ } else {
294
+ // b.r == 0 && b.w == 0
295
+ b.w = 1
296
+ }
297
+ b.buf[b.r] = byte(b.lastByte)
298
+ b.lastByte = -1
299
+ b.lastRuneSize = -1
300
+ return nil
301
+ }
302
+
303
+ // ReadRune reads a single UTF-8 encoded Unicode character and returns the
304
+ // rune and its size in bytes. If the encoded rune is invalid, it consumes one byte
305
+ // and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
306
+ func (b *Reader) ReadRune() (r rune, size int, err error) {
307
+ for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil && b.w-b.r < len(b.buf) {
308
+ b.fill() // b.w-b.r < len(buf) => buffer is not full
309
+ }
310
+ b.lastRuneSize = -1
311
+ if b.r == b.w {
312
+ return 0, 0, b.readErr()
313
+ }
314
+ r, size = utf8.DecodeRune(b.buf[b.r:b.w])
315
+ b.r += size
316
+ b.lastByte = int(b.buf[b.r-1])
317
+ b.lastRuneSize = size
318
+ return r, size, nil
319
+ }
320
+
321
+ // UnreadRune unreads the last rune. If the most recent method called on
322
+ // the [Reader] was not a [Reader.ReadRune], [Reader.UnreadRune] returns an error. (In this
323
+ // regard it is stricter than [Reader.UnreadByte], which will unread the last byte
324
+ // from any read operation.)
325
+ func (b *Reader) UnreadRune() error {
326
+ if b.lastRuneSize < 0 || b.r < b.lastRuneSize {
327
+ return ErrInvalidUnreadRune
328
+ }
329
+ b.r -= b.lastRuneSize
330
+ b.lastByte = -1
331
+ b.lastRuneSize = -1
332
+ return nil
333
+ }
334
+
335
+ // Buffered returns the number of bytes that can be read from the current buffer.
336
+ func (b *Reader) Buffered() int { return b.w - b.r }
337
+
338
+ // ReadSlice reads until the first occurrence of delim in the input,
339
+ // returning a slice pointing at the bytes in the buffer.
340
+ // The bytes stop being valid at the next read.
341
+ // If ReadSlice encounters an error before finding a delimiter,
342
+ // it returns all the data in the buffer and the error itself (often io.EOF).
343
+ // ReadSlice fails with error [ErrBufferFull] if the buffer fills without a delim.
344
+ // Because the data returned from ReadSlice will be overwritten
345
+ // by the next I/O operation, most clients should use
346
+ // [Reader.ReadBytes] or ReadString instead.
347
+ // ReadSlice returns err != nil if and only if line does not end in delim.
348
+ func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
349
+ s := 0 // search start index
350
+ for {
351
+ // Search buffer.
352
+ if i := bytes.IndexByte(b.buf[b.r+s:b.w], delim); i >= 0 {
353
+ i += s
354
+ line = b.buf[b.r : b.r+i+1]
355
+ b.r += i + 1
356
+ break
357
+ }
358
+
359
+ // Pending error?
360
+ if b.err != nil {
361
+ line = b.buf[b.r:b.w]
362
+ b.r = b.w
363
+ err = b.readErr()
364
+ break
365
+ }
366
+
367
+ // Buffer full?
368
+ if b.Buffered() >= len(b.buf) {
369
+ b.r = b.w
370
+ line = b.buf
371
+ err = ErrBufferFull
372
+ break
373
+ }
374
+
375
+ s = b.w - b.r // do not rescan area we scanned before
376
+
377
+ b.fill() // buffer is not full
378
+ }
379
+
380
+ // Handle last byte, if any.
381
+ if i := len(line) - 1; i >= 0 {
382
+ b.lastByte = int(line[i])
383
+ b.lastRuneSize = -1
384
+ }
385
+
386
+ return
387
+ }
388
+
389
+ // ReadLine is a low-level line-reading primitive. Most callers should use
390
+ // [Reader.ReadBytes]('\n') or [Reader.ReadString]('\n') instead or use a [Scanner].
391
+ //
392
+ // ReadLine tries to return a single line, not including the end-of-line bytes.
393
+ // If the line was too long for the buffer then isPrefix is set and the
394
+ // beginning of the line is returned. The rest of the line will be returned
395
+ // from future calls. isPrefix will be false when returning the last fragment
396
+ // of the line. The returned buffer is only valid until the next call to
397
+ // ReadLine. ReadLine either returns a non-nil line or it returns an error,
398
+ // never both.
399
+ //
400
+ // The text returned from ReadLine does not include the line end ("\r\n" or "\n").
401
+ // No indication or error is given if the input ends without a final line end.
402
+ // Calling [Reader.UnreadByte] after ReadLine will always unread the last byte read
403
+ // (possibly a character belonging to the line end) even if that byte is not
404
+ // part of the line returned by ReadLine.
405
+ func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
406
+ line, err = b.ReadSlice('\n')
407
+ if err == ErrBufferFull {
408
+ // Handle the case where "\r\n" straddles the buffer.
409
+ if len(line) > 0 && line[len(line)-1] == '\r' {
410
+ // Put the '\r' back on buf and drop it from line.
411
+ // Let the next call to ReadLine check for "\r\n".
412
+ if b.r == 0 {
413
+ // should be unreachable
414
+ panic("bufio: tried to rewind past start of buffer")
415
+ }
416
+ b.r--
417
+ line = line[:len(line)-1]
418
+ }
419
+ return line, true, nil
420
+ }
421
+
422
+ if len(line) == 0 {
423
+ if err != nil {
424
+ line = nil
425
+ }
426
+ return
427
+ }
428
+ err = nil
429
+
430
+ if line[len(line)-1] == '\n' {
431
+ drop := 1
432
+ if len(line) > 1 && line[len(line)-2] == '\r' {
433
+ drop = 2
434
+ }
435
+ line = line[:len(line)-drop]
436
+ }
437
+ return
438
+ }
439
+
440
+ // collectFragments reads until the first occurrence of delim in the input. It
441
+ // returns (slice of full buffers, remaining bytes before delim, total number
442
+ // of bytes in the combined first two elements, error).
443
+ // The complete result is equal to
444
+ // `bytes.Join(append(fullBuffers, finalFragment), nil)`, which has a
445
+ // length of `totalLen`. The result is structured in this way to allow callers
446
+ // to minimize allocations and copies.
447
+ func (b *Reader) collectFragments(delim byte) (fullBuffers [][]byte, finalFragment []byte, totalLen int, err error) {
448
+ var frag []byte
449
+ // Use ReadSlice to look for delim, accumulating full buffers.
450
+ for {
451
+ var e error
452
+ frag, e = b.ReadSlice(delim)
453
+ if e == nil { // got final fragment
454
+ break
455
+ }
456
+ if e != ErrBufferFull { // unexpected error
457
+ err = e
458
+ break
459
+ }
460
+
461
+ // Make a copy of the buffer.
462
+ buf := bytes.Clone(frag)
463
+ fullBuffers = append(fullBuffers, buf)
464
+ totalLen += len(buf)
465
+ }
466
+
467
+ totalLen += len(frag)
468
+ return fullBuffers, frag, totalLen, err
469
+ }
470
+
471
+ // ReadBytes reads until the first occurrence of delim in the input,
472
+ // returning a slice containing the data up to and including the delimiter.
473
+ // If ReadBytes encounters an error before finding a delimiter,
474
+ // it returns the data read before the error and the error itself (often io.EOF).
475
+ // ReadBytes returns err != nil if and only if the returned data does not end in
476
+ // delim.
477
+ // For simple uses, a Scanner may be more convenient.
478
+ func (b *Reader) ReadBytes(delim byte) ([]byte, error) {
479
+ full, frag, n, err := b.collectFragments(delim)
480
+ // Allocate new buffer to hold the full pieces and the fragment.
481
+ buf := make([]byte, n)
482
+ n = 0
483
+ // Copy full pieces and fragment in.
484
+ for i := range full {
485
+ n += copy(buf[n:], full[i])
486
+ }
487
+ copy(buf[n:], frag)
488
+ return buf, err
489
+ }
490
+
491
+ // ReadString reads until the first occurrence of delim in the input,
492
+ // returning a string containing the data up to and including the delimiter.
493
+ // If ReadString encounters an error before finding a delimiter,
494
+ // it returns the data read before the error and the error itself (often io.EOF).
495
+ // ReadString returns err != nil if and only if the returned data does not end in
496
+ // delim.
497
+ // For simple uses, a Scanner may be more convenient.
498
+ func (b *Reader) ReadString(delim byte) (string, error) {
499
+ full, frag, n, err := b.collectFragments(delim)
500
+ // Allocate new buffer to hold the full pieces and the fragment.
501
+ var buf strings.Builder
502
+ buf.Grow(n)
503
+ // Copy full pieces and fragment in.
504
+ for _, fb := range full {
505
+ buf.Write(fb)
506
+ }
507
+ buf.Write(frag)
508
+ return buf.String(), err
509
+ }
510
+
511
+ // WriteTo implements io.WriterTo.
512
+ // This may make multiple calls to the [Reader.Read] method of the underlying [Reader].
513
+ // If the underlying reader supports the [Reader.WriteTo] method,
514
+ // this calls the underlying [Reader.WriteTo] without buffering.
515
+ func (b *Reader) WriteTo(w io.Writer) (n int64, err error) {
516
+ b.lastByte = -1
517
+ b.lastRuneSize = -1
518
+
519
+ if b.r < b.w {
520
+ n, err = b.writeBuf(w)
521
+ if err != nil {
522
+ return
523
+ }
524
+ }
525
+
526
+ if r, ok := b.rd.(io.WriterTo); ok {
527
+ m, err := r.WriteTo(w)
528
+ n += m
529
+ return n, err
530
+ }
531
+
532
+ if w, ok := w.(io.ReaderFrom); ok {
533
+ m, err := w.ReadFrom(b.rd)
534
+ n += m
535
+ return n, err
536
+ }
537
+
538
+ if b.w-b.r < len(b.buf) {
539
+ b.fill() // buffer not full
540
+ }
541
+
542
+ for b.r < b.w {
543
+ // b.r < b.w => buffer is not empty
544
+ m, err := b.writeBuf(w)
545
+ n += m
546
+ if err != nil {
547
+ return n, err
548
+ }
549
+ b.fill() // buffer is empty
550
+ }
551
+
552
+ if b.err == io.EOF {
553
+ b.err = nil
554
+ }
555
+
556
+ return n, b.readErr()
557
+ }
558
+
559
+ var errNegativeWrite = errors.New("bufio: writer returned negative count from Write")
560
+
561
+ // writeBuf writes the [Reader]'s buffer to the writer.
562
+ func (b *Reader) writeBuf(w io.Writer) (int64, error) {
563
+ n, err := w.Write(b.buf[b.r:b.w])
564
+ if n < 0 {
565
+ panic(errNegativeWrite)
566
+ }
567
+ b.r += n
568
+ return int64(n), err
569
+ }
570
+
571
+ // buffered output
572
+
573
+ // Writer implements buffering for an [io.Writer] object.
574
+ // If an error occurs writing to a [Writer], no more data will be
575
+ // accepted and all subsequent writes, and [Writer.Flush], will return the error.
576
+ // After all data has been written, the client should call the
577
+ // [Writer.Flush] method to guarantee all data has been forwarded to
578
+ // the underlying [io.Writer].
579
+ type Writer struct {
580
+ err error
581
+ buf []byte
582
+ n int
583
+ wr io.Writer
584
+ }
585
+
586
+ // NewWriterSize returns a new [Writer] whose buffer has at least the specified
587
+ // size. If the argument io.Writer is already a [Writer] with large enough
588
+ // size, it returns the underlying [Writer].
589
+ func NewWriterSize(w io.Writer, size int) *Writer {
590
+ // Is it already a Writer?
591
+ b, ok := w.(*Writer)
592
+ if ok && len(b.buf) >= size {
593
+ return b
594
+ }
595
+ if size <= 0 {
596
+ size = defaultBufSize
597
+ }
598
+ return &Writer{
599
+ buf: make([]byte, size),
600
+ wr: w,
601
+ }
602
+ }
603
+
604
+ // NewWriter returns a new [Writer] whose buffer has the default size.
605
+ // If the argument io.Writer is already a [Writer] with large enough buffer size,
606
+ // it returns the underlying [Writer].
607
+ func NewWriter(w io.Writer) *Writer {
608
+ return NewWriterSize(w, defaultBufSize)
609
+ }
610
+
611
+ // Size returns the size of the underlying buffer in bytes.
612
+ func (b *Writer) Size() int { return len(b.buf) }
613
+
614
+ // Reset discards any unflushed buffered data, clears any error, and
615
+ // resets b to write its output to w.
616
+ // Calling Reset on the zero value of [Writer] initializes the internal buffer
617
+ // to the default size.
618
+ // Calling w.Reset(w) (that is, resetting a [Writer] to itself) does nothing.
619
+ func (b *Writer) Reset(w io.Writer) {
620
+ // If a Writer w is passed to NewWriter, NewWriter will return w.
621
+ // Different layers of code may do that, and then later pass w
622
+ // to Reset. Avoid infinite recursion in that case.
623
+ if b == w {
624
+ return
625
+ }
626
+ if b.buf == nil {
627
+ b.buf = make([]byte, defaultBufSize)
628
+ }
629
+ b.err = nil
630
+ b.n = 0
631
+ b.wr = w
632
+ }
633
+
634
+ // Flush writes any buffered data to the underlying [io.Writer].
635
+ func (b *Writer) Flush() error {
636
+ if b.err != nil {
637
+ return b.err
638
+ }
639
+ if b.n == 0 {
640
+ return nil
641
+ }
642
+ n, err := b.wr.Write(b.buf[0:b.n])
643
+ if n < b.n && err == nil {
644
+ err = io.ErrShortWrite
645
+ }
646
+ if err != nil {
647
+ if n > 0 && n < b.n {
648
+ copy(b.buf[0:b.n-n], b.buf[n:b.n])
649
+ }
650
+ b.n -= n
651
+ b.err = err
652
+ return err
653
+ }
654
+ b.n = 0
655
+ return nil
656
+ }
657
+
658
+ // Available returns how many bytes are unused in the buffer.
659
+ func (b *Writer) Available() int { return len(b.buf) - b.n }
660
+
661
+ // AvailableBuffer returns an empty buffer with b.Available() capacity.
662
+ // This buffer is intended to be appended to and
663
+ // passed to an immediately succeeding [Writer.Write] call.
664
+ // The buffer is only valid until the next write operation on b.
665
+ func (b *Writer) AvailableBuffer() []byte {
666
+ return b.buf[b.n:][:0]
667
+ }
668
+
669
+ // Buffered returns the number of bytes that have been written into the current buffer.
670
+ func (b *Writer) Buffered() int { return b.n }
671
+
672
+ // Write writes the contents of p into the buffer.
673
+ // It returns the number of bytes written.
674
+ // If nn < len(p), it also returns an error explaining
675
+ // why the write is short.
676
+ func (b *Writer) Write(p []byte) (nn int, err error) {
677
+ for len(p) > b.Available() && b.err == nil {
678
+ var n int
679
+ if b.Buffered() == 0 {
680
+ // Large write, empty buffer.
681
+ // Write directly from p to avoid copy.
682
+ n, b.err = b.wr.Write(p)
683
+ } else {
684
+ n = copy(b.buf[b.n:], p)
685
+ b.n += n
686
+ b.Flush()
687
+ }
688
+ nn += n
689
+ p = p[n:]
690
+ }
691
+ if b.err != nil {
692
+ return nn, b.err
693
+ }
694
+ n := copy(b.buf[b.n:], p)
695
+ b.n += n
696
+ nn += n
697
+ return nn, nil
698
+ }
699
+
700
+ // WriteByte writes a single byte.
701
+ func (b *Writer) WriteByte(c byte) error {
702
+ if b.err != nil {
703
+ return b.err
704
+ }
705
+ if b.Available() <= 0 && b.Flush() != nil {
706
+ return b.err
707
+ }
708
+ b.buf[b.n] = c
709
+ b.n++
710
+ return nil
711
+ }
712
+
713
+ // WriteRune writes a single Unicode code point, returning
714
+ // the number of bytes written and any error.
715
+ func (b *Writer) WriteRune(r rune) (size int, err error) {
716
+ // Compare as uint32 to correctly handle negative runes.
717
+ if uint32(r) < utf8.RuneSelf {
718
+ err = b.WriteByte(byte(r))
719
+ if err != nil {
720
+ return 0, err
721
+ }
722
+ return 1, nil
723
+ }
724
+ if b.err != nil {
725
+ return 0, b.err
726
+ }
727
+ n := b.Available()
728
+ if n < utf8.UTFMax {
729
+ if b.Flush(); b.err != nil {
730
+ return 0, b.err
731
+ }
732
+ n = b.Available()
733
+ if n < utf8.UTFMax {
734
+ // Can only happen if buffer is silly small.
735
+ return b.WriteString(string(r))
736
+ }
737
+ }
738
+ size = utf8.EncodeRune(b.buf[b.n:], r)
739
+ b.n += size
740
+ return size, nil
741
+ }
742
+
743
+ // WriteString writes a string.
744
+ // It returns the number of bytes written.
745
+ // If the count is less than len(s), it also returns an error explaining
746
+ // why the write is short.
747
+ func (b *Writer) WriteString(s string) (int, error) {
748
+ var sw io.StringWriter
749
+ tryStringWriter := true
750
+
751
+ nn := 0
752
+ for len(s) > b.Available() && b.err == nil {
753
+ var n int
754
+ if b.Buffered() == 0 && sw == nil && tryStringWriter {
755
+ // Check at most once whether b.wr is a StringWriter.
756
+ sw, tryStringWriter = b.wr.(io.StringWriter)
757
+ }
758
+ if b.Buffered() == 0 && tryStringWriter {
759
+ // Large write, empty buffer, and the underlying writer supports
760
+ // WriteString: forward the write to the underlying StringWriter.
761
+ // This avoids an extra copy.
762
+ n, b.err = sw.WriteString(s)
763
+ } else {
764
+ n = copy(b.buf[b.n:], s)
765
+ b.n += n
766
+ b.Flush()
767
+ }
768
+ nn += n
769
+ s = s[n:]
770
+ }
771
+ if b.err != nil {
772
+ return nn, b.err
773
+ }
774
+ n := copy(b.buf[b.n:], s)
775
+ b.n += n
776
+ nn += n
777
+ return nn, nil
778
+ }
779
+
780
+ // ReadFrom implements [io.ReaderFrom]. If the underlying writer
781
+ // supports the ReadFrom method, this calls the underlying ReadFrom.
782
+ // If there is buffered data and an underlying ReadFrom, this fills
783
+ // the buffer and writes it before calling ReadFrom.
784
+ func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) {
785
+ if b.err != nil {
786
+ return 0, b.err
787
+ }
788
+ readerFrom, readerFromOK := b.wr.(io.ReaderFrom)
789
+ var m int
790
+ for {
791
+ if b.Available() == 0 {
792
+ if err1 := b.Flush(); err1 != nil {
793
+ return n, err1
794
+ }
795
+ }
796
+ if readerFromOK && b.Buffered() == 0 {
797
+ nn, err := readerFrom.ReadFrom(r)
798
+ b.err = err
799
+ n += nn
800
+ return n, err
801
+ }
802
+ nr := 0
803
+ for nr < maxConsecutiveEmptyReads {
804
+ m, err = r.Read(b.buf[b.n:])
805
+ if m != 0 || err != nil {
806
+ break
807
+ }
808
+ nr++
809
+ }
810
+ if nr == maxConsecutiveEmptyReads {
811
+ return n, io.ErrNoProgress
812
+ }
813
+ b.n += m
814
+ n += int64(m)
815
+ if err != nil {
816
+ break
817
+ }
818
+ }
819
+ if err == io.EOF {
820
+ // If we filled the buffer exactly, flush preemptively.
821
+ if b.Available() == 0 {
822
+ err = b.Flush()
823
+ } else {
824
+ err = nil
825
+ }
826
+ }
827
+ return n, err
828
+ }
829
+
830
+ // buffered input and output
831
+
832
+ // ReadWriter stores pointers to a [Reader] and a [Writer].
833
+ // It implements [io.ReadWriter].
834
+ type ReadWriter struct {
835
+ *Reader
836
+ *Writer
837
+ }
838
+
839
+ // NewReadWriter allocates a new [ReadWriter] that dispatches to r and w.
840
+ func NewReadWriter(r *Reader, w *Writer) *ReadWriter {
841
+ return &ReadWriter{r, w}
842
+ }
go/src/bufio/bufio_test.go ADDED
@@ -0,0 +1,1999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bufio_test
6
+
7
+ import (
8
+ . "bufio"
9
+ "bytes"
10
+ "errors"
11
+ "fmt"
12
+ "internal/asan"
13
+ "io"
14
+ "math/rand"
15
+ "strconv"
16
+ "strings"
17
+ "testing"
18
+ "testing/iotest"
19
+ "time"
20
+ "unicode/utf8"
21
+ )
22
+
23
+ // Reads from a reader and rot13s the result.
24
+ type rot13Reader struct {
25
+ r io.Reader
26
+ }
27
+
28
+ func newRot13Reader(r io.Reader) *rot13Reader {
29
+ r13 := new(rot13Reader)
30
+ r13.r = r
31
+ return r13
32
+ }
33
+
34
+ func (r13 *rot13Reader) Read(p []byte) (int, error) {
35
+ n, err := r13.r.Read(p)
36
+ for i := 0; i < n; i++ {
37
+ c := p[i] | 0x20 // lowercase byte
38
+ if 'a' <= c && c <= 'm' {
39
+ p[i] += 13
40
+ } else if 'n' <= c && c <= 'z' {
41
+ p[i] -= 13
42
+ }
43
+ }
44
+ return n, err
45
+ }
46
+
47
+ // Call ReadByte to accumulate the text of a file
48
+ func readBytes(buf *Reader) string {
49
+ var b [1000]byte
50
+ nb := 0
51
+ for {
52
+ c, err := buf.ReadByte()
53
+ if err == io.EOF {
54
+ break
55
+ }
56
+ if err == nil {
57
+ b[nb] = c
58
+ nb++
59
+ } else if err != iotest.ErrTimeout {
60
+ panic("Data: " + err.Error())
61
+ }
62
+ }
63
+ return string(b[0:nb])
64
+ }
65
+
66
+ func TestReaderSimple(t *testing.T) {
67
+ data := "hello world"
68
+ b := NewReader(strings.NewReader(data))
69
+ if s := readBytes(b); s != "hello world" {
70
+ t.Errorf("simple hello world test failed: got %q", s)
71
+ }
72
+
73
+ b = NewReader(newRot13Reader(strings.NewReader(data)))
74
+ if s := readBytes(b); s != "uryyb jbeyq" {
75
+ t.Errorf("rot13 hello world test failed: got %q", s)
76
+ }
77
+ }
78
+
79
+ type readMaker struct {
80
+ name string
81
+ fn func(io.Reader) io.Reader
82
+ }
83
+
84
+ var readMakers = []readMaker{
85
+ {"full", func(r io.Reader) io.Reader { return r }},
86
+ {"byte", iotest.OneByteReader},
87
+ {"half", iotest.HalfReader},
88
+ {"data+err", iotest.DataErrReader},
89
+ {"timeout", iotest.TimeoutReader},
90
+ }
91
+
92
+ // Call ReadString (which ends up calling everything else)
93
+ // to accumulate the text of a file.
94
+ func readLines(b *Reader) string {
95
+ s := ""
96
+ for {
97
+ s1, err := b.ReadString('\n')
98
+ if err == io.EOF {
99
+ break
100
+ }
101
+ if err != nil && err != iotest.ErrTimeout {
102
+ panic("GetLines: " + err.Error())
103
+ }
104
+ s += s1
105
+ }
106
+ return s
107
+ }
108
+
109
+ // Call Read to accumulate the text of a file
110
+ func reads(buf *Reader, m int) string {
111
+ var b [1000]byte
112
+ nb := 0
113
+ for {
114
+ n, err := buf.Read(b[nb : nb+m])
115
+ nb += n
116
+ if err == io.EOF {
117
+ break
118
+ }
119
+ }
120
+ return string(b[0:nb])
121
+ }
122
+
123
+ type bufReader struct {
124
+ name string
125
+ fn func(*Reader) string
126
+ }
127
+
128
+ var bufreaders = []bufReader{
129
+ {"1", func(b *Reader) string { return reads(b, 1) }},
130
+ {"2", func(b *Reader) string { return reads(b, 2) }},
131
+ {"3", func(b *Reader) string { return reads(b, 3) }},
132
+ {"4", func(b *Reader) string { return reads(b, 4) }},
133
+ {"5", func(b *Reader) string { return reads(b, 5) }},
134
+ {"7", func(b *Reader) string { return reads(b, 7) }},
135
+ {"bytes", readBytes},
136
+ {"lines", readLines},
137
+ }
138
+
139
+ const minReadBufferSize = 16
140
+
141
+ var bufsizes = []int{
142
+ 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096,
143
+ }
144
+
145
+ func TestReader(t *testing.T) {
146
+ var texts [31]string
147
+ str := ""
148
+ all := ""
149
+ for i := 0; i < len(texts)-1; i++ {
150
+ texts[i] = str + "\n"
151
+ all += texts[i]
152
+ str += string(rune(i%26 + 'a'))
153
+ }
154
+ texts[len(texts)-1] = all
155
+
156
+ for h := 0; h < len(texts); h++ {
157
+ text := texts[h]
158
+ for i := 0; i < len(readMakers); i++ {
159
+ for j := 0; j < len(bufreaders); j++ {
160
+ for k := 0; k < len(bufsizes); k++ {
161
+ readmaker := readMakers[i]
162
+ bufreader := bufreaders[j]
163
+ bufsize := bufsizes[k]
164
+ read := readmaker.fn(strings.NewReader(text))
165
+ buf := NewReaderSize(read, bufsize)
166
+ s := bufreader.fn(buf)
167
+ if s != text {
168
+ t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
169
+ readmaker.name, bufreader.name, bufsize, text, s)
170
+ }
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ type zeroReader struct{}
178
+
179
+ func (zeroReader) Read(p []byte) (int, error) {
180
+ return 0, nil
181
+ }
182
+
183
+ func TestZeroReader(t *testing.T) {
184
+ var z zeroReader
185
+ r := NewReader(z)
186
+
187
+ c := make(chan error)
188
+ go func() {
189
+ _, err := r.ReadByte()
190
+ c <- err
191
+ }()
192
+
193
+ select {
194
+ case err := <-c:
195
+ if err == nil {
196
+ t.Error("error expected")
197
+ } else if err != io.ErrNoProgress {
198
+ t.Error("unexpected error:", err)
199
+ }
200
+ case <-time.After(time.Second):
201
+ t.Error("test timed out (endless loop in ReadByte?)")
202
+ }
203
+ }
204
+
205
+ // A StringReader delivers its data one string segment at a time via Read.
206
+ type StringReader struct {
207
+ data []string
208
+ step int
209
+ }
210
+
211
+ func (r *StringReader) Read(p []byte) (n int, err error) {
212
+ if r.step < len(r.data) {
213
+ s := r.data[r.step]
214
+ n = copy(p, s)
215
+ r.step++
216
+ } else {
217
+ err = io.EOF
218
+ }
219
+ return
220
+ }
221
+
222
+ func readRuneSegments(t *testing.T, segments []string) {
223
+ got := ""
224
+ want := strings.Join(segments, "")
225
+ r := NewReader(&StringReader{data: segments})
226
+ for {
227
+ r, _, err := r.ReadRune()
228
+ if err != nil {
229
+ if err != io.EOF {
230
+ return
231
+ }
232
+ break
233
+ }
234
+ got += string(r)
235
+ }
236
+ if got != want {
237
+ t.Errorf("segments=%v got=%s want=%s", segments, got, want)
238
+ }
239
+ }
240
+
241
+ var segmentList = [][]string{
242
+ {},
243
+ {""},
244
+ {"日", "本語"},
245
+ {"\u65e5", "\u672c", "\u8a9e"},
246
+ {"\U000065e5", "\U0000672c", "\U00008a9e"},
247
+ {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"},
248
+ {"Hello", ", ", "World", "!"},
249
+ {"Hello", ", ", "", "World", "!"},
250
+ }
251
+
252
+ func TestReadRune(t *testing.T) {
253
+ for _, s := range segmentList {
254
+ readRuneSegments(t, s)
255
+ }
256
+ }
257
+
258
+ func TestUnreadRune(t *testing.T) {
259
+ segments := []string{"Hello, world:", "日本語"}
260
+ r := NewReader(&StringReader{data: segments})
261
+ got := ""
262
+ want := strings.Join(segments, "")
263
+ // Normal execution.
264
+ for {
265
+ r1, _, err := r.ReadRune()
266
+ if err != nil {
267
+ if err != io.EOF {
268
+ t.Error("unexpected error on ReadRune:", err)
269
+ }
270
+ break
271
+ }
272
+ got += string(r1)
273
+ // Put it back and read it again.
274
+ if err = r.UnreadRune(); err != nil {
275
+ t.Fatal("unexpected error on UnreadRune:", err)
276
+ }
277
+ r2, _, err := r.ReadRune()
278
+ if err != nil {
279
+ t.Fatal("unexpected error reading after unreading:", err)
280
+ }
281
+ if r1 != r2 {
282
+ t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2)
283
+ }
284
+ }
285
+ if got != want {
286
+ t.Errorf("got %q, want %q", got, want)
287
+ }
288
+ }
289
+
290
+ func TestNoUnreadRuneAfterPeek(t *testing.T) {
291
+ br := NewReader(strings.NewReader("example"))
292
+ br.ReadRune()
293
+ br.Peek(1)
294
+ if err := br.UnreadRune(); err == nil {
295
+ t.Error("UnreadRune didn't fail after Peek")
296
+ }
297
+ }
298
+
299
+ func TestNoUnreadByteAfterPeek(t *testing.T) {
300
+ br := NewReader(strings.NewReader("example"))
301
+ br.ReadByte()
302
+ br.Peek(1)
303
+ if err := br.UnreadByte(); err == nil {
304
+ t.Error("UnreadByte didn't fail after Peek")
305
+ }
306
+ }
307
+
308
+ func TestNoUnreadRuneAfterDiscard(t *testing.T) {
309
+ br := NewReader(strings.NewReader("example"))
310
+ br.ReadRune()
311
+ br.Discard(1)
312
+ if err := br.UnreadRune(); err == nil {
313
+ t.Error("UnreadRune didn't fail after Discard")
314
+ }
315
+ }
316
+
317
+ func TestNoUnreadByteAfterDiscard(t *testing.T) {
318
+ br := NewReader(strings.NewReader("example"))
319
+ br.ReadByte()
320
+ br.Discard(1)
321
+ if err := br.UnreadByte(); err == nil {
322
+ t.Error("UnreadByte didn't fail after Discard")
323
+ }
324
+ }
325
+
326
+ func TestNoUnreadRuneAfterWriteTo(t *testing.T) {
327
+ br := NewReader(strings.NewReader("example"))
328
+ br.WriteTo(io.Discard)
329
+ if err := br.UnreadRune(); err == nil {
330
+ t.Error("UnreadRune didn't fail after WriteTo")
331
+ }
332
+ }
333
+
334
+ func TestNoUnreadByteAfterWriteTo(t *testing.T) {
335
+ br := NewReader(strings.NewReader("example"))
336
+ br.WriteTo(io.Discard)
337
+ if err := br.UnreadByte(); err == nil {
338
+ t.Error("UnreadByte didn't fail after WriteTo")
339
+ }
340
+ }
341
+
342
+ func TestUnreadByte(t *testing.T) {
343
+ segments := []string{"Hello, ", "world"}
344
+ r := NewReader(&StringReader{data: segments})
345
+ got := ""
346
+ want := strings.Join(segments, "")
347
+ // Normal execution.
348
+ for {
349
+ b1, err := r.ReadByte()
350
+ if err != nil {
351
+ if err != io.EOF {
352
+ t.Error("unexpected error on ReadByte:", err)
353
+ }
354
+ break
355
+ }
356
+ got += string(b1)
357
+ // Put it back and read it again.
358
+ if err = r.UnreadByte(); err != nil {
359
+ t.Fatal("unexpected error on UnreadByte:", err)
360
+ }
361
+ b2, err := r.ReadByte()
362
+ if err != nil {
363
+ t.Fatal("unexpected error reading after unreading:", err)
364
+ }
365
+ if b1 != b2 {
366
+ t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2)
367
+ }
368
+ }
369
+ if got != want {
370
+ t.Errorf("got %q, want %q", got, want)
371
+ }
372
+ }
373
+
374
+ func TestUnreadByteMultiple(t *testing.T) {
375
+ segments := []string{"Hello, ", "world"}
376
+ data := strings.Join(segments, "")
377
+ for n := 0; n <= len(data); n++ {
378
+ r := NewReader(&StringReader{data: segments})
379
+ // Read n bytes.
380
+ for i := 0; i < n; i++ {
381
+ b, err := r.ReadByte()
382
+ if err != nil {
383
+ t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err)
384
+ }
385
+ if b != data[i] {
386
+ t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i])
387
+ }
388
+ }
389
+ // Unread one byte if there is one.
390
+ if n > 0 {
391
+ if err := r.UnreadByte(); err != nil {
392
+ t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err)
393
+ }
394
+ }
395
+ // Test that we cannot unread any further.
396
+ if err := r.UnreadByte(); err == nil {
397
+ t.Errorf("n = %d: expected error on UnreadByte", n)
398
+ }
399
+ }
400
+ }
401
+
402
+ func TestUnreadByteOthers(t *testing.T) {
403
+ // A list of readers to use in conjunction with UnreadByte.
404
+ var readers = []func(*Reader, byte) ([]byte, error){
405
+ (*Reader).ReadBytes,
406
+ (*Reader).ReadSlice,
407
+ func(r *Reader, delim byte) ([]byte, error) {
408
+ data, err := r.ReadString(delim)
409
+ return []byte(data), err
410
+ },
411
+ // ReadLine doesn't fit the data/pattern easily
412
+ // so we leave it out. It should be covered via
413
+ // the ReadSlice test since ReadLine simply calls
414
+ // ReadSlice, and it's that function that handles
415
+ // the last byte.
416
+ }
417
+
418
+ // Try all readers with UnreadByte.
419
+ for rno, read := range readers {
420
+ // Some input data that is longer than the minimum reader buffer size.
421
+ const n = 10
422
+ var buf bytes.Buffer
423
+ for i := 0; i < n; i++ {
424
+ buf.WriteString("abcdefg")
425
+ }
426
+
427
+ r := NewReaderSize(&buf, minReadBufferSize)
428
+ readTo := func(delim byte, want string) {
429
+ data, err := read(r, delim)
430
+ if err != nil {
431
+ t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err)
432
+ }
433
+ if got := string(data); got != want {
434
+ t.Fatalf("#%d: got %q, want %q", rno, got, want)
435
+ }
436
+ }
437
+
438
+ // Read the data with occasional UnreadByte calls.
439
+ for i := 0; i < n; i++ {
440
+ readTo('d', "abcd")
441
+ for j := 0; j < 3; j++ {
442
+ if err := r.UnreadByte(); err != nil {
443
+ t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err)
444
+ }
445
+ readTo('d', "d")
446
+ }
447
+ readTo('g', "efg")
448
+ }
449
+
450
+ // All data should have been read.
451
+ _, err := r.ReadByte()
452
+ if err != io.EOF {
453
+ t.Errorf("#%d: got error %v; want EOF", rno, err)
454
+ }
455
+ }
456
+ }
457
+
458
+ // Test that UnreadRune fails if the preceding operation was not a ReadRune.
459
+ func TestUnreadRuneError(t *testing.T) {
460
+ buf := make([]byte, 3) // All runes in this test are 3 bytes long
461
+ r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}})
462
+ if r.UnreadRune() == nil {
463
+ t.Error("expected error on UnreadRune from fresh buffer")
464
+ }
465
+ _, _, err := r.ReadRune()
466
+ if err != nil {
467
+ t.Error("unexpected error on ReadRune (1):", err)
468
+ }
469
+ if err = r.UnreadRune(); err != nil {
470
+ t.Error("unexpected error on UnreadRune (1):", err)
471
+ }
472
+ if r.UnreadRune() == nil {
473
+ t.Error("expected error after UnreadRune (1)")
474
+ }
475
+ // Test error after Read.
476
+ _, _, err = r.ReadRune() // reset state
477
+ if err != nil {
478
+ t.Error("unexpected error on ReadRune (2):", err)
479
+ }
480
+ _, err = r.Read(buf)
481
+ if err != nil {
482
+ t.Error("unexpected error on Read (2):", err)
483
+ }
484
+ if r.UnreadRune() == nil {
485
+ t.Error("expected error after Read (2)")
486
+ }
487
+ // Test error after ReadByte.
488
+ _, _, err = r.ReadRune() // reset state
489
+ if err != nil {
490
+ t.Error("unexpected error on ReadRune (2):", err)
491
+ }
492
+ for range buf {
493
+ _, err = r.ReadByte()
494
+ if err != nil {
495
+ t.Error("unexpected error on ReadByte (2):", err)
496
+ }
497
+ }
498
+ if r.UnreadRune() == nil {
499
+ t.Error("expected error after ReadByte")
500
+ }
501
+ // Test error after UnreadByte.
502
+ _, _, err = r.ReadRune() // reset state
503
+ if err != nil {
504
+ t.Error("unexpected error on ReadRune (3):", err)
505
+ }
506
+ _, err = r.ReadByte()
507
+ if err != nil {
508
+ t.Error("unexpected error on ReadByte (3):", err)
509
+ }
510
+ err = r.UnreadByte()
511
+ if err != nil {
512
+ t.Error("unexpected error on UnreadByte (3):", err)
513
+ }
514
+ if r.UnreadRune() == nil {
515
+ t.Error("expected error after UnreadByte (3)")
516
+ }
517
+ // Test error after ReadSlice.
518
+ _, _, err = r.ReadRune() // reset state
519
+ if err != nil {
520
+ t.Error("unexpected error on ReadRune (4):", err)
521
+ }
522
+ _, err = r.ReadSlice(0)
523
+ if err != io.EOF {
524
+ t.Error("unexpected error on ReadSlice (4):", err)
525
+ }
526
+ if r.UnreadRune() == nil {
527
+ t.Error("expected error after ReadSlice (4)")
528
+ }
529
+ }
530
+
531
+ func TestUnreadRuneAtEOF(t *testing.T) {
532
+ // UnreadRune/ReadRune should error at EOF (was a bug; used to panic)
533
+ r := NewReader(strings.NewReader("x"))
534
+ r.ReadRune()
535
+ r.ReadRune()
536
+ r.UnreadRune()
537
+ _, _, err := r.ReadRune()
538
+ if err == nil {
539
+ t.Error("expected error at EOF")
540
+ } else if err != io.EOF {
541
+ t.Error("expected EOF; got", err)
542
+ }
543
+ }
544
+
545
+ func TestReadWriteRune(t *testing.T) {
546
+ const NRune = 1000
547
+ byteBuf := new(bytes.Buffer)
548
+ w := NewWriter(byteBuf)
549
+ // Write the runes out using WriteRune
550
+ buf := make([]byte, utf8.UTFMax)
551
+ for r := rune(0); r < NRune; r++ {
552
+ size := utf8.EncodeRune(buf, r)
553
+ nbytes, err := w.WriteRune(r)
554
+ if err != nil {
555
+ t.Fatalf("WriteRune(0x%x) error: %s", r, err)
556
+ }
557
+ if nbytes != size {
558
+ t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes)
559
+ }
560
+ }
561
+ w.Flush()
562
+
563
+ r := NewReader(byteBuf)
564
+ // Read them back with ReadRune
565
+ for r1 := rune(0); r1 < NRune; r1++ {
566
+ size := utf8.EncodeRune(buf, r1)
567
+ nr, nbytes, err := r.ReadRune()
568
+ if nr != r1 || nbytes != size || err != nil {
569
+ t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err)
570
+ }
571
+ }
572
+ }
573
+
574
+ func TestWriteInvalidRune(t *testing.T) {
575
+ // Invalid runes, including negative ones, should be written as the
576
+ // replacement character.
577
+ for _, r := range []rune{-1, utf8.MaxRune + 1} {
578
+ var buf strings.Builder
579
+ w := NewWriter(&buf)
580
+ w.WriteRune(r)
581
+ w.Flush()
582
+ if s := buf.String(); s != "\uFFFD" {
583
+ t.Errorf("WriteRune(%d) wrote %q, not replacement character", r, s)
584
+ }
585
+ }
586
+ }
587
+
588
+ func TestReadStringAllocs(t *testing.T) {
589
+ if asan.Enabled {
590
+ t.Skip("test allocates more with -asan; see #70079")
591
+ }
592
+ r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
593
+ buf := NewReader(r)
594
+ allocs := testing.AllocsPerRun(100, func() {
595
+ r.Seek(0, io.SeekStart)
596
+ buf.Reset(r)
597
+
598
+ _, err := buf.ReadString('\n')
599
+ if err != nil {
600
+ t.Fatal(err)
601
+ }
602
+ })
603
+ if allocs != 1 {
604
+ t.Errorf("Unexpected number of allocations, got %f, want 1", allocs)
605
+ }
606
+ }
607
+
608
+ func TestWriter(t *testing.T) {
609
+ var data [8192]byte
610
+
611
+ for i := 0; i < len(data); i++ {
612
+ data[i] = byte(' ' + i%('~'-' '))
613
+ }
614
+ w := new(bytes.Buffer)
615
+ for i := 0; i < len(bufsizes); i++ {
616
+ for j := 0; j < len(bufsizes); j++ {
617
+ nwrite := bufsizes[i]
618
+ bs := bufsizes[j]
619
+
620
+ // Write nwrite bytes using buffer size bs.
621
+ // Check that the right amount makes it out
622
+ // and that the data is correct.
623
+
624
+ w.Reset()
625
+ buf := NewWriterSize(w, bs)
626
+ context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
627
+ n, e1 := buf.Write(data[0:nwrite])
628
+ if e1 != nil || n != nwrite {
629
+ t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
630
+ continue
631
+ }
632
+ if e := buf.Flush(); e != nil {
633
+ t.Errorf("%s: buf.Flush = %v", context, e)
634
+ }
635
+
636
+ written := w.Bytes()
637
+ if len(written) != nwrite {
638
+ t.Errorf("%s: %d bytes written", context, len(written))
639
+ }
640
+ for l := 0; l < len(written); l++ {
641
+ if written[l] != data[l] {
642
+ t.Errorf("wrong bytes written")
643
+ t.Errorf("want=%q", data[:len(written)])
644
+ t.Errorf("have=%q", written)
645
+ }
646
+ }
647
+ }
648
+ }
649
+ }
650
+
651
+ func TestWriterAppend(t *testing.T) {
652
+ got := new(bytes.Buffer)
653
+ var want []byte
654
+ rn := rand.New(rand.NewSource(0))
655
+ w := NewWriterSize(got, 64)
656
+ for i := 0; i < 100; i++ {
657
+ // Obtain a buffer to append to.
658
+ b := w.AvailableBuffer()
659
+ if w.Available() != cap(b) {
660
+ t.Fatalf("Available() = %v, want %v", w.Available(), cap(b))
661
+ }
662
+
663
+ // While not recommended, it is valid to append to a shifted buffer.
664
+ // This forces Write to copy the input.
665
+ if rn.Intn(8) == 0 && cap(b) > 0 {
666
+ b = b[1:1:cap(b)]
667
+ }
668
+
669
+ // Append a random integer of varying width.
670
+ n := int64(rn.Intn(1 << rn.Intn(30)))
671
+ want = append(strconv.AppendInt(want, n, 10), ' ')
672
+ b = append(strconv.AppendInt(b, n, 10), ' ')
673
+ w.Write(b)
674
+ }
675
+ w.Flush()
676
+
677
+ if !bytes.Equal(got.Bytes(), want) {
678
+ t.Errorf("output mismatch:\ngot %s\nwant %s", got.Bytes(), want)
679
+ }
680
+ }
681
+
682
+ // Check that write errors are returned properly.
683
+
684
+ type errorWriterTest struct {
685
+ n, m int
686
+ err error
687
+ expect error
688
+ }
689
+
690
+ func (w errorWriterTest) Write(p []byte) (int, error) {
691
+ return len(p) * w.n / w.m, w.err
692
+ }
693
+
694
+ var errorWriterTests = []errorWriterTest{
695
+ {0, 1, nil, io.ErrShortWrite},
696
+ {1, 2, nil, io.ErrShortWrite},
697
+ {1, 1, nil, nil},
698
+ {0, 1, io.ErrClosedPipe, io.ErrClosedPipe},
699
+ {1, 2, io.ErrClosedPipe, io.ErrClosedPipe},
700
+ {1, 1, io.ErrClosedPipe, io.ErrClosedPipe},
701
+ }
702
+
703
+ func TestWriteErrors(t *testing.T) {
704
+ for _, w := range errorWriterTests {
705
+ buf := NewWriter(w)
706
+ _, e := buf.Write([]byte("hello world"))
707
+ if e != nil {
708
+ t.Errorf("Write hello to %v: %v", w, e)
709
+ continue
710
+ }
711
+ // Two flushes, to verify the error is sticky.
712
+ for i := 0; i < 2; i++ {
713
+ e = buf.Flush()
714
+ if e != w.expect {
715
+ t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect)
716
+ }
717
+ }
718
+ }
719
+ }
720
+
721
+ func TestNewReaderSizeIdempotent(t *testing.T) {
722
+ const BufSize = 1000
723
+ b := NewReaderSize(strings.NewReader("hello world"), BufSize)
724
+ // Does it recognize itself?
725
+ b1 := NewReaderSize(b, BufSize)
726
+ if b1 != b {
727
+ t.Error("NewReaderSize did not detect underlying Reader")
728
+ }
729
+ // Does it wrap if existing buffer is too small?
730
+ b2 := NewReaderSize(b, 2*BufSize)
731
+ if b2 == b {
732
+ t.Error("NewReaderSize did not enlarge buffer")
733
+ }
734
+ }
735
+
736
+ func TestNewWriterSizeIdempotent(t *testing.T) {
737
+ const BufSize = 1000
738
+ b := NewWriterSize(new(bytes.Buffer), BufSize)
739
+ // Does it recognize itself?
740
+ b1 := NewWriterSize(b, BufSize)
741
+ if b1 != b {
742
+ t.Error("NewWriterSize did not detect underlying Writer")
743
+ }
744
+ // Does it wrap if existing buffer is too small?
745
+ b2 := NewWriterSize(b, 2*BufSize)
746
+ if b2 == b {
747
+ t.Error("NewWriterSize did not enlarge buffer")
748
+ }
749
+ }
750
+
751
+ func TestWriteString(t *testing.T) {
752
+ const BufSize = 8
753
+ buf := new(strings.Builder)
754
+ b := NewWriterSize(buf, BufSize)
755
+ b.WriteString("0") // easy
756
+ b.WriteString("123456") // still easy
757
+ b.WriteString("7890") // easy after flush
758
+ b.WriteString("abcdefghijklmnopqrstuvwxy") // hard
759
+ b.WriteString("z")
760
+ if err := b.Flush(); err != nil {
761
+ t.Error("WriteString", err)
762
+ }
763
+ s := "01234567890abcdefghijklmnopqrstuvwxyz"
764
+ if buf.String() != s {
765
+ t.Errorf("WriteString wants %q gets %q", s, buf.String())
766
+ }
767
+ }
768
+
769
+ func TestWriteStringStringWriter(t *testing.T) {
770
+ const BufSize = 8
771
+ {
772
+ tw := &teststringwriter{}
773
+ b := NewWriterSize(tw, BufSize)
774
+ b.WriteString("1234")
775
+ tw.check(t, "", "")
776
+ b.WriteString("56789012") // longer than BufSize
777
+ tw.check(t, "12345678", "") // but not enough (after filling the partially-filled buffer)
778
+ b.Flush()
779
+ tw.check(t, "123456789012", "")
780
+ }
781
+ {
782
+ tw := &teststringwriter{}
783
+ b := NewWriterSize(tw, BufSize)
784
+ b.WriteString("123456789") // long string, empty buffer:
785
+ tw.check(t, "", "123456789") // use WriteString
786
+ }
787
+ {
788
+ tw := &teststringwriter{}
789
+ b := NewWriterSize(tw, BufSize)
790
+ b.WriteString("abc")
791
+ tw.check(t, "", "")
792
+ b.WriteString("123456789012345") // long string, non-empty buffer
793
+ tw.check(t, "abc12345", "6789012345") // use Write and then WriteString since the remaining part is still longer than BufSize
794
+ }
795
+ {
796
+ tw := &teststringwriter{}
797
+ b := NewWriterSize(tw, BufSize)
798
+ b.Write([]byte("abc")) // same as above, but use Write instead of WriteString
799
+ tw.check(t, "", "")
800
+ b.WriteString("123456789012345")
801
+ tw.check(t, "abc12345", "6789012345") // same as above
802
+ }
803
+ }
804
+
805
+ type teststringwriter struct {
806
+ write string
807
+ writeString string
808
+ }
809
+
810
+ func (w *teststringwriter) Write(b []byte) (int, error) {
811
+ w.write += string(b)
812
+ return len(b), nil
813
+ }
814
+
815
+ func (w *teststringwriter) WriteString(s string) (int, error) {
816
+ w.writeString += s
817
+ return len(s), nil
818
+ }
819
+
820
+ func (w *teststringwriter) check(t *testing.T, write, writeString string) {
821
+ t.Helper()
822
+ if w.write != write {
823
+ t.Errorf("write: expected %q, got %q", write, w.write)
824
+ }
825
+ if w.writeString != writeString {
826
+ t.Errorf("writeString: expected %q, got %q", writeString, w.writeString)
827
+ }
828
+ }
829
+
830
+ func TestBufferFull(t *testing.T) {
831
+ const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"
832
+ buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize)
833
+ line, err := buf.ReadSlice('!')
834
+ if string(line) != "And now, hello, " || err != ErrBufferFull {
835
+ t.Errorf("first ReadSlice(,) = %q, %v", line, err)
836
+ }
837
+ line, err = buf.ReadSlice('!')
838
+ if string(line) != "world!" || err != nil {
839
+ t.Errorf("second ReadSlice(,) = %q, %v", line, err)
840
+ }
841
+ }
842
+
843
+ func TestPeek(t *testing.T) {
844
+ p := make([]byte, 10)
845
+ // string is 16 (minReadBufferSize) long.
846
+ buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize)
847
+ if s, err := buf.Peek(1); string(s) != "a" || err != nil {
848
+ t.Fatalf("want %q got %q, err=%v", "a", string(s), err)
849
+ }
850
+ if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
851
+ t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err)
852
+ }
853
+ if _, err := buf.Peek(-1); err != ErrNegativeCount {
854
+ t.Fatalf("want ErrNegativeCount got %v", err)
855
+ }
856
+ if s, err := buf.Peek(32); string(s) != "abcdefghijklmnop" || err != ErrBufferFull {
857
+ t.Fatalf("want %q, ErrBufFull got %q, err=%v", "abcdefghijklmnop", string(s), err)
858
+ }
859
+ if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil {
860
+ t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err)
861
+ }
862
+ if s, err := buf.Peek(1); string(s) != "d" || err != nil {
863
+ t.Fatalf("want %q got %q, err=%v", "d", string(s), err)
864
+ }
865
+ if s, err := buf.Peek(2); string(s) != "de" || err != nil {
866
+ t.Fatalf("want %q got %q, err=%v", "de", string(s), err)
867
+ }
868
+ if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil {
869
+ t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err)
870
+ }
871
+ if s, err := buf.Peek(4); string(s) != "ghij" || err != nil {
872
+ t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err)
873
+ }
874
+ if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil {
875
+ t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err)
876
+ }
877
+ if s, err := buf.Peek(0); string(s) != "" || err != nil {
878
+ t.Fatalf("want %q got %q, err=%v", "", string(s), err)
879
+ }
880
+ if _, err := buf.Peek(1); err != io.EOF {
881
+ t.Fatalf("want EOF got %v", err)
882
+ }
883
+
884
+ // Test for issue 3022, not exposing a reader's error on a successful Peek.
885
+ buf = NewReaderSize(dataAndEOFReader("abcd"), 32)
886
+ if s, err := buf.Peek(2); string(s) != "ab" || err != nil {
887
+ t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err)
888
+ }
889
+ if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
890
+ t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err)
891
+ }
892
+ if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil {
893
+ t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err)
894
+ }
895
+ if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF {
896
+ t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err)
897
+ }
898
+ }
899
+
900
+ type dataAndEOFReader string
901
+
902
+ func (r dataAndEOFReader) Read(p []byte) (int, error) {
903
+ return copy(p, r), io.EOF
904
+ }
905
+
906
+ func TestPeekThenUnreadRune(t *testing.T) {
907
+ // This sequence used to cause a crash.
908
+ r := NewReader(strings.NewReader("x"))
909
+ r.ReadRune()
910
+ r.Peek(1)
911
+ r.UnreadRune()
912
+ r.ReadRune() // Used to panic here
913
+ }
914
+
915
+ var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy")
916
+ var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy")
917
+ var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n")
918
+
919
+ // TestReader wraps a []byte and returns reads of a specific length.
920
+ type testReader struct {
921
+ data []byte
922
+ stride int
923
+ }
924
+
925
+ func (t *testReader) Read(buf []byte) (n int, err error) {
926
+ n = t.stride
927
+ if n > len(t.data) {
928
+ n = len(t.data)
929
+ }
930
+ if n > len(buf) {
931
+ n = len(buf)
932
+ }
933
+ copy(buf, t.data)
934
+ t.data = t.data[n:]
935
+ if len(t.data) == 0 {
936
+ err = io.EOF
937
+ }
938
+ return
939
+ }
940
+
941
+ func testReadLine(t *testing.T, input []byte) {
942
+ for stride := 1; stride < 2; stride++ {
943
+ done := 0
944
+ reader := testReader{input, stride}
945
+ l := NewReaderSize(&reader, len(input)+1)
946
+ for {
947
+ line, isPrefix, err := l.ReadLine()
948
+ if len(line) > 0 && err != nil {
949
+ t.Errorf("ReadLine returned both data and error: %s", err)
950
+ }
951
+ if isPrefix {
952
+ t.Errorf("ReadLine returned prefix")
953
+ }
954
+ if err != nil {
955
+ if err != io.EOF {
956
+ t.Fatalf("Got unknown error: %s", err)
957
+ }
958
+ break
959
+ }
960
+ if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) {
961
+ t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line)
962
+ }
963
+ done += len(line)
964
+ }
965
+ if done != len(testOutput) {
966
+ t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride)
967
+ }
968
+ }
969
+ }
970
+
971
+ func TestReadLine(t *testing.T) {
972
+ testReadLine(t, testInput)
973
+ testReadLine(t, testInputrn)
974
+ }
975
+
976
+ func TestLineTooLong(t *testing.T) {
977
+ data := make([]byte, 0)
978
+ for i := 0; i < minReadBufferSize*5/2; i++ {
979
+ data = append(data, '0'+byte(i%10))
980
+ }
981
+ buf := bytes.NewReader(data)
982
+ l := NewReaderSize(buf, minReadBufferSize)
983
+ line, isPrefix, err := l.ReadLine()
984
+ if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
985
+ t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
986
+ }
987
+ data = data[len(line):]
988
+ line, isPrefix, err = l.ReadLine()
989
+ if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
990
+ t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
991
+ }
992
+ data = data[len(line):]
993
+ line, isPrefix, err = l.ReadLine()
994
+ if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
995
+ t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
996
+ }
997
+ line, isPrefix, err = l.ReadLine()
998
+ if isPrefix || err == nil {
999
+ t.Errorf("expected no more lines: %x %s", line, err)
1000
+ }
1001
+ }
1002
+
1003
+ func TestReadAfterLines(t *testing.T) {
1004
+ line1 := "this is line1"
1005
+ restData := "this is line2\nthis is line 3\n"
1006
+ inbuf := bytes.NewReader([]byte(line1 + "\n" + restData))
1007
+ outbuf := new(strings.Builder)
1008
+ maxLineLength := len(line1) + len(restData)/2
1009
+ l := NewReaderSize(inbuf, maxLineLength)
1010
+ line, isPrefix, err := l.ReadLine()
1011
+ if isPrefix || err != nil || string(line) != line1 {
1012
+ t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line))
1013
+ }
1014
+ n, err := io.Copy(outbuf, l)
1015
+ if int(n) != len(restData) || err != nil {
1016
+ t.Errorf("bad result for Read: n=%d err=%v", n, err)
1017
+ }
1018
+ if outbuf.String() != restData {
1019
+ t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData)
1020
+ }
1021
+ }
1022
+
1023
+ func TestReadEmptyBuffer(t *testing.T) {
1024
+ l := NewReaderSize(new(bytes.Buffer), minReadBufferSize)
1025
+ line, isPrefix, err := l.ReadLine()
1026
+ if err != io.EOF {
1027
+ t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
1028
+ }
1029
+ }
1030
+
1031
+ func TestLinesAfterRead(t *testing.T) {
1032
+ l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
1033
+ _, err := io.ReadAll(l)
1034
+ if err != nil {
1035
+ t.Error(err)
1036
+ return
1037
+ }
1038
+
1039
+ line, isPrefix, err := l.ReadLine()
1040
+ if err != io.EOF {
1041
+ t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
1042
+ }
1043
+ }
1044
+
1045
+ func TestReadLineNonNilLineOrError(t *testing.T) {
1046
+ r := NewReader(strings.NewReader("line 1\n"))
1047
+ for i := 0; i < 2; i++ {
1048
+ l, _, err := r.ReadLine()
1049
+ if l != nil && err != nil {
1050
+ t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both",
1051
+ i+1, l, err)
1052
+ }
1053
+ }
1054
+ }
1055
+
1056
+ type readLineResult struct {
1057
+ line []byte
1058
+ isPrefix bool
1059
+ err error
1060
+ }
1061
+
1062
+ var readLineNewlinesTests = []struct {
1063
+ input string
1064
+ expect []readLineResult
1065
+ }{
1066
+ {"012345678901234\r\n012345678901234\r\n", []readLineResult{
1067
+ {[]byte("012345678901234"), true, nil},
1068
+ {nil, false, nil},
1069
+ {[]byte("012345678901234"), true, nil},
1070
+ {nil, false, nil},
1071
+ {nil, false, io.EOF},
1072
+ }},
1073
+ {"0123456789012345\r012345678901234\r", []readLineResult{
1074
+ {[]byte("0123456789012345"), true, nil},
1075
+ {[]byte("\r012345678901234"), true, nil},
1076
+ {[]byte("\r"), false, nil},
1077
+ {nil, false, io.EOF},
1078
+ }},
1079
+ }
1080
+
1081
+ func TestReadLineNewlines(t *testing.T) {
1082
+ for _, e := range readLineNewlinesTests {
1083
+ testReadLineNewlines(t, e.input, e.expect)
1084
+ }
1085
+ }
1086
+
1087
+ func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) {
1088
+ b := NewReaderSize(strings.NewReader(input), minReadBufferSize)
1089
+ for i, e := range expect {
1090
+ line, isPrefix, err := b.ReadLine()
1091
+ if !bytes.Equal(line, e.line) {
1092
+ t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line)
1093
+ return
1094
+ }
1095
+ if isPrefix != e.isPrefix {
1096
+ t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix)
1097
+ return
1098
+ }
1099
+ if err != e.err {
1100
+ t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err)
1101
+ return
1102
+ }
1103
+ }
1104
+ }
1105
+
1106
+ func createTestInput(n int) []byte {
1107
+ input := make([]byte, n)
1108
+ for i := range input {
1109
+ // 101 and 251 are arbitrary prime numbers.
1110
+ // The idea is to create an input sequence
1111
+ // which doesn't repeat too frequently.
1112
+ input[i] = byte(i % 251)
1113
+ if i%101 == 0 {
1114
+ input[i] ^= byte(i / 101)
1115
+ }
1116
+ }
1117
+ return input
1118
+ }
1119
+
1120
+ func TestReaderWriteTo(t *testing.T) {
1121
+ input := createTestInput(8192)
1122
+ r := NewReader(onlyReader{bytes.NewReader(input)})
1123
+ w := new(bytes.Buffer)
1124
+ if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) {
1125
+ t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input))
1126
+ }
1127
+
1128
+ for i, val := range w.Bytes() {
1129
+ if val != input[i] {
1130
+ t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i])
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ type errorWriterToTest struct {
1136
+ rn, wn int
1137
+ rerr, werr error
1138
+ expected error
1139
+ }
1140
+
1141
+ func (r errorWriterToTest) Read(p []byte) (int, error) {
1142
+ return len(p) * r.rn, r.rerr
1143
+ }
1144
+
1145
+ func (w errorWriterToTest) Write(p []byte) (int, error) {
1146
+ return len(p) * w.wn, w.werr
1147
+ }
1148
+
1149
+ var errorWriterToTests = []errorWriterToTest{
1150
+ {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe},
1151
+ {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
1152
+ {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrUnexpectedEOF},
1153
+ {0, 1, io.EOF, nil, nil},
1154
+ }
1155
+
1156
+ func TestReaderWriteToErrors(t *testing.T) {
1157
+ for i, rw := range errorWriterToTests {
1158
+ r := NewReader(rw)
1159
+ if _, err := r.WriteTo(rw); err != rw.expected {
1160
+ t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
1161
+ }
1162
+ }
1163
+ }
1164
+
1165
+ func TestWriterReadFrom(t *testing.T) {
1166
+ ws := []func(io.Writer) io.Writer{
1167
+ func(w io.Writer) io.Writer { return onlyWriter{w} },
1168
+ func(w io.Writer) io.Writer { return w },
1169
+ }
1170
+
1171
+ rs := []func(io.Reader) io.Reader{
1172
+ iotest.DataErrReader,
1173
+ func(r io.Reader) io.Reader { return r },
1174
+ }
1175
+
1176
+ for ri, rfunc := range rs {
1177
+ for wi, wfunc := range ws {
1178
+ input := createTestInput(8192)
1179
+ b := new(strings.Builder)
1180
+ w := NewWriter(wfunc(b))
1181
+ r := rfunc(bytes.NewReader(input))
1182
+ if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) {
1183
+ t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input))
1184
+ continue
1185
+ }
1186
+ if err := w.Flush(); err != nil {
1187
+ t.Errorf("Flush returned %v", err)
1188
+ continue
1189
+ }
1190
+ if got, want := b.String(), string(input); got != want {
1191
+ t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want)
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ type errorReaderFromTest struct {
1198
+ rn, wn int
1199
+ rerr, werr error
1200
+ expected error
1201
+ }
1202
+
1203
+ func (r errorReaderFromTest) Read(p []byte) (int, error) {
1204
+ return len(p) * r.rn, r.rerr
1205
+ }
1206
+
1207
+ func (w errorReaderFromTest) Write(p []byte) (int, error) {
1208
+ return len(p) * w.wn, w.werr
1209
+ }
1210
+
1211
+ var errorReaderFromTests = []errorReaderFromTest{
1212
+ {0, 1, io.EOF, nil, nil},
1213
+ {1, 1, io.EOF, nil, nil},
1214
+ {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
1215
+ {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe},
1216
+ {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite},
1217
+ }
1218
+
1219
+ func TestWriterReadFromErrors(t *testing.T) {
1220
+ for i, rw := range errorReaderFromTests {
1221
+ w := NewWriter(rw)
1222
+ if _, err := w.ReadFrom(rw); err != rw.expected {
1223
+ t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
1224
+ }
1225
+ }
1226
+ }
1227
+
1228
+ // TestWriterReadFromCounts tests that using io.Copy to copy into a
1229
+ // bufio.Writer does not prematurely flush the buffer. For example, when
1230
+ // buffering writes to a network socket, excessive network writes should be
1231
+ // avoided.
1232
+ func TestWriterReadFromCounts(t *testing.T) {
1233
+ var w0 writeCountingDiscard
1234
+ b0 := NewWriterSize(&w0, 1234)
1235
+ b0.WriteString(strings.Repeat("x", 1000))
1236
+ if w0 != 0 {
1237
+ t.Fatalf("write 1000 'x's: got %d writes, want 0", w0)
1238
+ }
1239
+ b0.WriteString(strings.Repeat("x", 200))
1240
+ if w0 != 0 {
1241
+ t.Fatalf("write 1200 'x's: got %d writes, want 0", w0)
1242
+ }
1243
+ io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))})
1244
+ if w0 != 0 {
1245
+ t.Fatalf("write 1230 'x's: got %d writes, want 0", w0)
1246
+ }
1247
+ io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))})
1248
+ if w0 != 1 {
1249
+ t.Fatalf("write 1239 'x's: got %d writes, want 1", w0)
1250
+ }
1251
+
1252
+ var w1 writeCountingDiscard
1253
+ b1 := NewWriterSize(&w1, 1234)
1254
+ b1.WriteString(strings.Repeat("x", 1200))
1255
+ b1.Flush()
1256
+ if w1 != 1 {
1257
+ t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1)
1258
+ }
1259
+ b1.WriteString(strings.Repeat("x", 89))
1260
+ if w1 != 1 {
1261
+ t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1)
1262
+ }
1263
+ io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))})
1264
+ if w1 != 1 {
1265
+ t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1)
1266
+ }
1267
+ io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))})
1268
+ if w1 != 2 {
1269
+ t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1)
1270
+ }
1271
+ b1.Flush()
1272
+ if w1 != 3 {
1273
+ t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1)
1274
+ }
1275
+ }
1276
+
1277
+ // A writeCountingDiscard is like io.Discard and counts the number of times
1278
+ // Write is called on it.
1279
+ type writeCountingDiscard int
1280
+
1281
+ func (w *writeCountingDiscard) Write(p []byte) (int, error) {
1282
+ *w++
1283
+ return len(p), nil
1284
+ }
1285
+
1286
+ type negativeReader int
1287
+
1288
+ func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
1289
+
1290
+ func TestNegativeRead(t *testing.T) {
1291
+ // should panic with a description pointing at the reader, not at itself.
1292
+ // (should NOT panic with slice index error, for example.)
1293
+ b := NewReader(new(negativeReader))
1294
+ defer func() {
1295
+ switch err := recover().(type) {
1296
+ case nil:
1297
+ t.Fatal("read did not panic")
1298
+ case error:
1299
+ if !strings.Contains(err.Error(), "reader returned negative count from Read") {
1300
+ t.Fatalf("wrong panic: %v", err)
1301
+ }
1302
+ default:
1303
+ t.Fatalf("unexpected panic value: %T(%v)", err, err)
1304
+ }
1305
+ }()
1306
+ b.Read(make([]byte, 100))
1307
+ }
1308
+
1309
+ var errFake = errors.New("fake error")
1310
+
1311
+ type errorThenGoodReader struct {
1312
+ didErr bool
1313
+ nread int
1314
+ }
1315
+
1316
+ func (r *errorThenGoodReader) Read(p []byte) (int, error) {
1317
+ r.nread++
1318
+ if !r.didErr {
1319
+ r.didErr = true
1320
+ return 0, errFake
1321
+ }
1322
+ return len(p), nil
1323
+ }
1324
+
1325
+ func TestReaderClearError(t *testing.T) {
1326
+ r := &errorThenGoodReader{}
1327
+ b := NewReader(r)
1328
+ buf := make([]byte, 1)
1329
+ if _, err := b.Read(nil); err != nil {
1330
+ t.Fatalf("1st nil Read = %v; want nil", err)
1331
+ }
1332
+ if _, err := b.Read(buf); err != errFake {
1333
+ t.Fatalf("1st Read = %v; want errFake", err)
1334
+ }
1335
+ if _, err := b.Read(nil); err != nil {
1336
+ t.Fatalf("2nd nil Read = %v; want nil", err)
1337
+ }
1338
+ if _, err := b.Read(buf); err != nil {
1339
+ t.Fatalf("3rd Read with buffer = %v; want nil", err)
1340
+ }
1341
+ if r.nread != 2 {
1342
+ t.Errorf("num reads = %d; want 2", r.nread)
1343
+ }
1344
+ }
1345
+
1346
+ // Test for golang.org/issue/5947
1347
+ func TestWriterReadFromWhileFull(t *testing.T) {
1348
+ buf := new(bytes.Buffer)
1349
+ w := NewWriterSize(buf, 10)
1350
+
1351
+ // Fill buffer exactly.
1352
+ n, err := w.Write([]byte("0123456789"))
1353
+ if n != 10 || err != nil {
1354
+ t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err)
1355
+ }
1356
+
1357
+ // Use ReadFrom to read in some data.
1358
+ n2, err := w.ReadFrom(strings.NewReader("abcdef"))
1359
+ if n2 != 6 || err != nil {
1360
+ t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err)
1361
+ }
1362
+ }
1363
+
1364
+ type emptyThenNonEmptyReader struct {
1365
+ r io.Reader
1366
+ n int
1367
+ }
1368
+
1369
+ func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) {
1370
+ if r.n <= 0 {
1371
+ return r.r.Read(p)
1372
+ }
1373
+ r.n--
1374
+ return 0, nil
1375
+ }
1376
+
1377
+ // Test for golang.org/issue/7611
1378
+ func TestWriterReadFromUntilEOF(t *testing.T) {
1379
+ buf := new(bytes.Buffer)
1380
+ w := NewWriterSize(buf, 5)
1381
+
1382
+ // Partially fill buffer
1383
+ n, err := w.Write([]byte("0123"))
1384
+ if n != 4 || err != nil {
1385
+ t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
1386
+ }
1387
+
1388
+ // Use ReadFrom to read in some data.
1389
+ r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3}
1390
+ n2, err := w.ReadFrom(r)
1391
+ if n2 != 4 || err != nil {
1392
+ t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err)
1393
+ }
1394
+ w.Flush()
1395
+ if got, want := buf.String(), "0123abcd"; got != want {
1396
+ t.Fatalf("buf.Bytes() returned %q, want %q", got, want)
1397
+ }
1398
+ }
1399
+
1400
+ func TestWriterReadFromErrNoProgress(t *testing.T) {
1401
+ buf := new(bytes.Buffer)
1402
+ w := NewWriterSize(buf, 5)
1403
+
1404
+ // Partially fill buffer
1405
+ n, err := w.Write([]byte("0123"))
1406
+ if n != 4 || err != nil {
1407
+ t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
1408
+ }
1409
+
1410
+ // Use ReadFrom to read in some data.
1411
+ r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100}
1412
+ n2, err := w.ReadFrom(r)
1413
+ if n2 != 0 || err != io.ErrNoProgress {
1414
+ t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err)
1415
+ }
1416
+ }
1417
+
1418
+ type readFromWriter struct {
1419
+ buf []byte
1420
+ writeBytes int
1421
+ readFromBytes int
1422
+ }
1423
+
1424
+ func (w *readFromWriter) Write(p []byte) (int, error) {
1425
+ w.buf = append(w.buf, p...)
1426
+ w.writeBytes += len(p)
1427
+ return len(p), nil
1428
+ }
1429
+
1430
+ func (w *readFromWriter) ReadFrom(r io.Reader) (int64, error) {
1431
+ b, err := io.ReadAll(r)
1432
+ w.buf = append(w.buf, b...)
1433
+ w.readFromBytes += len(b)
1434
+ return int64(len(b)), err
1435
+ }
1436
+
1437
+ // Test that calling (*Writer).ReadFrom with a partially-filled buffer
1438
+ // fills the buffer before switching over to ReadFrom.
1439
+ func TestWriterReadFromWithBufferedData(t *testing.T) {
1440
+ const bufsize = 16
1441
+
1442
+ input := createTestInput(64)
1443
+ rfw := &readFromWriter{}
1444
+ w := NewWriterSize(rfw, bufsize)
1445
+
1446
+ const writeSize = 8
1447
+ if n, err := w.Write(input[:writeSize]); n != writeSize || err != nil {
1448
+ t.Errorf("w.Write(%v bytes) = %v, %v; want %v, nil", writeSize, n, err, writeSize)
1449
+ }
1450
+ n, err := w.ReadFrom(bytes.NewReader(input[writeSize:]))
1451
+ if wantn := len(input[writeSize:]); int(n) != wantn || err != nil {
1452
+ t.Errorf("io.Copy(w, %v bytes) = %v, %v; want %v, nil", wantn, n, err, wantn)
1453
+ }
1454
+ if err := w.Flush(); err != nil {
1455
+ t.Errorf("w.Flush() = %v, want nil", err)
1456
+ }
1457
+
1458
+ if got, want := rfw.writeBytes, bufsize; got != want {
1459
+ t.Errorf("wrote %v bytes with Write, want %v", got, want)
1460
+ }
1461
+ if got, want := rfw.readFromBytes, len(input)-bufsize; got != want {
1462
+ t.Errorf("wrote %v bytes with ReadFrom, want %v", got, want)
1463
+ }
1464
+ }
1465
+
1466
+ func TestReadZero(t *testing.T) {
1467
+ for _, size := range []int{100, 2} {
1468
+ t.Run(fmt.Sprintf("bufsize=%d", size), func(t *testing.T) {
1469
+ r := io.MultiReader(strings.NewReader("abc"), &emptyThenNonEmptyReader{r: strings.NewReader("def"), n: 1})
1470
+ br := NewReaderSize(r, size)
1471
+ want := func(s string, wantErr error) {
1472
+ p := make([]byte, 50)
1473
+ n, err := br.Read(p)
1474
+ if err != wantErr || n != len(s) || string(p[:n]) != s {
1475
+ t.Fatalf("read(%d) = %q, %v, want %q, %v", len(p), string(p[:n]), err, s, wantErr)
1476
+ }
1477
+ t.Logf("read(%d) = %q, %v", len(p), string(p[:n]), err)
1478
+ }
1479
+ want("abc", nil)
1480
+ want("", nil)
1481
+ want("def", nil)
1482
+ want("", io.EOF)
1483
+ })
1484
+ }
1485
+ }
1486
+
1487
+ func TestReaderReset(t *testing.T) {
1488
+ checkAll := func(r *Reader, want string) {
1489
+ t.Helper()
1490
+ all, err := io.ReadAll(r)
1491
+ if err != nil {
1492
+ t.Fatal(err)
1493
+ }
1494
+ if string(all) != want {
1495
+ t.Errorf("ReadAll returned %q, want %q", all, want)
1496
+ }
1497
+ }
1498
+
1499
+ r := NewReader(strings.NewReader("foo foo"))
1500
+ buf := make([]byte, 3)
1501
+ r.Read(buf)
1502
+ if string(buf) != "foo" {
1503
+ t.Errorf("buf = %q; want foo", buf)
1504
+ }
1505
+
1506
+ r.Reset(strings.NewReader("bar bar"))
1507
+ checkAll(r, "bar bar")
1508
+
1509
+ *r = Reader{} // zero out the Reader
1510
+ r.Reset(strings.NewReader("bar bar"))
1511
+ checkAll(r, "bar bar")
1512
+
1513
+ // Wrap a reader and then Reset to that reader.
1514
+ r.Reset(strings.NewReader("recur"))
1515
+ r2 := NewReader(r)
1516
+ checkAll(r2, "recur")
1517
+ r.Reset(strings.NewReader("recur2"))
1518
+ r2.Reset(r)
1519
+ checkAll(r2, "recur2")
1520
+ }
1521
+
1522
+ func TestWriterReset(t *testing.T) {
1523
+ var buf1, buf2, buf3, buf4, buf5 strings.Builder
1524
+ w := NewWriter(&buf1)
1525
+ w.WriteString("foo")
1526
+
1527
+ w.Reset(&buf2) // and not flushed
1528
+ w.WriteString("bar")
1529
+ w.Flush()
1530
+ if buf1.String() != "" {
1531
+ t.Errorf("buf1 = %q; want empty", buf1.String())
1532
+ }
1533
+ if buf2.String() != "bar" {
1534
+ t.Errorf("buf2 = %q; want bar", buf2.String())
1535
+ }
1536
+
1537
+ *w = Writer{} // zero out the Writer
1538
+ w.Reset(&buf3) // and not flushed
1539
+ w.WriteString("bar")
1540
+ w.Flush()
1541
+ if buf1.String() != "" {
1542
+ t.Errorf("buf1 = %q; want empty", buf1.String())
1543
+ }
1544
+ if buf3.String() != "bar" {
1545
+ t.Errorf("buf3 = %q; want bar", buf3.String())
1546
+ }
1547
+
1548
+ // Wrap a writer and then Reset to that writer.
1549
+ w.Reset(&buf4)
1550
+ w2 := NewWriter(w)
1551
+ w2.WriteString("recur")
1552
+ w2.Flush()
1553
+ if buf4.String() != "recur" {
1554
+ t.Errorf("buf4 = %q, want %q", buf4.String(), "recur")
1555
+ }
1556
+ w.Reset(&buf5)
1557
+ w2.Reset(w)
1558
+ w2.WriteString("recur2")
1559
+ w2.Flush()
1560
+ if buf5.String() != "recur2" {
1561
+ t.Errorf("buf5 = %q, want %q", buf5.String(), "recur2")
1562
+ }
1563
+ }
1564
+
1565
+ func TestReaderDiscard(t *testing.T) {
1566
+ tests := []struct {
1567
+ name string
1568
+ r io.Reader
1569
+ bufSize int // 0 means 16
1570
+ peekSize int
1571
+
1572
+ n int // input to Discard
1573
+
1574
+ want int // from Discard
1575
+ wantErr error // from Discard
1576
+
1577
+ wantBuffered int
1578
+ }{
1579
+ {
1580
+ name: "normal case",
1581
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1582
+ peekSize: 16,
1583
+ n: 6,
1584
+ want: 6,
1585
+ wantBuffered: 10,
1586
+ },
1587
+ {
1588
+ name: "discard causing read",
1589
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1590
+ n: 6,
1591
+ want: 6,
1592
+ wantBuffered: 10,
1593
+ },
1594
+ {
1595
+ name: "discard all without peek",
1596
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1597
+ n: 26,
1598
+ want: 26,
1599
+ wantBuffered: 0,
1600
+ },
1601
+ {
1602
+ name: "discard more than end",
1603
+ r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1604
+ n: 27,
1605
+ want: 26,
1606
+ wantErr: io.EOF,
1607
+ wantBuffered: 0,
1608
+ },
1609
+ // Any error from filling shouldn't show up until we
1610
+ // get past the valid bytes. Here we return 5 valid bytes at the same time
1611
+ // as an error, but test that we don't see the error from Discard.
1612
+ {
1613
+ name: "fill error, discard less",
1614
+ r: newScriptedReader(func(p []byte) (n int, err error) {
1615
+ if len(p) < 5 {
1616
+ panic("unexpected small read")
1617
+ }
1618
+ return 5, errors.New("5-then-error")
1619
+ }),
1620
+ n: 4,
1621
+ want: 4,
1622
+ wantErr: nil,
1623
+ wantBuffered: 1,
1624
+ },
1625
+ {
1626
+ name: "fill error, discard equal",
1627
+ r: newScriptedReader(func(p []byte) (n int, err error) {
1628
+ if len(p) < 5 {
1629
+ panic("unexpected small read")
1630
+ }
1631
+ return 5, errors.New("5-then-error")
1632
+ }),
1633
+ n: 5,
1634
+ want: 5,
1635
+ wantErr: nil,
1636
+ wantBuffered: 0,
1637
+ },
1638
+ {
1639
+ name: "fill error, discard more",
1640
+ r: newScriptedReader(func(p []byte) (n int, err error) {
1641
+ if len(p) < 5 {
1642
+ panic("unexpected small read")
1643
+ }
1644
+ return 5, errors.New("5-then-error")
1645
+ }),
1646
+ n: 6,
1647
+ want: 5,
1648
+ wantErr: errors.New("5-then-error"),
1649
+ wantBuffered: 0,
1650
+ },
1651
+ // Discard of 0 shouldn't cause a read:
1652
+ {
1653
+ name: "discard zero",
1654
+ r: newScriptedReader(), // will panic on Read
1655
+ n: 0,
1656
+ want: 0,
1657
+ wantErr: nil,
1658
+ wantBuffered: 0,
1659
+ },
1660
+ {
1661
+ name: "discard negative",
1662
+ r: newScriptedReader(), // will panic on Read
1663
+ n: -1,
1664
+ want: 0,
1665
+ wantErr: ErrNegativeCount,
1666
+ wantBuffered: 0,
1667
+ },
1668
+ }
1669
+ for _, tt := range tests {
1670
+ br := NewReaderSize(tt.r, tt.bufSize)
1671
+ if tt.peekSize > 0 {
1672
+ peekBuf, err := br.Peek(tt.peekSize)
1673
+ if err != nil {
1674
+ t.Errorf("%s: Peek(%d): %v", tt.name, tt.peekSize, err)
1675
+ continue
1676
+ }
1677
+ if len(peekBuf) != tt.peekSize {
1678
+ t.Errorf("%s: len(Peek(%d)) = %v; want %v", tt.name, tt.peekSize, len(peekBuf), tt.peekSize)
1679
+ continue
1680
+ }
1681
+ }
1682
+ discarded, err := br.Discard(tt.n)
1683
+ if ge, we := fmt.Sprint(err), fmt.Sprint(tt.wantErr); discarded != tt.want || ge != we {
1684
+ t.Errorf("%s: Discard(%d) = (%v, %v); want (%v, %v)", tt.name, tt.n, discarded, ge, tt.want, we)
1685
+ continue
1686
+ }
1687
+ if bn := br.Buffered(); bn != tt.wantBuffered {
1688
+ t.Errorf("%s: after Discard, Buffered = %d; want %d", tt.name, bn, tt.wantBuffered)
1689
+ }
1690
+ }
1691
+
1692
+ }
1693
+
1694
+ func TestReaderSize(t *testing.T) {
1695
+ if got, want := NewReader(nil).Size(), DefaultBufSize; got != want {
1696
+ t.Errorf("NewReader's Reader.Size = %d; want %d", got, want)
1697
+ }
1698
+ if got, want := NewReaderSize(nil, 1234).Size(), 1234; got != want {
1699
+ t.Errorf("NewReaderSize's Reader.Size = %d; want %d", got, want)
1700
+ }
1701
+ }
1702
+
1703
+ func TestWriterSize(t *testing.T) {
1704
+ if got, want := NewWriter(nil).Size(), DefaultBufSize; got != want {
1705
+ t.Errorf("NewWriter's Writer.Size = %d; want %d", got, want)
1706
+ }
1707
+ if got, want := NewWriterSize(nil, 1234).Size(), 1234; got != want {
1708
+ t.Errorf("NewWriterSize's Writer.Size = %d; want %d", got, want)
1709
+ }
1710
+ }
1711
+
1712
+ // An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have.
1713
+ type onlyReader struct {
1714
+ io.Reader
1715
+ }
1716
+
1717
+ // An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have.
1718
+ type onlyWriter struct {
1719
+ io.Writer
1720
+ }
1721
+
1722
+ // A scriptedReader is an io.Reader that executes its steps sequentially.
1723
+ type scriptedReader []func(p []byte) (n int, err error)
1724
+
1725
+ func (sr *scriptedReader) Read(p []byte) (n int, err error) {
1726
+ if len(*sr) == 0 {
1727
+ panic("too many Read calls on scripted Reader. No steps remain.")
1728
+ }
1729
+ step := (*sr)[0]
1730
+ *sr = (*sr)[1:]
1731
+ return step(p)
1732
+ }
1733
+
1734
+ func newScriptedReader(steps ...func(p []byte) (n int, err error)) io.Reader {
1735
+ sr := scriptedReader(steps)
1736
+ return &sr
1737
+ }
1738
+
1739
+ // eofReader returns the number of bytes read and io.EOF for the read that consumes the last of the content.
1740
+ type eofReader struct {
1741
+ buf []byte
1742
+ }
1743
+
1744
+ func (r *eofReader) Read(p []byte) (int, error) {
1745
+ read := copy(p, r.buf)
1746
+ r.buf = r.buf[read:]
1747
+
1748
+ switch read {
1749
+ case 0, len(r.buf):
1750
+ // As allowed in the documentation, this will return io.EOF
1751
+ // in the same call that consumes the last of the data.
1752
+ // https://godoc.org/io#Reader
1753
+ return read, io.EOF
1754
+ }
1755
+
1756
+ return read, nil
1757
+ }
1758
+
1759
+ func TestPartialReadEOF(t *testing.T) {
1760
+ src := make([]byte, 10)
1761
+ eofR := &eofReader{buf: src}
1762
+ r := NewReader(eofR)
1763
+
1764
+ // Start by reading 5 of the 10 available bytes.
1765
+ dest := make([]byte, 5)
1766
+ read, err := r.Read(dest)
1767
+ if err != nil {
1768
+ t.Fatalf("unexpected error: %v", err)
1769
+ }
1770
+ if n := len(dest); read != n {
1771
+ t.Fatalf("read %d bytes; wanted %d bytes", read, n)
1772
+ }
1773
+
1774
+ // The Reader should have buffered all the content from the io.Reader.
1775
+ if n := len(eofR.buf); n != 0 {
1776
+ t.Fatalf("got %d bytes left in bufio.Reader source; want 0 bytes", n)
1777
+ }
1778
+ // To prove the point, check that there are still 5 bytes available to read.
1779
+ if n := r.Buffered(); n != 5 {
1780
+ t.Fatalf("got %d bytes buffered in bufio.Reader; want 5 bytes", n)
1781
+ }
1782
+
1783
+ // This is the second read of 0 bytes.
1784
+ read, err = r.Read([]byte{})
1785
+ if err != nil {
1786
+ t.Fatalf("unexpected error: %v", err)
1787
+ }
1788
+ if read != 0 {
1789
+ t.Fatalf("read %d bytes; want 0 bytes", read)
1790
+ }
1791
+ }
1792
+
1793
+ type writerWithReadFromError struct{}
1794
+
1795
+ func (w writerWithReadFromError) ReadFrom(r io.Reader) (int64, error) {
1796
+ return 0, errors.New("writerWithReadFromError error")
1797
+ }
1798
+
1799
+ func (w writerWithReadFromError) Write(b []byte) (n int, err error) {
1800
+ return 10, nil
1801
+ }
1802
+
1803
+ func TestWriterReadFromMustSetUnderlyingError(t *testing.T) {
1804
+ var wr = NewWriter(writerWithReadFromError{})
1805
+ if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
1806
+ t.Fatal("expected ReadFrom returns error, got nil")
1807
+ }
1808
+ if _, err := wr.Write([]byte("123")); err == nil {
1809
+ t.Fatal("expected Write returns error, got nil")
1810
+ }
1811
+ }
1812
+
1813
+ type writeErrorOnlyWriter struct{}
1814
+
1815
+ func (w writeErrorOnlyWriter) Write(p []byte) (n int, err error) {
1816
+ return 0, errors.New("writeErrorOnlyWriter error")
1817
+ }
1818
+
1819
+ // Ensure that previous Write errors are immediately returned
1820
+ // on any ReadFrom. See golang.org/issue/35194.
1821
+ func TestWriterReadFromMustReturnUnderlyingError(t *testing.T) {
1822
+ var wr = NewWriter(writeErrorOnlyWriter{})
1823
+ s := "test1"
1824
+ wantBuffered := len(s)
1825
+ if _, err := wr.WriteString(s); err != nil {
1826
+ t.Fatalf("unexpected error: %v", err)
1827
+ }
1828
+ if err := wr.Flush(); err == nil {
1829
+ t.Error("expected flush error, got nil")
1830
+ }
1831
+ if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
1832
+ t.Fatal("expected error, got nil")
1833
+ }
1834
+ if buffered := wr.Buffered(); buffered != wantBuffered {
1835
+ t.Fatalf("Buffered = %v; want %v", buffered, wantBuffered)
1836
+ }
1837
+ }
1838
+
1839
+ func BenchmarkReaderCopyOptimal(b *testing.B) {
1840
+ // Optimal case is where the underlying reader implements io.WriterTo
1841
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1842
+ src := NewReader(srcBuf)
1843
+ dstBuf := new(bytes.Buffer)
1844
+ dst := onlyWriter{dstBuf}
1845
+ for i := 0; i < b.N; i++ {
1846
+ srcBuf.Reset()
1847
+ src.Reset(srcBuf)
1848
+ dstBuf.Reset()
1849
+ io.Copy(dst, src)
1850
+ }
1851
+ }
1852
+
1853
+ func BenchmarkReaderCopyUnoptimal(b *testing.B) {
1854
+ // Unoptimal case is where the underlying reader doesn't implement io.WriterTo
1855
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1856
+ src := NewReader(onlyReader{srcBuf})
1857
+ dstBuf := new(bytes.Buffer)
1858
+ dst := onlyWriter{dstBuf}
1859
+ for i := 0; i < b.N; i++ {
1860
+ srcBuf.Reset()
1861
+ src.Reset(onlyReader{srcBuf})
1862
+ dstBuf.Reset()
1863
+ io.Copy(dst, src)
1864
+ }
1865
+ }
1866
+
1867
+ func BenchmarkReaderCopyNoWriteTo(b *testing.B) {
1868
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1869
+ srcReader := NewReader(srcBuf)
1870
+ src := onlyReader{srcReader}
1871
+ dstBuf := new(bytes.Buffer)
1872
+ dst := onlyWriter{dstBuf}
1873
+ for i := 0; i < b.N; i++ {
1874
+ srcBuf.Reset()
1875
+ srcReader.Reset(srcBuf)
1876
+ dstBuf.Reset()
1877
+ io.Copy(dst, src)
1878
+ }
1879
+ }
1880
+
1881
+ func BenchmarkReaderWriteToOptimal(b *testing.B) {
1882
+ const bufSize = 16 << 10
1883
+ buf := make([]byte, bufSize)
1884
+ r := bytes.NewReader(buf)
1885
+ srcReader := NewReaderSize(onlyReader{r}, 1<<10)
1886
+ if _, ok := io.Discard.(io.ReaderFrom); !ok {
1887
+ b.Fatal("io.Discard doesn't support ReaderFrom")
1888
+ }
1889
+ for i := 0; i < b.N; i++ {
1890
+ r.Seek(0, io.SeekStart)
1891
+ srcReader.Reset(onlyReader{r})
1892
+ n, err := srcReader.WriteTo(io.Discard)
1893
+ if err != nil {
1894
+ b.Fatal(err)
1895
+ }
1896
+ if n != bufSize {
1897
+ b.Fatalf("n = %d; want %d", n, bufSize)
1898
+ }
1899
+ }
1900
+ }
1901
+
1902
+ func BenchmarkReaderReadString(b *testing.B) {
1903
+ r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
1904
+ buf := NewReader(r)
1905
+ b.ReportAllocs()
1906
+ for i := 0; i < b.N; i++ {
1907
+ r.Seek(0, io.SeekStart)
1908
+ buf.Reset(r)
1909
+
1910
+ _, err := buf.ReadString('\n')
1911
+ if err != nil {
1912
+ b.Fatal(err)
1913
+ }
1914
+ }
1915
+ }
1916
+
1917
+ func BenchmarkWriterCopyOptimal(b *testing.B) {
1918
+ // Optimal case is where the underlying writer implements io.ReaderFrom
1919
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1920
+ src := onlyReader{srcBuf}
1921
+ dstBuf := new(bytes.Buffer)
1922
+ dst := NewWriter(dstBuf)
1923
+ for i := 0; i < b.N; i++ {
1924
+ srcBuf.Reset()
1925
+ dstBuf.Reset()
1926
+ dst.Reset(dstBuf)
1927
+ io.Copy(dst, src)
1928
+ }
1929
+ }
1930
+
1931
+ func BenchmarkWriterCopyUnoptimal(b *testing.B) {
1932
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1933
+ src := onlyReader{srcBuf}
1934
+ dstBuf := new(bytes.Buffer)
1935
+ dst := NewWriter(onlyWriter{dstBuf})
1936
+ for i := 0; i < b.N; i++ {
1937
+ srcBuf.Reset()
1938
+ dstBuf.Reset()
1939
+ dst.Reset(onlyWriter{dstBuf})
1940
+ io.Copy(dst, src)
1941
+ }
1942
+ }
1943
+
1944
+ func BenchmarkWriterCopyNoReadFrom(b *testing.B) {
1945
+ srcBuf := bytes.NewBuffer(make([]byte, 8192))
1946
+ src := onlyReader{srcBuf}
1947
+ dstBuf := new(bytes.Buffer)
1948
+ dstWriter := NewWriter(dstBuf)
1949
+ dst := onlyWriter{dstWriter}
1950
+ for i := 0; i < b.N; i++ {
1951
+ srcBuf.Reset()
1952
+ dstBuf.Reset()
1953
+ dstWriter.Reset(dstBuf)
1954
+ io.Copy(dst, src)
1955
+ }
1956
+ }
1957
+
1958
+ func BenchmarkReaderEmpty(b *testing.B) {
1959
+ b.ReportAllocs()
1960
+ str := strings.Repeat("x", 16<<10)
1961
+ for i := 0; i < b.N; i++ {
1962
+ br := NewReader(strings.NewReader(str))
1963
+ n, err := io.Copy(io.Discard, br)
1964
+ if err != nil {
1965
+ b.Fatal(err)
1966
+ }
1967
+ if n != int64(len(str)) {
1968
+ b.Fatal("wrong length")
1969
+ }
1970
+ }
1971
+ }
1972
+
1973
+ func BenchmarkWriterEmpty(b *testing.B) {
1974
+ b.ReportAllocs()
1975
+ str := strings.Repeat("x", 1<<10)
1976
+ bs := []byte(str)
1977
+ for i := 0; i < b.N; i++ {
1978
+ bw := NewWriter(io.Discard)
1979
+ bw.Flush()
1980
+ bw.WriteByte('a')
1981
+ bw.Flush()
1982
+ bw.WriteRune('B')
1983
+ bw.Flush()
1984
+ bw.Write(bs)
1985
+ bw.Flush()
1986
+ bw.WriteString(str)
1987
+ bw.Flush()
1988
+ }
1989
+ }
1990
+
1991
+ func BenchmarkWriterFlush(b *testing.B) {
1992
+ b.ReportAllocs()
1993
+ bw := NewWriter(io.Discard)
1994
+ str := strings.Repeat("x", 50)
1995
+ for i := 0; i < b.N; i++ {
1996
+ bw.WriteString(str)
1997
+ bw.Flush()
1998
+ }
1999
+ }
go/src/bufio/example_test.go ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bufio_test
6
+
7
+ import (
8
+ "bufio"
9
+ "bytes"
10
+ "fmt"
11
+ "os"
12
+ "strconv"
13
+ "strings"
14
+ )
15
+
16
+ func ExampleWriter() {
17
+ w := bufio.NewWriter(os.Stdout)
18
+ fmt.Fprint(w, "Hello, ")
19
+ fmt.Fprint(w, "world!")
20
+ w.Flush() // Don't forget to flush!
21
+ // Output: Hello, world!
22
+ }
23
+
24
+ func ExampleWriter_AvailableBuffer() {
25
+ w := bufio.NewWriter(os.Stdout)
26
+ for _, i := range []int64{1, 2, 3, 4} {
27
+ b := w.AvailableBuffer()
28
+ b = strconv.AppendInt(b, i, 10)
29
+ b = append(b, ' ')
30
+ w.Write(b)
31
+ }
32
+ w.Flush()
33
+ // Output: 1 2 3 4
34
+ }
35
+
36
+ // ExampleWriter_ReadFrom demonstrates how to use the ReadFrom method of Writer.
37
+ func ExampleWriter_ReadFrom() {
38
+ var buf bytes.Buffer
39
+ writer := bufio.NewWriter(&buf)
40
+
41
+ data := "Hello, world!\nThis is a ReadFrom example."
42
+ reader := strings.NewReader(data)
43
+
44
+ n, err := writer.ReadFrom(reader)
45
+ if err != nil {
46
+ fmt.Println("ReadFrom Error:", err)
47
+ return
48
+ }
49
+
50
+ if err = writer.Flush(); err != nil {
51
+ fmt.Println("Flush Error:", err)
52
+ return
53
+ }
54
+
55
+ fmt.Println("Bytes written:", n)
56
+ fmt.Println("Buffer contents:", buf.String())
57
+ // Output:
58
+ // Bytes written: 41
59
+ // Buffer contents: Hello, world!
60
+ // This is a ReadFrom example.
61
+ }
62
+
63
+ // The simplest use of a Scanner, to read standard input as a set of lines.
64
+ func ExampleScanner_lines() {
65
+ scanner := bufio.NewScanner(os.Stdin)
66
+ for scanner.Scan() {
67
+ fmt.Println(scanner.Text()) // Println will add back the final '\n'
68
+ }
69
+ if err := scanner.Err(); err != nil {
70
+ fmt.Fprintln(os.Stderr, "reading standard input:", err)
71
+ }
72
+ }
73
+
74
+ // Return the most recent call to Scan as a []byte.
75
+ func ExampleScanner_Bytes() {
76
+ scanner := bufio.NewScanner(strings.NewReader("gopher"))
77
+ for scanner.Scan() {
78
+ fmt.Println(len(scanner.Bytes()) == 6)
79
+ }
80
+ if err := scanner.Err(); err != nil {
81
+ fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
82
+ }
83
+ // Output:
84
+ // true
85
+ }
86
+
87
+ // Use a Scanner to implement a simple word-count utility by scanning the
88
+ // input as a sequence of space-delimited tokens.
89
+ func ExampleScanner_words() {
90
+ // An artificial input source.
91
+ const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
92
+ scanner := bufio.NewScanner(strings.NewReader(input))
93
+ // Set the split function for the scanning operation.
94
+ scanner.Split(bufio.ScanWords)
95
+ // Count the words.
96
+ count := 0
97
+ for scanner.Scan() {
98
+ count++
99
+ }
100
+ if err := scanner.Err(); err != nil {
101
+ fmt.Fprintln(os.Stderr, "reading input:", err)
102
+ }
103
+ fmt.Printf("%d\n", count)
104
+ // Output: 15
105
+ }
106
+
107
+ // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
108
+ // 32-bit decimal input.
109
+ func ExampleScanner_custom() {
110
+ // An artificial input source.
111
+ const input = "1234 5678 1234567901234567890"
112
+ scanner := bufio.NewScanner(strings.NewReader(input))
113
+ // Create a custom split function by wrapping the existing ScanWords function.
114
+ split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
115
+ advance, token, err = bufio.ScanWords(data, atEOF)
116
+ if err == nil && token != nil {
117
+ _, err = strconv.ParseInt(string(token), 10, 32)
118
+ }
119
+ return
120
+ }
121
+ // Set the split function for the scanning operation.
122
+ scanner.Split(split)
123
+ // Validate the input
124
+ for scanner.Scan() {
125
+ fmt.Printf("%s\n", scanner.Text())
126
+ }
127
+
128
+ if err := scanner.Err(); err != nil {
129
+ fmt.Printf("Invalid input: %s", err)
130
+ }
131
+ // Output:
132
+ // 1234
133
+ // 5678
134
+ // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
135
+ }
136
+
137
+ // Use a Scanner with a custom split function to parse a comma-separated
138
+ // list with an empty final value.
139
+ func ExampleScanner_emptyFinalToken() {
140
+ // Comma-separated list; last entry is empty.
141
+ const input = "1,2,3,4,"
142
+ scanner := bufio.NewScanner(strings.NewReader(input))
143
+ // Define a split function that separates on commas.
144
+ onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
145
+ for i := 0; i < len(data); i++ {
146
+ if data[i] == ',' {
147
+ return i + 1, data[:i], nil
148
+ }
149
+ }
150
+ if !atEOF {
151
+ return 0, nil, nil
152
+ }
153
+ // There is one final token to be delivered, which may be the empty string.
154
+ // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
155
+ // but does not trigger an error to be returned from Scan itself.
156
+ return 0, data, bufio.ErrFinalToken
157
+ }
158
+ scanner.Split(onComma)
159
+ // Scan.
160
+ for scanner.Scan() {
161
+ fmt.Printf("%q ", scanner.Text())
162
+ }
163
+ if err := scanner.Err(); err != nil {
164
+ fmt.Fprintln(os.Stderr, "reading input:", err)
165
+ }
166
+ // Output: "1" "2" "3" "4" ""
167
+ }
168
+
169
+ // Use a Scanner with a custom split function to parse a comma-separated
170
+ // list with an empty final value but stops at the token "STOP".
171
+ func ExampleScanner_earlyStop() {
172
+ onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
173
+ i := bytes.IndexByte(data, ',')
174
+ if i == -1 {
175
+ if !atEOF {
176
+ return 0, nil, nil
177
+ }
178
+ // If we have reached the end, return the last token.
179
+ return 0, data, bufio.ErrFinalToken
180
+ }
181
+ // If the token is "STOP", stop the scanning and ignore the rest.
182
+ if string(data[:i]) == "STOP" {
183
+ return i + 1, nil, bufio.ErrFinalToken
184
+ }
185
+ // Otherwise, return the token before the comma.
186
+ return i + 1, data[:i], nil
187
+ }
188
+ const input = "1,2,STOP,4,"
189
+ scanner := bufio.NewScanner(strings.NewReader(input))
190
+ scanner.Split(onComma)
191
+ for scanner.Scan() {
192
+ fmt.Printf("Got a token %q\n", scanner.Text())
193
+ }
194
+ if err := scanner.Err(); err != nil {
195
+ fmt.Fprintln(os.Stderr, "reading input:", err)
196
+ }
197
+ // Output:
198
+ // Got a token "1"
199
+ // Got a token "2"
200
+ }
go/src/bufio/export_test.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bufio
6
+
7
+ // Exported for testing only.
8
+ import (
9
+ "unicode/utf8"
10
+ )
11
+
12
+ var IsSpace = isSpace
13
+
14
+ const DefaultBufSize = defaultBufSize
15
+
16
+ func (s *Scanner) MaxTokenSize(n int) {
17
+ if n < utf8.UTFMax || n > 1e9 {
18
+ panic("bad max token size")
19
+ }
20
+ if n < len(s.buf) {
21
+ s.buf = make([]byte, n)
22
+ }
23
+ s.maxTokenSize = n
24
+ }
25
+
26
+ // ErrOrEOF is like Err, but returns EOF. Used to test a corner case.
27
+ func (s *Scanner) ErrOrEOF() error {
28
+ return s.err
29
+ }
go/src/bufio/net_test.go ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build unix
6
+
7
+ package bufio_test
8
+
9
+ import (
10
+ "bufio"
11
+ "io"
12
+ "net"
13
+ "path/filepath"
14
+ "strings"
15
+ "sync"
16
+ "testing"
17
+ )
18
+
19
+ // TestCopyUnixpacket tests that we can use bufio when copying
20
+ // across a unixpacket socket. This used to fail due to an unnecessary
21
+ // empty Write call that was interpreted as an EOF.
22
+ func TestCopyUnixpacket(t *testing.T) {
23
+ tmpDir := t.TempDir()
24
+ socket := filepath.Join(tmpDir, "unixsock")
25
+
26
+ // Start a unixpacket server.
27
+ addr := &net.UnixAddr{
28
+ Name: socket,
29
+ Net: "unixpacket",
30
+ }
31
+ server, err := net.ListenUnix("unixpacket", addr)
32
+ if err != nil {
33
+ t.Skipf("skipping test because opening a unixpacket socket failed: %v", err)
34
+ }
35
+
36
+ // Start a goroutine for the server to accept one connection
37
+ // and read all the data sent on the connection,
38
+ // reporting the number of bytes read on ch.
39
+ ch := make(chan int, 1)
40
+ var wg sync.WaitGroup
41
+ wg.Add(1)
42
+ go func() {
43
+ defer wg.Done()
44
+
45
+ tot := 0
46
+ defer func() {
47
+ ch <- tot
48
+ }()
49
+
50
+ serverConn, err := server.Accept()
51
+ if err != nil {
52
+ t.Error(err)
53
+ return
54
+ }
55
+
56
+ buf := make([]byte, 1024)
57
+ for {
58
+ n, err := serverConn.Read(buf)
59
+ tot += n
60
+ if err == io.EOF {
61
+ return
62
+ }
63
+ if err != nil {
64
+ t.Error(err)
65
+ return
66
+ }
67
+ }
68
+ }()
69
+
70
+ clientConn, err := net.DialUnix("unixpacket", nil, addr)
71
+ if err != nil {
72
+ // Leaves the server goroutine hanging. Oh well.
73
+ t.Fatal(err)
74
+ }
75
+
76
+ defer wg.Wait()
77
+ defer clientConn.Close()
78
+
79
+ const data = "data"
80
+ r := bufio.NewReader(strings.NewReader(data))
81
+ n, err := io.Copy(clientConn, r)
82
+ if err != nil {
83
+ t.Fatal(err)
84
+ }
85
+
86
+ if n != int64(len(data)) {
87
+ t.Errorf("io.Copy returned %d, want %d", n, len(data))
88
+ }
89
+
90
+ clientConn.Close()
91
+ tot := <-ch
92
+
93
+ if tot != len(data) {
94
+ t.Errorf("server read %d, want %d", tot, len(data))
95
+ }
96
+ }
go/src/bufio/scan.go ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bufio
6
+
7
+ import (
8
+ "bytes"
9
+ "errors"
10
+ "io"
11
+ "unicode/utf8"
12
+ )
13
+
14
+ // Scanner provides a convenient interface for reading data such as
15
+ // a file of newline-delimited lines of text. Successive calls to
16
+ // the [Scanner.Scan] method will step through the 'tokens' of a file, skipping
17
+ // the bytes between the tokens. The specification of a token is
18
+ // defined by a split function of type [SplitFunc]; the default split
19
+ // function breaks the input into lines with line termination stripped. [Scanner.Split]
20
+ // functions are defined in this package for scanning a file into
21
+ // lines, bytes, UTF-8-encoded runes, and space-delimited words. The
22
+ // client may instead provide a custom split function.
23
+ //
24
+ // Scanning stops unrecoverably at EOF, the first I/O error, or a token too
25
+ // large to fit in the [Scanner.Buffer]. When a scan stops, the reader may have
26
+ // advanced arbitrarily far past the last token. Programs that need more
27
+ // control over error handling or large tokens, or must run sequential scans
28
+ // on a reader, should use [bufio.Reader] instead.
29
+ type Scanner struct {
30
+ r io.Reader // The reader provided by the client.
31
+ split SplitFunc // The function to split the tokens.
32
+ maxTokenSize int // Maximum size of a token; modified by tests.
33
+ token []byte // Last token returned by split.
34
+ buf []byte // Buffer used as argument to split.
35
+ start int // First non-processed byte in buf.
36
+ end int // End of data in buf.
37
+ err error // Sticky error.
38
+ empties int // Count of successive empty tokens.
39
+ scanCalled bool // Scan has been called; buffer is in use.
40
+ done bool // Scan has finished.
41
+ }
42
+
43
+ // SplitFunc is the signature of the split function used to tokenize the
44
+ // input. The arguments are an initial substring of the remaining unprocessed
45
+ // data and a flag, atEOF, that reports whether the [Reader] has no more data
46
+ // to give. The return values are the number of bytes to advance the input
47
+ // and the next token to return to the user, if any, plus an error, if any.
48
+ //
49
+ // Scanning stops if the function returns an error, in which case some of
50
+ // the input may be discarded. If that error is [ErrFinalToken], scanning
51
+ // stops with no error. A non-nil token delivered with [ErrFinalToken]
52
+ // will be the last token, and a nil token with [ErrFinalToken]
53
+ // immediately stops the scanning.
54
+ //
55
+ // Otherwise, the [Scanner] advances the input. If the token is not nil,
56
+ // the [Scanner] returns it to the user. If the token is nil, the
57
+ // Scanner reads more data and continues scanning; if there is no more
58
+ // data--if atEOF was true--the [Scanner] returns. If the data does not
59
+ // yet hold a complete token, for instance if it has no newline while
60
+ // scanning lines, a [SplitFunc] can return (0, nil, nil) to signal the
61
+ // [Scanner] to read more data into the slice and try again with a
62
+ // longer slice starting at the same point in the input.
63
+ //
64
+ // The function is never called with an empty data slice unless atEOF
65
+ // is true. If atEOF is true, however, data may be non-empty and,
66
+ // as always, holds unprocessed text.
67
+ type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)
68
+
69
+ // Errors returned by Scanner.
70
+ var (
71
+ ErrTooLong = errors.New("bufio.Scanner: token too long")
72
+ ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
73
+ ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
74
+ ErrBadReadCount = errors.New("bufio.Scanner: Read returned impossible count")
75
+ )
76
+
77
+ const (
78
+ // MaxScanTokenSize is the maximum size used to buffer a token
79
+ // unless the user provides an explicit buffer with [Scanner.Buffer].
80
+ // The actual maximum token size may be smaller as the buffer
81
+ // may need to include, for instance, a newline.
82
+ MaxScanTokenSize = 64 * 1024
83
+
84
+ startBufSize = 4096 // Size of initial allocation for buffer.
85
+ )
86
+
87
+ // NewScanner returns a new [Scanner] to read from r.
88
+ // The split function defaults to [ScanLines].
89
+ func NewScanner(r io.Reader) *Scanner {
90
+ return &Scanner{
91
+ r: r,
92
+ split: ScanLines,
93
+ maxTokenSize: MaxScanTokenSize,
94
+ }
95
+ }
96
+
97
+ // Err returns the first non-EOF error that was encountered by the [Scanner].
98
+ func (s *Scanner) Err() error {
99
+ if s.err == io.EOF {
100
+ return nil
101
+ }
102
+ return s.err
103
+ }
104
+
105
+ // Bytes returns the most recent token generated by a call to [Scanner.Scan].
106
+ // The underlying array may point to data that will be overwritten
107
+ // by a subsequent call to Scan. It does no allocation.
108
+ func (s *Scanner) Bytes() []byte {
109
+ return s.token
110
+ }
111
+
112
+ // Text returns the most recent token generated by a call to [Scanner.Scan]
113
+ // as a newly allocated string holding its bytes.
114
+ func (s *Scanner) Text() string {
115
+ return string(s.token)
116
+ }
117
+
118
+ // ErrFinalToken is a special sentinel error value. It is intended to be
119
+ // returned by a Split function to indicate that the scanning should stop
120
+ // with no error. If the token being delivered with this error is not nil,
121
+ // the token is the last token.
122
+ //
123
+ // The value is useful to stop processing early or when it is necessary to
124
+ // deliver a final empty token (which is different from a nil token).
125
+ // One could achieve the same behavior with a custom error value but
126
+ // providing one here is tidier.
127
+ // See the emptyFinalToken example for a use of this value.
128
+ var ErrFinalToken = errors.New("final token")
129
+
130
+ // Scan advances the [Scanner] to the next token, which will then be
131
+ // available through the [Scanner.Bytes] or [Scanner.Text] method. It returns false when
132
+ // there are no more tokens, either by reaching the end of the input or an error.
133
+ // After Scan returns false, the [Scanner.Err] method will return any error that
134
+ // occurred during scanning, except that if it was [io.EOF], [Scanner.Err]
135
+ // will return nil.
136
+ // Scan panics if the split function returns too many empty
137
+ // tokens without advancing the input. This is a common error mode for
138
+ // scanners.
139
+ func (s *Scanner) Scan() bool {
140
+ if s.done {
141
+ return false
142
+ }
143
+ s.scanCalled = true
144
+ // Loop until we have a token.
145
+ for {
146
+ // See if we can get a token with what we already have.
147
+ // If we've run out of data but have an error, give the split function
148
+ // a chance to recover any remaining, possibly empty token.
149
+ if s.end > s.start || s.err != nil {
150
+ advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
151
+ if err != nil {
152
+ if err == ErrFinalToken {
153
+ s.token = token
154
+ s.done = true
155
+ // When token is not nil, it means the scanning stops
156
+ // with a trailing token, and thus the return value
157
+ // should be true to indicate the existence of the token.
158
+ return token != nil
159
+ }
160
+ s.setErr(err)
161
+ return false
162
+ }
163
+ if !s.advance(advance) {
164
+ return false
165
+ }
166
+ s.token = token
167
+ if token != nil {
168
+ if s.err == nil || advance > 0 {
169
+ s.empties = 0
170
+ } else {
171
+ // Returning tokens not advancing input at EOF.
172
+ s.empties++
173
+ if s.empties > maxConsecutiveEmptyReads {
174
+ panic("bufio.Scan: too many empty tokens without progressing")
175
+ }
176
+ }
177
+ return true
178
+ }
179
+ }
180
+ // We cannot generate a token with what we are holding.
181
+ // If we've already hit EOF or an I/O error, we are done.
182
+ if s.err != nil {
183
+ // Shut it down.
184
+ s.start = 0
185
+ s.end = 0
186
+ return false
187
+ }
188
+ // Must read more data.
189
+ // First, shift data to beginning of buffer if there's lots of empty space
190
+ // or space is needed.
191
+ if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
192
+ copy(s.buf, s.buf[s.start:s.end])
193
+ s.end -= s.start
194
+ s.start = 0
195
+ }
196
+ // Is the buffer full? If so, resize.
197
+ if s.end == len(s.buf) {
198
+ // Guarantee no overflow in the multiplication below.
199
+ const maxInt = int(^uint(0) >> 1)
200
+ if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 {
201
+ s.setErr(ErrTooLong)
202
+ return false
203
+ }
204
+ newSize := len(s.buf) * 2
205
+ if newSize == 0 {
206
+ newSize = startBufSize
207
+ }
208
+ newSize = min(newSize, s.maxTokenSize)
209
+ newBuf := make([]byte, newSize)
210
+ copy(newBuf, s.buf[s.start:s.end])
211
+ s.buf = newBuf
212
+ s.end -= s.start
213
+ s.start = 0
214
+ }
215
+ // Finally we can read some input. Make sure we don't get stuck with
216
+ // a misbehaving Reader. Officially we don't need to do this, but let's
217
+ // be extra careful: Scanner is for safe, simple jobs.
218
+ for loop := 0; ; {
219
+ n, err := s.r.Read(s.buf[s.end:len(s.buf)])
220
+ if n < 0 || len(s.buf)-s.end < n {
221
+ s.setErr(ErrBadReadCount)
222
+ break
223
+ }
224
+ s.end += n
225
+ if err != nil {
226
+ s.setErr(err)
227
+ break
228
+ }
229
+ if n > 0 {
230
+ s.empties = 0
231
+ break
232
+ }
233
+ loop++
234
+ if loop > maxConsecutiveEmptyReads {
235
+ s.setErr(io.ErrNoProgress)
236
+ break
237
+ }
238
+ }
239
+ }
240
+ }
241
+
242
+ // advance consumes n bytes of the buffer. It reports whether the advance was legal.
243
+ func (s *Scanner) advance(n int) bool {
244
+ if n < 0 {
245
+ s.setErr(ErrNegativeAdvance)
246
+ return false
247
+ }
248
+ if n > s.end-s.start {
249
+ s.setErr(ErrAdvanceTooFar)
250
+ return false
251
+ }
252
+ s.start += n
253
+ return true
254
+ }
255
+
256
+ // setErr records the first error encountered.
257
+ func (s *Scanner) setErr(err error) {
258
+ if s.err == nil || s.err == io.EOF {
259
+ s.err = err
260
+ }
261
+ }
262
+
263
+ // Buffer controls memory allocation by the Scanner.
264
+ // It sets the initial buffer to use when scanning
265
+ // and the maximum size of buffer that may be allocated during scanning.
266
+ // The contents of the buffer are ignored.
267
+ //
268
+ // The maximum token size must be less than the larger of max and cap(buf).
269
+ // If max <= cap(buf), [Scanner.Scan] will use this buffer only and do no allocation.
270
+ //
271
+ // By default, [Scanner.Scan] uses an internal buffer and sets the
272
+ // maximum token size to [MaxScanTokenSize].
273
+ //
274
+ // Buffer panics if it is called after scanning has started.
275
+ func (s *Scanner) Buffer(buf []byte, max int) {
276
+ if s.scanCalled {
277
+ panic("Buffer called after Scan")
278
+ }
279
+ s.buf = buf[0:cap(buf)]
280
+ s.maxTokenSize = max
281
+ }
282
+
283
+ // Split sets the split function for the [Scanner].
284
+ // The default split function is [ScanLines].
285
+ //
286
+ // Split panics if it is called after scanning has started.
287
+ func (s *Scanner) Split(split SplitFunc) {
288
+ if s.scanCalled {
289
+ panic("Split called after Scan")
290
+ }
291
+ s.split = split
292
+ }
293
+
294
+ // Split functions
295
+
296
+ // ScanBytes is a split function for a [Scanner] that returns each byte as a token.
297
+ func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
298
+ if atEOF && len(data) == 0 {
299
+ return 0, nil, nil
300
+ }
301
+ return 1, data[0:1], nil
302
+ }
303
+
304
+ var errorRune = []byte(string(utf8.RuneError))
305
+
306
+ // ScanRunes is a split function for a [Scanner] that returns each
307
+ // UTF-8-encoded rune as a token. The sequence of runes returned is
308
+ // equivalent to that from a range loop over the input as a string, which
309
+ // means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
310
+ // Because of the Scan interface, this makes it impossible for the client to
311
+ // distinguish correctly encoded replacement runes from encoding errors.
312
+ func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
313
+ if atEOF && len(data) == 0 {
314
+ return 0, nil, nil
315
+ }
316
+
317
+ // Fast path 1: ASCII.
318
+ if data[0] < utf8.RuneSelf {
319
+ return 1, data[0:1], nil
320
+ }
321
+
322
+ // Fast path 2: Correct UTF-8 decode without error.
323
+ _, width := utf8.DecodeRune(data)
324
+ if width > 1 {
325
+ // It's a valid encoding. Width cannot be one for a correctly encoded
326
+ // non-ASCII rune.
327
+ return width, data[0:width], nil
328
+ }
329
+
330
+ // We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
331
+ // Is the error because there wasn't a full rune to be decoded?
332
+ // FullRune distinguishes correctly between erroneous and incomplete encodings.
333
+ if !atEOF && !utf8.FullRune(data) {
334
+ // Incomplete; get more bytes.
335
+ return 0, nil, nil
336
+ }
337
+
338
+ // We have a real UTF-8 encoding error. Return a properly encoded error rune
339
+ // but advance only one byte. This matches the behavior of a range loop over
340
+ // an incorrectly encoded string.
341
+ return 1, errorRune, nil
342
+ }
343
+
344
+ // dropCR drops a terminal \r from the data.
345
+ func dropCR(data []byte) []byte {
346
+ if len(data) > 0 && data[len(data)-1] == '\r' {
347
+ return data[0 : len(data)-1]
348
+ }
349
+ return data
350
+ }
351
+
352
+ // ScanLines is a split function for a [Scanner] that returns each line of
353
+ // text, stripped of any trailing end-of-line marker. The returned line may
354
+ // be empty. The end-of-line marker is one optional carriage return followed
355
+ // by one mandatory newline. In regular expression notation, it is `\r?\n`.
356
+ // The last non-empty line of input will be returned even if it has no
357
+ // newline.
358
+ func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
359
+ if atEOF && len(data) == 0 {
360
+ return 0, nil, nil
361
+ }
362
+ if i := bytes.IndexByte(data, '\n'); i >= 0 {
363
+ // We have a full newline-terminated line.
364
+ return i + 1, dropCR(data[0:i]), nil
365
+ }
366
+ // If we're at EOF, we have a final, non-terminated line. Return it.
367
+ if atEOF {
368
+ return len(data), dropCR(data), nil
369
+ }
370
+ // Request more data.
371
+ return 0, nil, nil
372
+ }
373
+
374
+ // isSpace reports whether the character is a Unicode white space character.
375
+ // We avoid dependency on the unicode package, but check validity of the implementation
376
+ // in the tests.
377
+ func isSpace(r rune) bool {
378
+ if r <= '\u00FF' {
379
+ // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
380
+ switch r {
381
+ case ' ', '\t', '\n', '\v', '\f', '\r':
382
+ return true
383
+ case '\u0085', '\u00A0':
384
+ return true
385
+ }
386
+ return false
387
+ }
388
+ // High-valued ones.
389
+ if '\u2000' <= r && r <= '\u200a' {
390
+ return true
391
+ }
392
+ switch r {
393
+ case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
394
+ return true
395
+ }
396
+ return false
397
+ }
398
+
399
+ // ScanWords is a split function for a [Scanner] that returns each
400
+ // space-separated word of text, with surrounding spaces deleted. It will
401
+ // never return an empty string. The definition of space is set by
402
+ // unicode.IsSpace.
403
+ func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
404
+ // Skip leading spaces.
405
+ start := 0
406
+ for width := 0; start < len(data); start += width {
407
+ var r rune
408
+ r, width = utf8.DecodeRune(data[start:])
409
+ if !isSpace(r) {
410
+ break
411
+ }
412
+ }
413
+ // Scan until space, marking end of word.
414
+ for width, i := 0, start; i < len(data); i += width {
415
+ var r rune
416
+ r, width = utf8.DecodeRune(data[i:])
417
+ if isSpace(r) {
418
+ return i + width, data[start:i], nil
419
+ }
420
+ }
421
+ // If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
422
+ if atEOF && len(data) > start {
423
+ return len(data), data[start:], nil
424
+ }
425
+ // Request more data.
426
+ return start, nil, nil
427
+ }
go/src/bufio/scan_test.go ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bufio_test
6
+
7
+ import (
8
+ . "bufio"
9
+ "bytes"
10
+ "errors"
11
+ "io"
12
+ "strings"
13
+ "testing"
14
+ "unicode"
15
+ "unicode/utf8"
16
+ )
17
+
18
+ const smallMaxTokenSize = 256 // Much smaller for more efficient testing.
19
+
20
+ // Test white space table matches the Unicode definition.
21
+ func TestSpace(t *testing.T) {
22
+ for r := rune(0); r <= utf8.MaxRune; r++ {
23
+ if IsSpace(r) != unicode.IsSpace(r) {
24
+ t.Fatalf("white space property disagrees: %#U should be %t", r, unicode.IsSpace(r))
25
+ }
26
+ }
27
+ }
28
+
29
+ var scanTests = []string{
30
+ "",
31
+ "a",
32
+ "¼",
33
+ "☹",
34
+ "\x81", // UTF-8 error
35
+ "\uFFFD", // correctly encoded RuneError
36
+ "abcdefgh",
37
+ "abc def\n\t\tgh ",
38
+ "abc¼☹\x81\uFFFD日本語\x82abc",
39
+ }
40
+
41
+ func TestScanByte(t *testing.T) {
42
+ for n, test := range scanTests {
43
+ buf := strings.NewReader(test)
44
+ s := NewScanner(buf)
45
+ s.Split(ScanBytes)
46
+ var i int
47
+ for i = 0; s.Scan(); i++ {
48
+ if b := s.Bytes(); len(b) != 1 || b[0] != test[i] {
49
+ t.Errorf("#%d: %d: expected %q got %q", n, i, test, b)
50
+ }
51
+ }
52
+ if i != len(test) {
53
+ t.Errorf("#%d: termination expected at %d; got %d", n, len(test), i)
54
+ }
55
+ err := s.Err()
56
+ if err != nil {
57
+ t.Errorf("#%d: %v", n, err)
58
+ }
59
+ }
60
+ }
61
+
62
+ // Test that the rune splitter returns same sequence of runes (not bytes) as for range string.
63
+ func TestScanRune(t *testing.T) {
64
+ for n, test := range scanTests {
65
+ buf := strings.NewReader(test)
66
+ s := NewScanner(buf)
67
+ s.Split(ScanRunes)
68
+ var i, runeCount int
69
+ var expect rune
70
+ // Use a string range loop to validate the sequence of runes.
71
+ for i, expect = range test {
72
+ if !s.Scan() {
73
+ break
74
+ }
75
+ runeCount++
76
+ got, _ := utf8.DecodeRune(s.Bytes())
77
+ if got != expect {
78
+ t.Errorf("#%d: %d: expected %q got %q", n, i, expect, got)
79
+ }
80
+ }
81
+ if s.Scan() {
82
+ t.Errorf("#%d: scan ran too long, got %q", n, s.Text())
83
+ }
84
+ testRuneCount := utf8.RuneCountInString(test)
85
+ if runeCount != testRuneCount {
86
+ t.Errorf("#%d: termination expected at %d; got %d", n, testRuneCount, runeCount)
87
+ }
88
+ err := s.Err()
89
+ if err != nil {
90
+ t.Errorf("#%d: %v", n, err)
91
+ }
92
+ }
93
+ }
94
+
95
+ var wordScanTests = []string{
96
+ "",
97
+ " ",
98
+ "\n",
99
+ "a",
100
+ " a ",
101
+ "abc def",
102
+ " abc def ",
103
+ " abc\tdef\nghi\rjkl\fmno\vpqr\u0085stu\u00a0\n",
104
+ }
105
+
106
+ // Test that the word splitter returns the same data as strings.Fields.
107
+ func TestScanWords(t *testing.T) {
108
+ for n, test := range wordScanTests {
109
+ buf := strings.NewReader(test)
110
+ s := NewScanner(buf)
111
+ s.Split(ScanWords)
112
+ words := strings.Fields(test)
113
+ var wordCount int
114
+ for wordCount = 0; wordCount < len(words); wordCount++ {
115
+ if !s.Scan() {
116
+ break
117
+ }
118
+ got := s.Text()
119
+ if got != words[wordCount] {
120
+ t.Errorf("#%d: %d: expected %q got %q", n, wordCount, words[wordCount], got)
121
+ }
122
+ }
123
+ if s.Scan() {
124
+ t.Errorf("#%d: scan ran too long, got %q", n, s.Text())
125
+ }
126
+ if wordCount != len(words) {
127
+ t.Errorf("#%d: termination expected at %d; got %d", n, len(words), wordCount)
128
+ }
129
+ err := s.Err()
130
+ if err != nil {
131
+ t.Errorf("#%d: %v", n, err)
132
+ }
133
+ }
134
+ }
135
+
136
+ // slowReader is a reader that returns only a few bytes at a time, to test the incremental
137
+ // reads in Scanner.Scan.
138
+ type slowReader struct {
139
+ max int
140
+ buf io.Reader
141
+ }
142
+
143
+ func (sr *slowReader) Read(p []byte) (n int, err error) {
144
+ if len(p) > sr.max {
145
+ p = p[0:sr.max]
146
+ }
147
+ return sr.buf.Read(p)
148
+ }
149
+
150
+ // genLine writes to buf a predictable but non-trivial line of text of length
151
+ // n, including the terminal newline and an occasional carriage return.
152
+ // If addNewline is false, the \r and \n are not emitted.
153
+ func genLine(buf *bytes.Buffer, lineNum, n int, addNewline bool) {
154
+ buf.Reset()
155
+ doCR := lineNum%5 == 0
156
+ if doCR {
157
+ n--
158
+ }
159
+ for i := 0; i < n-1; i++ { // Stop early for \n.
160
+ c := 'a' + byte(lineNum+i)
161
+ if c == '\n' || c == '\r' { // Don't confuse us.
162
+ c = 'N'
163
+ }
164
+ buf.WriteByte(c)
165
+ }
166
+ if addNewline {
167
+ if doCR {
168
+ buf.WriteByte('\r')
169
+ }
170
+ buf.WriteByte('\n')
171
+ }
172
+ }
173
+
174
+ // Test the line splitter, including some carriage returns but no long lines.
175
+ func TestScanLongLines(t *testing.T) {
176
+ // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize.
177
+ tmp := new(bytes.Buffer)
178
+ buf := new(bytes.Buffer)
179
+ lineNum := 0
180
+ j := 0
181
+ for i := 0; i < 2*smallMaxTokenSize; i++ {
182
+ genLine(tmp, lineNum, j, true)
183
+ if j < smallMaxTokenSize {
184
+ j++
185
+ } else {
186
+ j--
187
+ }
188
+ buf.Write(tmp.Bytes())
189
+ lineNum++
190
+ }
191
+ s := NewScanner(&slowReader{1, buf})
192
+ s.Split(ScanLines)
193
+ s.MaxTokenSize(smallMaxTokenSize)
194
+ j = 0
195
+ for lineNum := 0; s.Scan(); lineNum++ {
196
+ genLine(tmp, lineNum, j, false)
197
+ if j < smallMaxTokenSize {
198
+ j++
199
+ } else {
200
+ j--
201
+ }
202
+ line := tmp.String() // We use the string-valued token here, for variety.
203
+ if s.Text() != line {
204
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Text(), line)
205
+ }
206
+ }
207
+ err := s.Err()
208
+ if err != nil {
209
+ t.Fatal(err)
210
+ }
211
+ }
212
+
213
+ // Test that the line splitter errors out on a long line.
214
+ func TestScanLineTooLong(t *testing.T) {
215
+ const smallMaxTokenSize = 256 // Much smaller for more efficient testing.
216
+ // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize.
217
+ tmp := new(bytes.Buffer)
218
+ buf := new(bytes.Buffer)
219
+ lineNum := 0
220
+ j := 0
221
+ for i := 0; i < 2*smallMaxTokenSize; i++ {
222
+ genLine(tmp, lineNum, j, true)
223
+ j++
224
+ buf.Write(tmp.Bytes())
225
+ lineNum++
226
+ }
227
+ s := NewScanner(&slowReader{3, buf})
228
+ s.Split(ScanLines)
229
+ s.MaxTokenSize(smallMaxTokenSize)
230
+ j = 0
231
+ for lineNum := 0; s.Scan(); lineNum++ {
232
+ genLine(tmp, lineNum, j, false)
233
+ if j < smallMaxTokenSize {
234
+ j++
235
+ } else {
236
+ j--
237
+ }
238
+ line := tmp.Bytes()
239
+ if !bytes.Equal(s.Bytes(), line) {
240
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line)
241
+ }
242
+ }
243
+ err := s.Err()
244
+ if err != ErrTooLong {
245
+ t.Fatalf("expected ErrTooLong; got %s", err)
246
+ }
247
+ }
248
+
249
+ // Test that the line splitter handles a final line without a newline.
250
+ func testNoNewline(text string, lines []string, t *testing.T) {
251
+ buf := strings.NewReader(text)
252
+ s := NewScanner(&slowReader{7, buf})
253
+ s.Split(ScanLines)
254
+ for lineNum := 0; s.Scan(); lineNum++ {
255
+ line := lines[lineNum]
256
+ if s.Text() != line {
257
+ t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line)
258
+ }
259
+ }
260
+ err := s.Err()
261
+ if err != nil {
262
+ t.Fatal(err)
263
+ }
264
+ }
265
+
266
+ // Test that the line splitter handles a final line without a newline.
267
+ func TestScanLineNoNewline(t *testing.T) {
268
+ const text = "abcdefghijklmn\nopqrstuvwxyz"
269
+ lines := []string{
270
+ "abcdefghijklmn",
271
+ "opqrstuvwxyz",
272
+ }
273
+ testNoNewline(text, lines, t)
274
+ }
275
+
276
+ // Test that the line splitter handles a final line with a carriage return but no newline.
277
+ func TestScanLineReturnButNoNewline(t *testing.T) {
278
+ const text = "abcdefghijklmn\nopqrstuvwxyz\r"
279
+ lines := []string{
280
+ "abcdefghijklmn",
281
+ "opqrstuvwxyz",
282
+ }
283
+ testNoNewline(text, lines, t)
284
+ }
285
+
286
+ // Test that the line splitter handles a final empty line.
287
+ func TestScanLineEmptyFinalLine(t *testing.T) {
288
+ const text = "abcdefghijklmn\nopqrstuvwxyz\n\n"
289
+ lines := []string{
290
+ "abcdefghijklmn",
291
+ "opqrstuvwxyz",
292
+ "",
293
+ }
294
+ testNoNewline(text, lines, t)
295
+ }
296
+
297
+ // Test that the line splitter handles a final empty line with a carriage return but no newline.
298
+ func TestScanLineEmptyFinalLineWithCR(t *testing.T) {
299
+ const text = "abcdefghijklmn\nopqrstuvwxyz\n\r"
300
+ lines := []string{
301
+ "abcdefghijklmn",
302
+ "opqrstuvwxyz",
303
+ "",
304
+ }
305
+ testNoNewline(text, lines, t)
306
+ }
307
+
308
+ var testError = errors.New("testError")
309
+
310
+ // Test the correct error is returned when the split function errors out.
311
+ func TestSplitError(t *testing.T) {
312
+ // Create a split function that delivers a little data, then a predictable error.
313
+ numSplits := 0
314
+ const okCount = 7
315
+ errorSplit := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
316
+ if atEOF {
317
+ panic("didn't get enough data")
318
+ }
319
+ if numSplits >= okCount {
320
+ return 0, nil, testError
321
+ }
322
+ numSplits++
323
+ return 1, data[0:1], nil
324
+ }
325
+ // Read the data.
326
+ const text = "abcdefghijklmnopqrstuvwxyz"
327
+ buf := strings.NewReader(text)
328
+ s := NewScanner(&slowReader{1, buf})
329
+ s.Split(errorSplit)
330
+ var i int
331
+ for i = 0; s.Scan(); i++ {
332
+ if len(s.Bytes()) != 1 || text[i] != s.Bytes()[0] {
333
+ t.Errorf("#%d: expected %q got %q", i, text[i], s.Bytes()[0])
334
+ }
335
+ }
336
+ // Check correct termination location and error.
337
+ if i != okCount {
338
+ t.Errorf("unexpected termination; expected %d tokens got %d", okCount, i)
339
+ }
340
+ err := s.Err()
341
+ if err != testError {
342
+ t.Fatalf("expected %q got %v", testError, err)
343
+ }
344
+ }
345
+
346
+ // Test that an EOF is overridden by a user-generated scan error.
347
+ func TestErrAtEOF(t *testing.T) {
348
+ s := NewScanner(strings.NewReader("1 2 33"))
349
+ // This splitter will fail on last entry, after s.err==EOF.
350
+ split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
351
+ advance, token, err = ScanWords(data, atEOF)
352
+ if len(token) > 1 {
353
+ if s.ErrOrEOF() != io.EOF {
354
+ t.Fatal("not testing EOF")
355
+ }
356
+ err = testError
357
+ }
358
+ return
359
+ }
360
+ s.Split(split)
361
+ for s.Scan() {
362
+ }
363
+ if s.Err() != testError {
364
+ t.Fatal("wrong error:", s.Err())
365
+ }
366
+ }
367
+
368
+ // Test for issue 5268.
369
+ type alwaysError struct{}
370
+
371
+ func (alwaysError) Read(p []byte) (int, error) {
372
+ return 0, io.ErrUnexpectedEOF
373
+ }
374
+
375
+ func TestNonEOFWithEmptyRead(t *testing.T) {
376
+ scanner := NewScanner(alwaysError{})
377
+ for scanner.Scan() {
378
+ t.Fatal("read should fail")
379
+ }
380
+ err := scanner.Err()
381
+ if err != io.ErrUnexpectedEOF {
382
+ t.Errorf("unexpected error: %v", err)
383
+ }
384
+ }
385
+
386
+ // Test that Scan finishes if we have endless empty reads.
387
+ type endlessZeros struct{}
388
+
389
+ func (endlessZeros) Read(p []byte) (int, error) {
390
+ return 0, nil
391
+ }
392
+
393
+ func TestBadReader(t *testing.T) {
394
+ scanner := NewScanner(endlessZeros{})
395
+ for scanner.Scan() {
396
+ t.Fatal("read should fail")
397
+ }
398
+ err := scanner.Err()
399
+ if err != io.ErrNoProgress {
400
+ t.Errorf("unexpected error: %v", err)
401
+ }
402
+ }
403
+
404
+ func TestScanWordsExcessiveWhiteSpace(t *testing.T) {
405
+ const word = "ipsum"
406
+ s := strings.Repeat(" ", 4*smallMaxTokenSize) + word
407
+ scanner := NewScanner(strings.NewReader(s))
408
+ scanner.MaxTokenSize(smallMaxTokenSize)
409
+ scanner.Split(ScanWords)
410
+ if !scanner.Scan() {
411
+ t.Fatalf("scan failed: %v", scanner.Err())
412
+ }
413
+ if token := scanner.Text(); token != word {
414
+ t.Fatalf("unexpected token: %v", token)
415
+ }
416
+ }
417
+
418
+ // Test that empty tokens, including at end of line or end of file, are found by the scanner.
419
+ // Issue 8672: Could miss final empty token.
420
+
421
+ func commaSplit(data []byte, atEOF bool) (advance int, token []byte, err error) {
422
+ for i := 0; i < len(data); i++ {
423
+ if data[i] == ',' {
424
+ return i + 1, data[:i], nil
425
+ }
426
+ }
427
+ return 0, data, ErrFinalToken
428
+ }
429
+
430
+ func testEmptyTokens(t *testing.T, text string, values []string) {
431
+ s := NewScanner(strings.NewReader(text))
432
+ s.Split(commaSplit)
433
+ var i int
434
+ for i = 0; s.Scan(); i++ {
435
+ if i >= len(values) {
436
+ t.Fatalf("got %d fields, expected %d", i+1, len(values))
437
+ }
438
+ if s.Text() != values[i] {
439
+ t.Errorf("%d: expected %q got %q", i, values[i], s.Text())
440
+ }
441
+ }
442
+ if i != len(values) {
443
+ t.Fatalf("got %d fields, expected %d", i, len(values))
444
+ }
445
+ if err := s.Err(); err != nil {
446
+ t.Fatal(err)
447
+ }
448
+ }
449
+
450
+ func TestEmptyTokens(t *testing.T) {
451
+ testEmptyTokens(t, "1,2,3,", []string{"1", "2", "3", ""})
452
+ }
453
+
454
+ func TestWithNoEmptyTokens(t *testing.T) {
455
+ testEmptyTokens(t, "1,2,3", []string{"1", "2", "3"})
456
+ }
457
+
458
+ func loopAtEOFSplit(data []byte, atEOF bool) (advance int, token []byte, err error) {
459
+ if len(data) > 0 {
460
+ return 1, data[:1], nil
461
+ }
462
+ return 0, data, nil
463
+ }
464
+
465
+ func TestDontLoopForever(t *testing.T) {
466
+ s := NewScanner(strings.NewReader("abc"))
467
+ s.Split(loopAtEOFSplit)
468
+ // Expect a panic
469
+ defer func() {
470
+ err := recover()
471
+ if err == nil {
472
+ t.Fatal("should have panicked")
473
+ }
474
+ if msg, ok := err.(string); !ok || !strings.Contains(msg, "empty tokens") {
475
+ panic(err)
476
+ }
477
+ }()
478
+ for count := 0; s.Scan(); count++ {
479
+ if count > 1000 {
480
+ t.Fatal("looping")
481
+ }
482
+ }
483
+ if s.Err() != nil {
484
+ t.Fatal("after scan:", s.Err())
485
+ }
486
+ }
487
+
488
+ func TestBlankLines(t *testing.T) {
489
+ s := NewScanner(strings.NewReader(strings.Repeat("\n", 1000)))
490
+ for count := 0; s.Scan(); count++ {
491
+ if count > 2000 {
492
+ t.Fatal("looping")
493
+ }
494
+ }
495
+ if s.Err() != nil {
496
+ t.Fatal("after scan:", s.Err())
497
+ }
498
+ }
499
+
500
+ type countdown int
501
+
502
+ func (c *countdown) split(data []byte, atEOF bool) (advance int, token []byte, err error) {
503
+ if *c > 0 {
504
+ *c--
505
+ return 1, data[:1], nil
506
+ }
507
+ return 0, nil, nil
508
+ }
509
+
510
+ // Check that the looping-at-EOF check doesn't trigger for merely empty tokens.
511
+ func TestEmptyLinesOK(t *testing.T) {
512
+ c := countdown(10000)
513
+ s := NewScanner(strings.NewReader(strings.Repeat("\n", 10000)))
514
+ s.Split(c.split)
515
+ for s.Scan() {
516
+ }
517
+ if s.Err() != nil {
518
+ t.Fatal("after scan:", s.Err())
519
+ }
520
+ if c != 0 {
521
+ t.Fatalf("stopped with %d left to process", c)
522
+ }
523
+ }
524
+
525
+ // Make sure we can read a huge token if a big enough buffer is provided.
526
+ func TestHugeBuffer(t *testing.T) {
527
+ text := strings.Repeat("x", 2*MaxScanTokenSize)
528
+ s := NewScanner(strings.NewReader(text + "\n"))
529
+ s.Buffer(make([]byte, 100), 3*MaxScanTokenSize)
530
+ for s.Scan() {
531
+ token := s.Text()
532
+ if token != text {
533
+ t.Errorf("scan got incorrect token of length %d", len(token))
534
+ }
535
+ }
536
+ if s.Err() != nil {
537
+ t.Fatal("after scan:", s.Err())
538
+ }
539
+ }
540
+
541
+ // negativeEOFReader returns an invalid -1 at the end, as though it
542
+ // were wrapping the read system call.
543
+ type negativeEOFReader int
544
+
545
+ func (r *negativeEOFReader) Read(p []byte) (int, error) {
546
+ if *r > 0 {
547
+ c := int(*r)
548
+ if c > len(p) {
549
+ c = len(p)
550
+ }
551
+ for i := 0; i < c; i++ {
552
+ p[i] = 'a'
553
+ }
554
+ p[c-1] = '\n'
555
+ *r -= negativeEOFReader(c)
556
+ return c, nil
557
+ }
558
+ return -1, io.EOF
559
+ }
560
+
561
+ // Test that the scanner doesn't panic and returns ErrBadReadCount
562
+ // on a reader that returns a negative count of bytes read (issue 38053).
563
+ func TestNegativeEOFReader(t *testing.T) {
564
+ r := negativeEOFReader(10)
565
+ scanner := NewScanner(&r)
566
+ c := 0
567
+ for scanner.Scan() {
568
+ c++
569
+ if c > 1 {
570
+ t.Error("read too many lines")
571
+ break
572
+ }
573
+ }
574
+ if got, want := scanner.Err(), ErrBadReadCount; got != want {
575
+ t.Errorf("scanner.Err: got %v, want %v", got, want)
576
+ }
577
+ }
578
+
579
+ // largeReader returns an invalid count that is larger than the number
580
+ // of bytes requested.
581
+ type largeReader struct{}
582
+
583
+ func (largeReader) Read(p []byte) (int, error) {
584
+ return len(p) + 1, nil
585
+ }
586
+
587
+ // Test that the scanner doesn't panic and returns ErrBadReadCount
588
+ // on a reader that returns an impossibly large count of bytes read (issue 38053).
589
+ func TestLargeReader(t *testing.T) {
590
+ scanner := NewScanner(largeReader{})
591
+ for scanner.Scan() {
592
+ }
593
+ if got, want := scanner.Err(), ErrBadReadCount; got != want {
594
+ t.Errorf("scanner.Err: got %v, want %v", got, want)
595
+ }
596
+ }
go/src/builtin/builtin.go ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ /*
6
+ Package builtin provides documentation for Go's predeclared identifiers.
7
+ The items documented here are not actually in package builtin
8
+ but their descriptions here allow godoc to present documentation
9
+ for the language's special identifiers.
10
+ */
11
+ package builtin
12
+
13
+ import "cmp"
14
+
15
+ // bool is the set of boolean values, true and false.
16
+ type bool bool
17
+
18
+ // true and false are the two untyped boolean values.
19
+ const (
20
+ true = 0 == 0 // Untyped bool.
21
+ false = 0 != 0 // Untyped bool.
22
+ )
23
+
24
+ // uint8 is the set of all unsigned 8-bit integers.
25
+ // Range: 0 through 255.
26
+ type uint8 uint8
27
+
28
+ // uint16 is the set of all unsigned 16-bit integers.
29
+ // Range: 0 through 65535.
30
+ type uint16 uint16
31
+
32
+ // uint32 is the set of all unsigned 32-bit integers.
33
+ // Range: 0 through 4294967295.
34
+ type uint32 uint32
35
+
36
+ // uint64 is the set of all unsigned 64-bit integers.
37
+ // Range: 0 through 18446744073709551615.
38
+ type uint64 uint64
39
+
40
+ // int8 is the set of all signed 8-bit integers.
41
+ // Range: -128 through 127.
42
+ type int8 int8
43
+
44
+ // int16 is the set of all signed 16-bit integers.
45
+ // Range: -32768 through 32767.
46
+ type int16 int16
47
+
48
+ // int32 is the set of all signed 32-bit integers.
49
+ // Range: -2147483648 through 2147483647.
50
+ type int32 int32
51
+
52
+ // int64 is the set of all signed 64-bit integers.
53
+ // Range: -9223372036854775808 through 9223372036854775807.
54
+ type int64 int64
55
+
56
+ // float32 is the set of all IEEE 754 32-bit floating-point numbers.
57
+ type float32 float32
58
+
59
+ // float64 is the set of all IEEE 754 64-bit floating-point numbers.
60
+ type float64 float64
61
+
62
+ // complex64 is the set of all complex numbers with float32 real and
63
+ // imaginary parts.
64
+ type complex64 complex64
65
+
66
+ // complex128 is the set of all complex numbers with float64 real and
67
+ // imaginary parts.
68
+ type complex128 complex128
69
+
70
+ // string is the set of all strings of 8-bit bytes, conventionally but not
71
+ // necessarily representing UTF-8-encoded text. A string may be empty, but
72
+ // not nil. Values of string type are immutable.
73
+ type string string
74
+
75
+ // int is a signed integer type that is at least 32 bits in size. It is a
76
+ // distinct type, however, and not an alias for, say, int32.
77
+ type int int
78
+
79
+ // uint is an unsigned integer type that is at least 32 bits in size. It is a
80
+ // distinct type, however, and not an alias for, say, uint32.
81
+ type uint uint
82
+
83
+ // uintptr is an integer type that is large enough to hold the bit pattern of
84
+ // any pointer.
85
+ type uintptr uintptr
86
+
87
+ // byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
88
+ // used, by convention, to distinguish byte values from 8-bit unsigned
89
+ // integer values.
90
+ type byte = uint8
91
+
92
+ // rune is an alias for int32 and is equivalent to int32 in all ways. It is
93
+ // used, by convention, to distinguish character values from integer values.
94
+ type rune = int32
95
+
96
+ // any is an alias for interface{} and is equivalent to interface{} in all ways.
97
+ type any = interface{}
98
+
99
+ // comparable is an interface that is implemented by all comparable types
100
+ // (booleans, numbers, strings, pointers, channels, arrays of comparable types,
101
+ // structs whose fields are all comparable types).
102
+ // The comparable interface may only be used as a type parameter constraint,
103
+ // not as the type of a variable.
104
+ type comparable interface{ comparable }
105
+
106
+ // iota is a predeclared identifier representing the untyped integer ordinal
107
+ // number of the current const specification in a (usually parenthesized)
108
+ // const declaration. It is zero-indexed.
109
+ const iota = 0 // Untyped int.
110
+
111
+ // nil is a predeclared identifier representing the zero value for a
112
+ // pointer, channel, func, interface, map, or slice type.
113
+ var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
114
+
115
+ // Type is here for the purposes of documentation only. It is a stand-in
116
+ // for any Go type, but represents the same type for any given function
117
+ // invocation.
118
+ type Type int
119
+
120
+ // Type1 is here for the purposes of documentation only. It is a stand-in
121
+ // for any Go type, but represents the same type for any given function
122
+ // invocation.
123
+ type Type1 int
124
+
125
+ // TypeOrExpr is here for the purposes of documentation only. It is a stand-in
126
+ // for either a Go type or an expression.
127
+ type TypeOrExpr int
128
+
129
+ // IntegerType is here for the purposes of documentation only. It is a stand-in
130
+ // for any integer type: int, uint, int8 etc.
131
+ type IntegerType int
132
+
133
+ // FloatType is here for the purposes of documentation only. It is a stand-in
134
+ // for either float type: float32 or float64.
135
+ type FloatType float32
136
+
137
+ // ComplexType is here for the purposes of documentation only. It is a
138
+ // stand-in for either complex type: complex64 or complex128.
139
+ type ComplexType complex64
140
+
141
+ // The append built-in function appends elements to the end of a slice. If
142
+ // it has sufficient capacity, the destination is resliced to accommodate the
143
+ // new elements. If it does not, a new underlying array will be allocated.
144
+ // Append returns the updated slice. It is therefore necessary to store the
145
+ // result of append, often in the variable holding the slice itself:
146
+ //
147
+ // slice = append(slice, elem1, elem2)
148
+ // slice = append(slice, anotherSlice...)
149
+ //
150
+ // As a special case, it is legal to append a string to a byte slice, like this:
151
+ //
152
+ // slice = append([]byte("hello "), "world"...)
153
+ func append(slice []Type, elems ...Type) []Type
154
+
155
+ // The copy built-in function copies elements from a source slice into a
156
+ // destination slice. (As a special case, it also will copy bytes from a
157
+ // string to a slice of bytes.) The source and destination may overlap. Copy
158
+ // returns the number of elements copied, which will be the minimum of
159
+ // len(src) and len(dst).
160
+ func copy(dst, src []Type) int
161
+
162
+ // The delete built-in function deletes the element with the specified key
163
+ // (m[key]) from the map. If m is nil or there is no such element, delete
164
+ // is a no-op.
165
+ func delete(m map[Type]Type1, key Type)
166
+
167
+ // The len built-in function returns the length of v, according to its type:
168
+ //
169
+ // - Array: the number of elements in v.
170
+ // - Pointer to array: the number of elements in *v (even if v is nil).
171
+ // - Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
172
+ // - String: the number of bytes in v.
173
+ // - Channel: the number of elements queued (unread) in the channel buffer;
174
+ // if v is nil, len(v) is zero.
175
+ //
176
+ // For some arguments, such as a string literal or a simple array expression, the
177
+ // result can be a constant. See the Go language specification's "Length and
178
+ // capacity" section for details.
179
+ func len(v Type) int
180
+
181
+ // The cap built-in function returns the capacity of v, according to its type:
182
+ //
183
+ // - Array: the number of elements in v (same as len(v)).
184
+ // - Pointer to array: the number of elements in *v (same as len(v)).
185
+ // - Slice: the maximum length the slice can reach when resliced;
186
+ // if v is nil, cap(v) is zero.
187
+ // - Channel: the channel buffer capacity, in units of elements;
188
+ // if v is nil, cap(v) is zero.
189
+ //
190
+ // For some arguments, such as a simple array expression, the result can be a
191
+ // constant. See the Go language specification's "Length and capacity" section for
192
+ // details.
193
+ func cap(v Type) int
194
+
195
+ // The make built-in function allocates and initializes an object of type
196
+ // slice, map, or chan (only). Like new, the first argument is a type, not a
197
+ // value. Unlike new, make's return type is the same as the type of its
198
+ // argument, not a pointer to it. The specification of the result depends on
199
+ // the type:
200
+ //
201
+ // - Slice: The size specifies the length. The capacity of the slice is
202
+ // equal to its length. A second integer argument may be provided to
203
+ // specify a different capacity; it must be no smaller than the
204
+ // length. For example, make([]int, 0, 10) allocates an underlying array
205
+ // of size 10 and returns a slice of length 0 and capacity 10 that is
206
+ // backed by this underlying array.
207
+ // - Map: An empty map is allocated with enough space to hold the
208
+ // specified number of elements. The size may be omitted, in which case
209
+ // a small starting size is allocated.
210
+ // - Channel: The channel's buffer is initialized with the specified
211
+ // buffer capacity. If zero, or the size is omitted, the channel is
212
+ // unbuffered.
213
+ func make(t Type, size ...IntegerType) Type
214
+
215
+ // The max built-in function returns the largest value of a fixed number of
216
+ // arguments of [cmp.Ordered] types. There must be at least one argument.
217
+ // If T is a floating-point type and any of the arguments are NaNs,
218
+ // max will return NaN.
219
+ func max[T cmp.Ordered](x T, y ...T) T
220
+
221
+ // The min built-in function returns the smallest value of a fixed number of
222
+ // arguments of [cmp.Ordered] types. There must be at least one argument.
223
+ // If T is a floating-point type and any of the arguments are NaNs,
224
+ // min will return NaN.
225
+ func min[T cmp.Ordered](x T, y ...T) T
226
+
227
+ // The built-in function new allocates a new, initialized variable and returns
228
+ // a pointer to it. It accepts a single argument, which may be either a type
229
+ // or an expression.
230
+ // If the argument is a type T, then new(T) allocates a variable of type T
231
+ // initialized to its zero value.
232
+ // Otherwise, the argument is an expression x and new(x) allocates a variable
233
+ // of the type of x initialized to the value of x. If that value is an untyped
234
+ // constant, it is first implicitly converted to its default type.
235
+ func new(TypeOrExpr) *Type
236
+
237
+ // The complex built-in function constructs a complex value from two
238
+ // floating-point values. The real and imaginary parts must be of the same
239
+ // size, either float32 or float64 (or assignable to them), and the return
240
+ // value will be the corresponding complex type (complex64 for float32,
241
+ // complex128 for float64).
242
+ func complex(r, i FloatType) ComplexType
243
+
244
+ // The real built-in function returns the real part of the complex number c.
245
+ // The return value will be floating point type corresponding to the type of c.
246
+ func real(c ComplexType) FloatType
247
+
248
+ // The imag built-in function returns the imaginary part of the complex
249
+ // number c. The return value will be floating point type corresponding to
250
+ // the type of c.
251
+ func imag(c ComplexType) FloatType
252
+
253
+ // The clear built-in function clears maps and slices.
254
+ // For maps, clear deletes all entries, resulting in an empty map.
255
+ // For slices, clear sets all elements up to the length of the slice
256
+ // to the zero value of the respective element type. If the argument
257
+ // type is a type parameter, the type parameter's type set must
258
+ // contain only map or slice types, and clear performs the operation
259
+ // implied by the type argument. If t is nil, clear is a no-op.
260
+ func clear[T ~[]Type | ~map[Type]Type1](t T)
261
+
262
+ // The close built-in function closes a channel, which must be either
263
+ // bidirectional or send-only. It should be executed only by the sender,
264
+ // never the receiver, and has the effect of shutting down the channel after
265
+ // the last sent value is received. After the last value has been received
266
+ // from a closed channel c, any receive from c will succeed without
267
+ // blocking, returning the zero value for the channel element. The form
268
+ //
269
+ // x, ok := <-c
270
+ //
271
+ // will also set ok to false for a closed and empty channel.
272
+ func close(c chan<- Type)
273
+
274
+ // The panic built-in function stops normal execution of the current
275
+ // goroutine. When a function F calls panic, normal execution of F stops
276
+ // immediately. Any functions whose execution was deferred by F are run in
277
+ // the usual way, and then F returns to its caller. To the caller G, the
278
+ // invocation of F then behaves like a call to panic, terminating G's
279
+ // execution and running any deferred functions. This continues until all
280
+ // functions in the executing goroutine have stopped, in reverse order. At
281
+ // that point, the program is terminated with a non-zero exit code. This
282
+ // termination sequence is called panicking and can be controlled by the
283
+ // built-in function recover.
284
+ //
285
+ // Starting in Go 1.21, calling panic with a nil interface value or an
286
+ // untyped nil causes a run-time error (a different panic).
287
+ // The GODEBUG setting panicnil=1 disables the run-time error.
288
+ func panic(v any)
289
+
290
+ // The recover built-in function allows a program to manage behavior of a
291
+ // panicking goroutine. Executing a call to recover inside a deferred
292
+ // function (but not any function called by it) stops the panicking sequence
293
+ // by restoring normal execution and retrieves the error value passed to the
294
+ // call of panic. If recover is called outside the deferred function it will
295
+ // not stop a panicking sequence. In this case, or when the goroutine is not
296
+ // panicking, recover returns nil.
297
+ //
298
+ // Prior to Go 1.21, recover would also return nil if panic is called with
299
+ // a nil argument. See [panic] for details.
300
+ func recover() any
301
+
302
+ // The print built-in function formats its arguments in an
303
+ // implementation-specific way and writes the result to standard error.
304
+ // Print is useful for bootstrapping and debugging; it is not guaranteed
305
+ // to stay in the language.
306
+ func print(args ...Type)
307
+
308
+ // The println built-in function formats its arguments in an
309
+ // implementation-specific way and writes the result to standard error.
310
+ // Spaces are always added between arguments and a newline is appended.
311
+ // Println is useful for bootstrapping and debugging; it is not guaranteed
312
+ // to stay in the language.
313
+ func println(args ...Type)
314
+
315
+ // The error built-in interface type is the conventional interface for
316
+ // representing an error condition, with the nil value representing no error.
317
+ type error interface {
318
+ Error() string
319
+ }
go/src/bytes/boundary_test.go ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+ //
5
+ //go:build linux
6
+
7
+ package bytes_test
8
+
9
+ import (
10
+ . "bytes"
11
+ "syscall"
12
+ "testing"
13
+ )
14
+
15
+ // This file tests the situation where byte operations are checking
16
+ // data very near to a page boundary. We want to make sure those
17
+ // operations do not read across the boundary and cause a page
18
+ // fault where they shouldn't.
19
+
20
+ // These tests run only on linux. The code being tested is
21
+ // not OS-specific, so it does not need to be tested on all
22
+ // operating systems.
23
+
24
+ // dangerousSlice returns a slice which is immediately
25
+ // preceded and followed by a faulting page.
26
+ func dangerousSlice(t *testing.T) []byte {
27
+ pagesize := syscall.Getpagesize()
28
+ b, err := syscall.Mmap(0, 0, 3*pagesize, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANONYMOUS|syscall.MAP_PRIVATE)
29
+ if err != nil {
30
+ t.Fatalf("mmap failed %s", err)
31
+ }
32
+ err = syscall.Mprotect(b[:pagesize], syscall.PROT_NONE)
33
+ if err != nil {
34
+ t.Fatalf("mprotect low failed %s\n", err)
35
+ }
36
+ err = syscall.Mprotect(b[2*pagesize:], syscall.PROT_NONE)
37
+ if err != nil {
38
+ t.Fatalf("mprotect high failed %s\n", err)
39
+ }
40
+ return b[pagesize : 2*pagesize]
41
+ }
42
+
43
+ func TestEqualNearPageBoundary(t *testing.T) {
44
+ t.Parallel()
45
+ b := dangerousSlice(t)
46
+ for i := range b {
47
+ b[i] = 'A'
48
+ }
49
+ for i := 0; i <= len(b); i++ {
50
+ Equal(b[:i], b[len(b)-i:])
51
+ Equal(b[len(b)-i:], b[:i])
52
+ }
53
+ }
54
+
55
+ func TestIndexByteNearPageBoundary(t *testing.T) {
56
+ t.Parallel()
57
+ b := dangerousSlice(t)
58
+ for i := range b {
59
+ idx := IndexByte(b[i:], 1)
60
+ if idx != -1 {
61
+ t.Fatalf("IndexByte(b[%d:])=%d, want -1\n", i, idx)
62
+ }
63
+ }
64
+ }
65
+
66
+ func TestIndexNearPageBoundary(t *testing.T) {
67
+ t.Parallel()
68
+ q := dangerousSlice(t)
69
+ if len(q) > 64 {
70
+ // Only worry about when we're near the end of a page.
71
+ q = q[len(q)-64:]
72
+ }
73
+ b := dangerousSlice(t)
74
+ if len(b) > 256 {
75
+ // Only worry about when we're near the end of a page.
76
+ b = b[len(b)-256:]
77
+ }
78
+ for j := 1; j < len(q); j++ {
79
+ q[j-1] = 1 // difference is only found on the last byte
80
+ for i := range b {
81
+ idx := Index(b[i:], q[:j])
82
+ if idx != -1 {
83
+ t.Fatalf("Index(b[%d:], q[:%d])=%d, want -1\n", i, j, idx)
84
+ }
85
+ }
86
+ q[j-1] = 0
87
+ }
88
+
89
+ // Test differing alignments and sizes of q which always end on a page boundary.
90
+ q[len(q)-1] = 1 // difference is only found on the last byte
91
+ for j := 0; j < len(q); j++ {
92
+ for i := range b {
93
+ idx := Index(b[i:], q[j:])
94
+ if idx != -1 {
95
+ t.Fatalf("Index(b[%d:], q[%d:])=%d, want -1\n", i, j, idx)
96
+ }
97
+ }
98
+ }
99
+ q[len(q)-1] = 0
100
+ }
101
+
102
+ func TestCountNearPageBoundary(t *testing.T) {
103
+ t.Parallel()
104
+ b := dangerousSlice(t)
105
+ for i := range b {
106
+ c := Count(b[i:], []byte{1})
107
+ if c != 0 {
108
+ t.Fatalf("Count(b[%d:], {1})=%d, want 0\n", i, c)
109
+ }
110
+ c = Count(b[:i], []byte{0})
111
+ if c != i {
112
+ t.Fatalf("Count(b[:%d], {0})=%d, want %d\n", i, c, i)
113
+ }
114
+ }
115
+ }
go/src/bytes/buffer.go ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes
6
+
7
+ // Simple byte buffer for marshaling data.
8
+
9
+ import (
10
+ "errors"
11
+ "io"
12
+ "unicode/utf8"
13
+ )
14
+
15
+ // smallBufferSize is an initial allocation minimal capacity.
16
+ const smallBufferSize = 64
17
+
18
+ // A Buffer is a variable-sized buffer of bytes with [Buffer.Read] and [Buffer.Write] methods.
19
+ // The zero value for Buffer is an empty buffer ready to use.
20
+ type Buffer struct {
21
+ buf []byte // contents are the bytes buf[off : len(buf)]
22
+ off int // read at &buf[off], write at &buf[len(buf)]
23
+ lastRead readOp // last read operation, so that Unread* can work correctly.
24
+
25
+ // Copying and modifying a non-zero Buffer is prone to error,
26
+ // but we cannot employ the noCopy trick used by WaitGroup and Mutex,
27
+ // which causes vet's copylocks checker to report misuse, as vet
28
+ // cannot reliably distinguish the zero and non-zero cases.
29
+ // See #26462, #25907, #47276, #48398 for history.
30
+ }
31
+
32
+ // The readOp constants describe the last action performed on
33
+ // the buffer, so that UnreadRune and UnreadByte can check for
34
+ // invalid usage. opReadRuneX constants are chosen such that
35
+ // converted to int they correspond to the rune size that was read.
36
+ type readOp int8
37
+
38
+ // Don't use iota for these, as the values need to correspond with the
39
+ // names and comments, which is easier to see when being explicit.
40
+ const (
41
+ opRead readOp = -1 // Any other read operation.
42
+ opInvalid readOp = 0 // Non-read operation.
43
+ opReadRune1 readOp = 1 // Read rune of size 1.
44
+ opReadRune2 readOp = 2 // Read rune of size 2.
45
+ opReadRune3 readOp = 3 // Read rune of size 3.
46
+ opReadRune4 readOp = 4 // Read rune of size 4.
47
+ )
48
+
49
+ // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
50
+ var ErrTooLarge = errors.New("bytes.Buffer: too large")
51
+ var errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read")
52
+
53
+ const maxInt = int(^uint(0) >> 1)
54
+
55
+ // Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
56
+ // The slice is valid for use only until the next buffer modification (that is,
57
+ // only until the next call to a method like [Buffer.Read], [Buffer.Write], [Buffer.Reset], or [Buffer.Truncate]).
58
+ // The slice aliases the buffer content at least until the next buffer modification,
59
+ // so immediate changes to the slice will affect the result of future reads.
60
+ func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
61
+
62
+ // AvailableBuffer returns an empty buffer with b.Available() capacity.
63
+ // This buffer is intended to be appended to and
64
+ // passed to an immediately succeeding [Buffer.Write] call.
65
+ // The buffer is only valid until the next write operation on b.
66
+ func (b *Buffer) AvailableBuffer() []byte { return b.buf[len(b.buf):] }
67
+
68
+ // String returns the contents of the unread portion of the buffer
69
+ // as a string. If the [Buffer] is a nil pointer, it returns "<nil>".
70
+ //
71
+ // To build strings more efficiently, see the [strings.Builder] type.
72
+ func (b *Buffer) String() string {
73
+ if b == nil {
74
+ // Special case, useful in debugging.
75
+ return "<nil>"
76
+ }
77
+ return string(b.buf[b.off:])
78
+ }
79
+
80
+ // Peek returns the next n bytes without advancing the buffer.
81
+ // If Peek returns fewer than n bytes, it also returns [io.EOF].
82
+ // The slice is only valid until the next call to a read or write method.
83
+ // The slice aliases the buffer content at least until the next buffer modification,
84
+ // so immediate changes to the slice will affect the result of future reads.
85
+ func (b *Buffer) Peek(n int) ([]byte, error) {
86
+ if b.Len() < n {
87
+ return b.buf[b.off:], io.EOF
88
+ }
89
+ return b.buf[b.off : b.off+n], nil
90
+ }
91
+
92
+ // empty reports whether the unread portion of the buffer is empty.
93
+ func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
94
+
95
+ // Len returns the number of bytes of the unread portion of the buffer;
96
+ // b.Len() == len(b.Bytes()).
97
+ func (b *Buffer) Len() int { return len(b.buf) - b.off }
98
+
99
+ // Cap returns the capacity of the buffer's underlying byte slice, that is, the
100
+ // total space allocated for the buffer's data.
101
+ func (b *Buffer) Cap() int { return cap(b.buf) }
102
+
103
+ // Available returns how many bytes are unused in the buffer.
104
+ func (b *Buffer) Available() int { return cap(b.buf) - len(b.buf) }
105
+
106
+ // Truncate discards all but the first n unread bytes from the buffer
107
+ // but continues to use the same allocated storage.
108
+ // It panics if n is negative or greater than the length of the buffer.
109
+ func (b *Buffer) Truncate(n int) {
110
+ if n == 0 {
111
+ b.Reset()
112
+ return
113
+ }
114
+ b.lastRead = opInvalid
115
+ if n < 0 || n > b.Len() {
116
+ panic("bytes.Buffer: truncation out of range")
117
+ }
118
+ b.buf = b.buf[:b.off+n]
119
+ }
120
+
121
+ // Reset resets the buffer to be empty,
122
+ // but it retains the underlying storage for use by future writes.
123
+ // Reset is the same as [Buffer.Truncate](0).
124
+ func (b *Buffer) Reset() {
125
+ b.buf = b.buf[:0]
126
+ b.off = 0
127
+ b.lastRead = opInvalid
128
+ }
129
+
130
+ // tryGrowByReslice is an inlineable version of grow for the fast-case where the
131
+ // internal buffer only needs to be resliced.
132
+ // It returns the index where bytes should be written and whether it succeeded.
133
+ func (b *Buffer) tryGrowByReslice(n int) (int, bool) {
134
+ if l := len(b.buf); n <= cap(b.buf)-l {
135
+ b.buf = b.buf[:l+n]
136
+ return l, true
137
+ }
138
+ return 0, false
139
+ }
140
+
141
+ // grow grows the buffer to guarantee space for n more bytes.
142
+ // It returns the index where bytes should be written.
143
+ // If the buffer can't grow it will panic with ErrTooLarge.
144
+ func (b *Buffer) grow(n int) int {
145
+ m := b.Len()
146
+ // If buffer is empty, reset to recover space.
147
+ if m == 0 && b.off != 0 {
148
+ b.Reset()
149
+ }
150
+ // Try to grow by means of a reslice.
151
+ if i, ok := b.tryGrowByReslice(n); ok {
152
+ return i
153
+ }
154
+ if b.buf == nil && n <= smallBufferSize {
155
+ b.buf = make([]byte, n, smallBufferSize)
156
+ return 0
157
+ }
158
+ c := cap(b.buf)
159
+ if n <= c/2-m {
160
+ // We can slide things down instead of allocating a new
161
+ // slice. We only need m+n <= c to slide, but
162
+ // we instead let capacity get twice as large so we
163
+ // don't spend all our time copying.
164
+ copy(b.buf, b.buf[b.off:])
165
+ } else if c > maxInt-c-n {
166
+ panic(ErrTooLarge)
167
+ } else {
168
+ // Add b.off to account for b.buf[:b.off] being sliced off the front.
169
+ b.buf = growSlice(b.buf[b.off:], b.off+n)
170
+ }
171
+ // Restore b.off and len(b.buf).
172
+ b.off = 0
173
+ b.buf = b.buf[:m+n]
174
+ return m
175
+ }
176
+
177
+ // Grow grows the buffer's capacity, if necessary, to guarantee space for
178
+ // another n bytes. After Grow(n), at least n bytes can be written to the
179
+ // buffer without another allocation.
180
+ // If n is negative, Grow will panic.
181
+ // If the buffer can't grow it will panic with [ErrTooLarge].
182
+ func (b *Buffer) Grow(n int) {
183
+ if n < 0 {
184
+ panic("bytes.Buffer.Grow: negative count")
185
+ }
186
+ m := b.grow(n)
187
+ b.buf = b.buf[:m]
188
+ }
189
+
190
+ // Write appends the contents of p to the buffer, growing the buffer as
191
+ // needed. The return value n is the length of p; err is always nil. If the
192
+ // buffer becomes too large, Write will panic with [ErrTooLarge].
193
+ func (b *Buffer) Write(p []byte) (n int, err error) {
194
+ b.lastRead = opInvalid
195
+ m, ok := b.tryGrowByReslice(len(p))
196
+ if !ok {
197
+ m = b.grow(len(p))
198
+ }
199
+ return copy(b.buf[m:], p), nil
200
+ }
201
+
202
+ // WriteString appends the contents of s to the buffer, growing the buffer as
203
+ // needed. The return value n is the length of s; err is always nil. If the
204
+ // buffer becomes too large, WriteString will panic with [ErrTooLarge].
205
+ func (b *Buffer) WriteString(s string) (n int, err error) {
206
+ b.lastRead = opInvalid
207
+ m, ok := b.tryGrowByReslice(len(s))
208
+ if !ok {
209
+ m = b.grow(len(s))
210
+ }
211
+ return copy(b.buf[m:], s), nil
212
+ }
213
+
214
+ // MinRead is the minimum slice size passed to a [Buffer.Read] call by
215
+ // [Buffer.ReadFrom]. As long as the [Buffer] has at least MinRead bytes beyond
216
+ // what is required to hold the contents of r, [Buffer.ReadFrom] will not grow the
217
+ // underlying buffer.
218
+ const MinRead = 512
219
+
220
+ // ReadFrom reads data from r until EOF and appends it to the buffer, growing
221
+ // the buffer as needed. The return value n is the number of bytes read. Any
222
+ // error except io.EOF encountered during the read is also returned. If the
223
+ // buffer becomes too large, ReadFrom will panic with [ErrTooLarge].
224
+ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
225
+ b.lastRead = opInvalid
226
+ for {
227
+ i := b.grow(MinRead)
228
+ b.buf = b.buf[:i]
229
+ m, e := r.Read(b.buf[i:cap(b.buf)])
230
+ if m < 0 {
231
+ panic(errNegativeRead)
232
+ }
233
+
234
+ b.buf = b.buf[:i+m]
235
+ n += int64(m)
236
+ if e == io.EOF {
237
+ return n, nil // e is EOF, so return nil explicitly
238
+ }
239
+ if e != nil {
240
+ return n, e
241
+ }
242
+ }
243
+ }
244
+
245
+ // growSlice grows b by n, preserving the original content of b.
246
+ // If the allocation fails, it panics with ErrTooLarge.
247
+ func growSlice(b []byte, n int) []byte {
248
+ defer func() {
249
+ if recover() != nil {
250
+ panic(ErrTooLarge)
251
+ }
252
+ }()
253
+ // TODO(http://golang.org/issue/51462): We should rely on the append-make
254
+ // pattern so that the compiler can call runtime.growslice. For example:
255
+ // return append(b, make([]byte, n)...)
256
+ // This avoids unnecessary zero-ing of the first len(b) bytes of the
257
+ // allocated slice, but this pattern causes b to escape onto the heap.
258
+ //
259
+ // Instead use the append-make pattern with a nil slice to ensure that
260
+ // we allocate buffers rounded up to the closest size class.
261
+ c := len(b) + n // ensure enough space for n elements
262
+ if c < 2*cap(b) {
263
+ // The growth rate has historically always been 2x. In the future,
264
+ // we could rely purely on append to determine the growth rate.
265
+ c = 2 * cap(b)
266
+ }
267
+ b2 := append([]byte(nil), make([]byte, c)...)
268
+ i := copy(b2, b)
269
+ return b2[:i]
270
+ }
271
+
272
+ // WriteTo writes data to w until the buffer is drained or an error occurs.
273
+ // The return value n is the number of bytes written; it always fits into an
274
+ // int, but it is int64 to match the [io.WriterTo] interface. Any error
275
+ // encountered during the write is also returned.
276
+ func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
277
+ b.lastRead = opInvalid
278
+ if nBytes := b.Len(); nBytes > 0 {
279
+ m, e := w.Write(b.buf[b.off:])
280
+ if m > nBytes {
281
+ panic("bytes.Buffer.WriteTo: invalid Write count")
282
+ }
283
+ b.off += m
284
+ n = int64(m)
285
+ if e != nil {
286
+ return n, e
287
+ }
288
+ // all bytes should have been written, by definition of
289
+ // Write method in io.Writer
290
+ if m != nBytes {
291
+ return n, io.ErrShortWrite
292
+ }
293
+ }
294
+ // Buffer is now empty; reset.
295
+ b.Reset()
296
+ return n, nil
297
+ }
298
+
299
+ // WriteByte appends the byte c to the buffer, growing the buffer as needed.
300
+ // The returned error is always nil, but is included to match [bufio.Writer]'s
301
+ // WriteByte. If the buffer becomes too large, WriteByte will panic with
302
+ // [ErrTooLarge].
303
+ func (b *Buffer) WriteByte(c byte) error {
304
+ b.lastRead = opInvalid
305
+ m, ok := b.tryGrowByReslice(1)
306
+ if !ok {
307
+ m = b.grow(1)
308
+ }
309
+ b.buf[m] = c
310
+ return nil
311
+ }
312
+
313
+ // WriteRune appends the UTF-8 encoding of Unicode code point r to the
314
+ // buffer, returning its length and an error, which is always nil but is
315
+ // included to match [bufio.Writer]'s WriteRune. The buffer is grown as needed;
316
+ // if it becomes too large, WriteRune will panic with [ErrTooLarge].
317
+ func (b *Buffer) WriteRune(r rune) (n int, err error) {
318
+ // Compare as uint32 to correctly handle negative runes.
319
+ if uint32(r) < utf8.RuneSelf {
320
+ b.WriteByte(byte(r))
321
+ return 1, nil
322
+ }
323
+ b.lastRead = opInvalid
324
+ m, ok := b.tryGrowByReslice(utf8.UTFMax)
325
+ if !ok {
326
+ m = b.grow(utf8.UTFMax)
327
+ }
328
+ b.buf = utf8.AppendRune(b.buf[:m], r)
329
+ return len(b.buf) - m, nil
330
+ }
331
+
332
+ // Read reads the next len(p) bytes from the buffer or until the buffer
333
+ // is drained. The return value n is the number of bytes read. If the
334
+ // buffer has no data to return, err is [io.EOF] (unless len(p) is zero);
335
+ // otherwise it is nil.
336
+ func (b *Buffer) Read(p []byte) (n int, err error) {
337
+ b.lastRead = opInvalid
338
+ if b.empty() {
339
+ // Buffer is empty, reset to recover space.
340
+ b.Reset()
341
+ if len(p) == 0 {
342
+ return 0, nil
343
+ }
344
+ return 0, io.EOF
345
+ }
346
+ n = copy(p, b.buf[b.off:])
347
+ b.off += n
348
+ if n > 0 {
349
+ b.lastRead = opRead
350
+ }
351
+ return n, nil
352
+ }
353
+
354
+ // Next returns a slice containing the next n bytes from the buffer,
355
+ // advancing the buffer as if the bytes had been returned by [Buffer.Read].
356
+ // If there are fewer than n bytes in the buffer, Next returns the entire buffer.
357
+ // The slice is only valid until the next call to a read or write method.
358
+ func (b *Buffer) Next(n int) []byte {
359
+ b.lastRead = opInvalid
360
+ m := b.Len()
361
+ if n > m {
362
+ n = m
363
+ }
364
+ data := b.buf[b.off : b.off+n]
365
+ b.off += n
366
+ if n > 0 {
367
+ b.lastRead = opRead
368
+ }
369
+ return data
370
+ }
371
+
372
+ // ReadByte reads and returns the next byte from the buffer.
373
+ // If no byte is available, it returns error [io.EOF].
374
+ func (b *Buffer) ReadByte() (byte, error) {
375
+ if b.empty() {
376
+ // Buffer is empty, reset to recover space.
377
+ b.Reset()
378
+ return 0, io.EOF
379
+ }
380
+ c := b.buf[b.off]
381
+ b.off++
382
+ b.lastRead = opRead
383
+ return c, nil
384
+ }
385
+
386
+ // ReadRune reads and returns the next UTF-8-encoded
387
+ // Unicode code point from the buffer.
388
+ // If no bytes are available, the error returned is io.EOF.
389
+ // If the bytes are an erroneous UTF-8 encoding, it
390
+ // consumes one byte and returns U+FFFD, 1.
391
+ func (b *Buffer) ReadRune() (r rune, size int, err error) {
392
+ if b.empty() {
393
+ // Buffer is empty, reset to recover space.
394
+ b.Reset()
395
+ return 0, 0, io.EOF
396
+ }
397
+ c := b.buf[b.off]
398
+ if c < utf8.RuneSelf {
399
+ b.off++
400
+ b.lastRead = opReadRune1
401
+ return rune(c), 1, nil
402
+ }
403
+ r, n := utf8.DecodeRune(b.buf[b.off:])
404
+ b.off += n
405
+ b.lastRead = readOp(n)
406
+ return r, n, nil
407
+ }
408
+
409
+ // UnreadRune unreads the last rune returned by [Buffer.ReadRune].
410
+ // If the most recent read or write operation on the buffer was
411
+ // not a successful [Buffer.ReadRune], UnreadRune returns an error. (In this regard
412
+ // it is stricter than [Buffer.UnreadByte], which will unread the last byte
413
+ // from any read operation.)
414
+ func (b *Buffer) UnreadRune() error {
415
+ if b.lastRead <= opInvalid {
416
+ return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune")
417
+ }
418
+ if b.off >= int(b.lastRead) {
419
+ b.off -= int(b.lastRead)
420
+ }
421
+ b.lastRead = opInvalid
422
+ return nil
423
+ }
424
+
425
+ var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read")
426
+
427
+ // UnreadByte unreads the last byte returned by the most recent successful
428
+ // read operation that read at least one byte. If a write has happened since
429
+ // the last read, if the last read returned an error, or if the read read zero
430
+ // bytes, UnreadByte returns an error.
431
+ func (b *Buffer) UnreadByte() error {
432
+ if b.lastRead == opInvalid {
433
+ return errUnreadByte
434
+ }
435
+ b.lastRead = opInvalid
436
+ if b.off > 0 {
437
+ b.off--
438
+ }
439
+ return nil
440
+ }
441
+
442
+ // ReadBytes reads until the first occurrence of delim in the input,
443
+ // returning a slice containing the data up to and including the delimiter.
444
+ // If ReadBytes encounters an error before finding a delimiter,
445
+ // it returns the data read before the error and the error itself (often [io.EOF]).
446
+ // ReadBytes returns err != nil if and only if the returned data does not end in
447
+ // delim.
448
+ func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
449
+ slice, err := b.readSlice(delim)
450
+ // return a copy of slice. The buffer's backing array may
451
+ // be overwritten by later calls.
452
+ line = append(line, slice...)
453
+ return line, err
454
+ }
455
+
456
+ // readSlice is like ReadBytes but returns a reference to internal buffer data.
457
+ func (b *Buffer) readSlice(delim byte) (line []byte, err error) {
458
+ i := IndexByte(b.buf[b.off:], delim)
459
+ end := b.off + i + 1
460
+ if i < 0 {
461
+ end = len(b.buf)
462
+ err = io.EOF
463
+ }
464
+ line = b.buf[b.off:end]
465
+ b.off = end
466
+ b.lastRead = opRead
467
+ return line, err
468
+ }
469
+
470
+ // ReadString reads until the first occurrence of delim in the input,
471
+ // returning a string containing the data up to and including the delimiter.
472
+ // If ReadString encounters an error before finding a delimiter,
473
+ // it returns the data read before the error and the error itself (often [io.EOF]).
474
+ // ReadString returns err != nil if and only if the returned data does not end
475
+ // in delim.
476
+ func (b *Buffer) ReadString(delim byte) (line string, err error) {
477
+ slice, err := b.readSlice(delim)
478
+ return string(slice), err
479
+ }
480
+
481
+ // NewBuffer creates and initializes a new [Buffer] using buf as its
482
+ // initial contents. The new [Buffer] takes ownership of buf, and the
483
+ // caller should not use buf after this call. NewBuffer is intended to
484
+ // prepare a [Buffer] to read existing data. It can also be used to set
485
+ // the initial size of the internal buffer for writing. To do that,
486
+ // buf should have the desired capacity but a length of zero.
487
+ //
488
+ // In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
489
+ // sufficient to initialize a [Buffer].
490
+ func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
491
+
492
+ // NewBufferString creates and initializes a new [Buffer] using string s as its
493
+ // initial contents. It is intended to prepare a buffer to read an existing
494
+ // string.
495
+ //
496
+ // In most cases, new([Buffer]) (or just declaring a [Buffer] variable) is
497
+ // sufficient to initialize a [Buffer].
498
+ func NewBufferString(s string) *Buffer {
499
+ return &Buffer{buf: []byte(s)}
500
+ }
go/src/bytes/buffer_test.go ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ . "bytes"
9
+ "fmt"
10
+ "internal/testenv"
11
+ "io"
12
+ "math/rand"
13
+ "strconv"
14
+ "testing"
15
+ "unicode/utf8"
16
+ )
17
+
18
+ const N = 10000 // make this bigger for a larger (and slower) test
19
+ var testString string // test data for write tests
20
+ var testBytes []byte // test data; same as testString but as a slice.
21
+
22
+ type negativeReader struct{}
23
+
24
+ func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
25
+
26
+ func init() {
27
+ testBytes = make([]byte, N)
28
+ for i := 0; i < N; i++ {
29
+ testBytes[i] = 'a' + byte(i%26)
30
+ }
31
+ testString = string(testBytes)
32
+ }
33
+
34
+ // Verify that contents of buf match the string s.
35
+ func check(t *testing.T, testname string, buf *Buffer, s string) {
36
+ bytes := buf.Bytes()
37
+ str := buf.String()
38
+ if buf.Len() != len(bytes) {
39
+ t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d", testname, buf.Len(), len(bytes))
40
+ }
41
+
42
+ if buf.Len() != len(str) {
43
+ t.Errorf("%s: buf.Len() == %d, len(buf.String()) == %d", testname, buf.Len(), len(str))
44
+ }
45
+
46
+ if buf.Len() != len(s) {
47
+ t.Errorf("%s: buf.Len() == %d, len(s) == %d", testname, buf.Len(), len(s))
48
+ }
49
+
50
+ if string(bytes) != s {
51
+ t.Errorf("%s: string(buf.Bytes()) == %q, s == %q", testname, string(bytes), s)
52
+ }
53
+ }
54
+
55
+ // Fill buf through n writes of string fus.
56
+ // The initial contents of buf corresponds to the string s;
57
+ // the result is the final contents of buf returned as a string.
58
+ func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string {
59
+ check(t, testname+" (fill 1)", buf, s)
60
+ for ; n > 0; n-- {
61
+ m, err := buf.WriteString(fus)
62
+ if m != len(fus) {
63
+ t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fus))
64
+ }
65
+ if err != nil {
66
+ t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
67
+ }
68
+ s += fus
69
+ check(t, testname+" (fill 4)", buf, s)
70
+ }
71
+ return s
72
+ }
73
+
74
+ // Fill buf through n writes of byte slice fub.
75
+ // The initial contents of buf corresponds to the string s;
76
+ // the result is the final contents of buf returned as a string.
77
+ func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string {
78
+ check(t, testname+" (fill 1)", buf, s)
79
+ for ; n > 0; n-- {
80
+ m, err := buf.Write(fub)
81
+ if m != len(fub) {
82
+ t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fub))
83
+ }
84
+ if err != nil {
85
+ t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err)
86
+ }
87
+ s += string(fub)
88
+ check(t, testname+" (fill 4)", buf, s)
89
+ }
90
+ return s
91
+ }
92
+
93
+ func TestNewBuffer(t *testing.T) {
94
+ buf := NewBuffer(testBytes)
95
+ check(t, "NewBuffer", buf, testString)
96
+ }
97
+
98
+ var buf Buffer
99
+
100
+ // Calling NewBuffer and immediately shallow copying the Buffer struct
101
+ // should not result in any allocations.
102
+ // This can be used to reset the underlying []byte of an existing Buffer.
103
+ func TestNewBufferShallow(t *testing.T) {
104
+ testenv.SkipIfOptimizationOff(t)
105
+ n := testing.AllocsPerRun(1000, func() {
106
+ buf = *NewBuffer(testBytes)
107
+ })
108
+ if n > 0 {
109
+ t.Errorf("allocations occurred while shallow copying")
110
+ }
111
+ check(t, "NewBuffer", &buf, testString)
112
+ }
113
+
114
+ func TestNewBufferString(t *testing.T) {
115
+ buf := NewBufferString(testString)
116
+ check(t, "NewBufferString", buf, testString)
117
+ }
118
+
119
+ // Empty buf through repeated reads into fub.
120
+ // The initial contents of buf corresponds to the string s.
121
+ func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
122
+ check(t, testname+" (empty 1)", buf, s)
123
+
124
+ for {
125
+ n, err := buf.Read(fub)
126
+ if n == 0 {
127
+ break
128
+ }
129
+ if err != nil {
130
+ t.Errorf(testname+" (empty 2): err should always be nil, found err == %s", err)
131
+ }
132
+ s = s[n:]
133
+ check(t, testname+" (empty 3)", buf, s)
134
+ }
135
+
136
+ check(t, testname+" (empty 4)", buf, "")
137
+ }
138
+
139
+ func TestBasicOperations(t *testing.T) {
140
+ var buf Buffer
141
+
142
+ for i := 0; i < 5; i++ {
143
+ check(t, "TestBasicOperations (1)", &buf, "")
144
+
145
+ buf.Reset()
146
+ check(t, "TestBasicOperations (2)", &buf, "")
147
+
148
+ buf.Truncate(0)
149
+ check(t, "TestBasicOperations (3)", &buf, "")
150
+
151
+ n, err := buf.Write(testBytes[0:1])
152
+ if want := 1; err != nil || n != want {
153
+ t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil)
154
+ }
155
+ check(t, "TestBasicOperations (4)", &buf, "a")
156
+
157
+ buf.WriteByte(testString[1])
158
+ check(t, "TestBasicOperations (5)", &buf, "ab")
159
+
160
+ n, err = buf.Write(testBytes[2:26])
161
+ if want := 24; err != nil || n != want {
162
+ t.Errorf("Write: got (%d, %v), want (%d, %v)", n, err, want, nil)
163
+ }
164
+ check(t, "TestBasicOperations (6)", &buf, testString[0:26])
165
+
166
+ buf.Truncate(26)
167
+ check(t, "TestBasicOperations (7)", &buf, testString[0:26])
168
+
169
+ buf.Truncate(20)
170
+ check(t, "TestBasicOperations (8)", &buf, testString[0:20])
171
+
172
+ empty(t, "TestBasicOperations (9)", &buf, testString[0:20], make([]byte, 5))
173
+ empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100))
174
+
175
+ buf.WriteByte(testString[1])
176
+ c, err := buf.ReadByte()
177
+ if want := testString[1]; err != nil || c != want {
178
+ t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, want, nil)
179
+ }
180
+ c, err = buf.ReadByte()
181
+ if err != io.EOF {
182
+ t.Errorf("ReadByte: got (%q, %v), want (%q, %v)", c, err, byte(0), io.EOF)
183
+ }
184
+ }
185
+ }
186
+
187
+ func TestLargeStringWrites(t *testing.T) {
188
+ var buf Buffer
189
+ limit := 30
190
+ if testing.Short() {
191
+ limit = 9
192
+ }
193
+ for i := 3; i < limit; i += 3 {
194
+ s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, testString)
195
+ empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(testString)/i))
196
+ }
197
+ check(t, "TestLargeStringWrites (3)", &buf, "")
198
+ }
199
+
200
+ func TestLargeByteWrites(t *testing.T) {
201
+ var buf Buffer
202
+ limit := 30
203
+ if testing.Short() {
204
+ limit = 9
205
+ }
206
+ for i := 3; i < limit; i += 3 {
207
+ s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, testBytes)
208
+ empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(testString)/i))
209
+ }
210
+ check(t, "TestLargeByteWrites (3)", &buf, "")
211
+ }
212
+
213
+ func TestLargeStringReads(t *testing.T) {
214
+ var buf Buffer
215
+ for i := 3; i < 30; i += 3 {
216
+ s := fillString(t, "TestLargeReads (1)", &buf, "", 5, testString[:len(testString)/i])
217
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString)))
218
+ }
219
+ check(t, "TestLargeStringReads (3)", &buf, "")
220
+ }
221
+
222
+ func TestLargeByteReads(t *testing.T) {
223
+ var buf Buffer
224
+ for i := 3; i < 30; i += 3 {
225
+ s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, testBytes[:len(testBytes)/i])
226
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(testString)))
227
+ }
228
+ check(t, "TestLargeByteReads (3)", &buf, "")
229
+ }
230
+
231
+ func TestMixedReadsAndWrites(t *testing.T) {
232
+ var buf Buffer
233
+ s := ""
234
+ for i := 0; i < 50; i++ {
235
+ wlen := rand.Intn(len(testString))
236
+ if i%2 == 0 {
237
+ s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testString[0:wlen])
238
+ } else {
239
+ s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testBytes[0:wlen])
240
+ }
241
+
242
+ rlen := rand.Intn(len(testString))
243
+ fub := make([]byte, rlen)
244
+ n, _ := buf.Read(fub)
245
+ s = s[n:]
246
+ }
247
+ empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
248
+ }
249
+
250
+ func TestCapWithPreallocatedSlice(t *testing.T) {
251
+ buf := NewBuffer(make([]byte, 10))
252
+ n := buf.Cap()
253
+ if n != 10 {
254
+ t.Errorf("expected 10, got %d", n)
255
+ }
256
+ }
257
+
258
+ func TestCapWithSliceAndWrittenData(t *testing.T) {
259
+ buf := NewBuffer(make([]byte, 0, 10))
260
+ buf.Write([]byte("test"))
261
+ n := buf.Cap()
262
+ if n != 10 {
263
+ t.Errorf("expected 10, got %d", n)
264
+ }
265
+ }
266
+
267
+ func TestNil(t *testing.T) {
268
+ var b *Buffer
269
+ if b.String() != "<nil>" {
270
+ t.Errorf("expected <nil>; got %q", b.String())
271
+ }
272
+ }
273
+
274
+ func TestReadFrom(t *testing.T) {
275
+ var buf Buffer
276
+ for i := 3; i < 30; i += 3 {
277
+ s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, testBytes[:len(testBytes)/i])
278
+ var b Buffer
279
+ b.ReadFrom(&buf)
280
+ empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(testString)))
281
+ }
282
+ }
283
+
284
+ type panicReader struct{ panic bool }
285
+
286
+ func (r panicReader) Read(p []byte) (int, error) {
287
+ if r.panic {
288
+ panic("oops")
289
+ }
290
+ return 0, io.EOF
291
+ }
292
+
293
+ // Make sure that an empty Buffer remains empty when
294
+ // it is "grown" before a Read that panics
295
+ func TestReadFromPanicReader(t *testing.T) {
296
+
297
+ // First verify non-panic behaviour
298
+ var buf Buffer
299
+ i, err := buf.ReadFrom(panicReader{})
300
+ if err != nil {
301
+ t.Fatal(err)
302
+ }
303
+ if i != 0 {
304
+ t.Fatalf("unexpected return from bytes.ReadFrom (1): got: %d, want %d", i, 0)
305
+ }
306
+ check(t, "TestReadFromPanicReader (1)", &buf, "")
307
+
308
+ // Confirm that when Reader panics, the empty buffer remains empty
309
+ var buf2 Buffer
310
+ defer func() {
311
+ recover()
312
+ check(t, "TestReadFromPanicReader (2)", &buf2, "")
313
+ }()
314
+ buf2.ReadFrom(panicReader{panic: true})
315
+ }
316
+
317
+ func TestReadFromNegativeReader(t *testing.T) {
318
+ var b Buffer
319
+ defer func() {
320
+ switch err := recover().(type) {
321
+ case nil:
322
+ t.Fatal("bytes.Buffer.ReadFrom didn't panic")
323
+ case error:
324
+ // this is the error string of errNegativeRead
325
+ wantError := "bytes.Buffer: reader returned negative count from Read"
326
+ if err.Error() != wantError {
327
+ t.Fatalf("recovered panic: got %v, want %v", err.Error(), wantError)
328
+ }
329
+ default:
330
+ t.Fatalf("unexpected panic value: %#v", err)
331
+ }
332
+ }()
333
+
334
+ b.ReadFrom(new(negativeReader))
335
+ }
336
+
337
+ func TestWriteTo(t *testing.T) {
338
+ var buf Buffer
339
+ for i := 3; i < 30; i += 3 {
340
+ s := fillBytes(t, "TestWriteTo (1)", &buf, "", 5, testBytes[:len(testBytes)/i])
341
+ var b Buffer
342
+ buf.WriteTo(&b)
343
+ empty(t, "TestWriteTo (2)", &b, s, make([]byte, len(testString)))
344
+ }
345
+ }
346
+
347
+ func TestWriteAppend(t *testing.T) {
348
+ var got Buffer
349
+ var want []byte
350
+ for i := 0; i < 1000; i++ {
351
+ b := got.AvailableBuffer()
352
+ b = strconv.AppendInt(b, int64(i), 10)
353
+ want = strconv.AppendInt(want, int64(i), 10)
354
+ got.Write(b)
355
+ }
356
+ if !Equal(got.Bytes(), want) {
357
+ t.Fatalf("Bytes() = %q, want %q", &got, want)
358
+ }
359
+
360
+ // With a sufficiently sized buffer, there should be no allocations.
361
+ n := testing.AllocsPerRun(100, func() {
362
+ got.Reset()
363
+ for i := 0; i < 1000; i++ {
364
+ b := got.AvailableBuffer()
365
+ b = strconv.AppendInt(b, int64(i), 10)
366
+ got.Write(b)
367
+ }
368
+ })
369
+ if n > 0 {
370
+ t.Errorf("allocations occurred while appending")
371
+ }
372
+ }
373
+
374
+ func TestRuneIO(t *testing.T) {
375
+ const NRune = 1000
376
+ // Built a test slice while we write the data
377
+ b := make([]byte, utf8.UTFMax*NRune)
378
+ var buf Buffer
379
+ n := 0
380
+ for r := rune(0); r < NRune; r++ {
381
+ size := utf8.EncodeRune(b[n:], r)
382
+ nbytes, err := buf.WriteRune(r)
383
+ if err != nil {
384
+ t.Fatalf("WriteRune(%U) error: %s", r, err)
385
+ }
386
+ if nbytes != size {
387
+ t.Fatalf("WriteRune(%U) expected %d, got %d", r, size, nbytes)
388
+ }
389
+ n += size
390
+ }
391
+ b = b[0:n]
392
+
393
+ // Check the resulting bytes
394
+ if !Equal(buf.Bytes(), b) {
395
+ t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b)
396
+ }
397
+
398
+ p := make([]byte, utf8.UTFMax)
399
+ // Read it back with ReadRune
400
+ for r := rune(0); r < NRune; r++ {
401
+ size := utf8.EncodeRune(p, r)
402
+ nr, nbytes, err := buf.ReadRune()
403
+ if nr != r || nbytes != size || err != nil {
404
+ t.Fatalf("ReadRune(%U) got %U,%d not %U,%d (err=%s)", r, nr, nbytes, r, size, err)
405
+ }
406
+ }
407
+
408
+ // Check that UnreadRune works
409
+ buf.Reset()
410
+
411
+ // check at EOF
412
+ if err := buf.UnreadRune(); err == nil {
413
+ t.Fatal("UnreadRune at EOF: got no error")
414
+ }
415
+ if _, _, err := buf.ReadRune(); err == nil {
416
+ t.Fatal("ReadRune at EOF: got no error")
417
+ }
418
+ if err := buf.UnreadRune(); err == nil {
419
+ t.Fatal("UnreadRune after ReadRune at EOF: got no error")
420
+ }
421
+
422
+ // check not at EOF
423
+ buf.Write(b)
424
+ for r := rune(0); r < NRune; r++ {
425
+ r1, size, _ := buf.ReadRune()
426
+ if err := buf.UnreadRune(); err != nil {
427
+ t.Fatalf("UnreadRune(%U) got error %q", r, err)
428
+ }
429
+ r2, nbytes, err := buf.ReadRune()
430
+ if r1 != r2 || r1 != r || nbytes != size || err != nil {
431
+ t.Fatalf("ReadRune(%U) after UnreadRune got %U,%d not %U,%d (err=%s)", r, r2, nbytes, r, size, err)
432
+ }
433
+ }
434
+ }
435
+
436
+ func TestWriteInvalidRune(t *testing.T) {
437
+ // Invalid runes, including negative ones, should be written as
438
+ // utf8.RuneError.
439
+ for _, r := range []rune{-1, utf8.MaxRune + 1} {
440
+ var buf Buffer
441
+ buf.WriteRune(r)
442
+ check(t, fmt.Sprintf("TestWriteInvalidRune (%d)", r), &buf, "\uFFFD")
443
+ }
444
+ }
445
+
446
+ func TestNext(t *testing.T) {
447
+ b := []byte{0, 1, 2, 3, 4}
448
+ tmp := make([]byte, 5)
449
+ for i := 0; i <= 5; i++ {
450
+ for j := i; j <= 5; j++ {
451
+ for k := 0; k <= 6; k++ {
452
+ // 0 <= i <= j <= 5; 0 <= k <= 6
453
+ // Check that if we start with a buffer
454
+ // of length j at offset i and ask for
455
+ // Next(k), we get the right bytes.
456
+ buf := NewBuffer(b[0:j])
457
+ n, _ := buf.Read(tmp[0:i])
458
+ if n != i {
459
+ t.Fatalf("Read %d returned %d", i, n)
460
+ }
461
+ bb := buf.Next(k)
462
+ want := k
463
+ if want > j-i {
464
+ want = j - i
465
+ }
466
+ if len(bb) != want {
467
+ t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb))
468
+ }
469
+ for l, v := range bb {
470
+ if v != byte(l+i) {
471
+ t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i)
472
+ }
473
+ }
474
+ }
475
+ }
476
+ }
477
+ }
478
+
479
+ var readBytesTests = []struct {
480
+ buffer string
481
+ delim byte
482
+ expected []string
483
+ err error
484
+ }{
485
+ {"", 0, []string{""}, io.EOF},
486
+ {"a\x00", 0, []string{"a\x00"}, nil},
487
+ {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil},
488
+ {"hello\x01world", 1, []string{"hello\x01"}, nil},
489
+ {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF},
490
+ {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil},
491
+ {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF},
492
+ }
493
+
494
+ func TestReadBytes(t *testing.T) {
495
+ for _, test := range readBytesTests {
496
+ buf := NewBufferString(test.buffer)
497
+ var err error
498
+ for _, expected := range test.expected {
499
+ var bytes []byte
500
+ bytes, err = buf.ReadBytes(test.delim)
501
+ if string(bytes) != expected {
502
+ t.Errorf("expected %q, got %q", expected, bytes)
503
+ }
504
+ if err != nil {
505
+ break
506
+ }
507
+ }
508
+ if err != test.err {
509
+ t.Errorf("expected error %v, got %v", test.err, err)
510
+ }
511
+ }
512
+ }
513
+
514
+ func TestReadString(t *testing.T) {
515
+ for _, test := range readBytesTests {
516
+ buf := NewBufferString(test.buffer)
517
+ var err error
518
+ for _, expected := range test.expected {
519
+ var s string
520
+ s, err = buf.ReadString(test.delim)
521
+ if s != expected {
522
+ t.Errorf("expected %q, got %q", expected, s)
523
+ }
524
+ if err != nil {
525
+ break
526
+ }
527
+ }
528
+ if err != test.err {
529
+ t.Errorf("expected error %v, got %v", test.err, err)
530
+ }
531
+ }
532
+ }
533
+
534
+ var peekTests = []struct {
535
+ buffer string
536
+ skip int
537
+ n int
538
+ expected string
539
+ err error
540
+ }{
541
+ {"", 0, 0, "", nil},
542
+ {"aaa", 0, 3, "aaa", nil},
543
+ {"foobar", 0, 2, "fo", nil},
544
+ {"a", 0, 2, "a", io.EOF},
545
+ {"helloworld", 4, 3, "owo", nil},
546
+ {"helloworld", 5, 5, "world", nil},
547
+ {"helloworld", 5, 6, "world", io.EOF},
548
+ {"helloworld", 10, 1, "", io.EOF},
549
+ }
550
+
551
+ func TestPeek(t *testing.T) {
552
+ for _, test := range peekTests {
553
+ buf := NewBufferString(test.buffer)
554
+ buf.Next(test.skip)
555
+ bytes, err := buf.Peek(test.n)
556
+ if string(bytes) != test.expected {
557
+ t.Errorf("expected %q, got %q", test.expected, bytes)
558
+ }
559
+ if err != test.err {
560
+ t.Errorf("expected error %v, got %v", test.err, err)
561
+ }
562
+ if buf.Len() != len(test.buffer)-test.skip {
563
+ t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer)-test.skip)
564
+ }
565
+ }
566
+ }
567
+
568
+ func BenchmarkReadString(b *testing.B) {
569
+ const n = 32 << 10
570
+
571
+ data := make([]byte, n)
572
+ data[n-1] = 'x'
573
+ b.SetBytes(int64(n))
574
+ for i := 0; i < b.N; i++ {
575
+ buf := NewBuffer(data)
576
+ _, err := buf.ReadString('x')
577
+ if err != nil {
578
+ b.Fatal(err)
579
+ }
580
+ }
581
+ }
582
+
583
+ func TestGrow(t *testing.T) {
584
+ x := []byte{'x'}
585
+ y := []byte{'y'}
586
+ tmp := make([]byte, 72)
587
+ for _, growLen := range []int{0, 100, 1000, 10000, 100000} {
588
+ for _, startLen := range []int{0, 100, 1000, 10000, 100000} {
589
+ xBytes := Repeat(x, startLen)
590
+
591
+ buf := NewBuffer(xBytes)
592
+ // If we read, this affects buf.off, which is good to test.
593
+ readBytes, _ := buf.Read(tmp)
594
+ yBytes := Repeat(y, growLen)
595
+ allocs := testing.AllocsPerRun(100, func() {
596
+ buf.Grow(growLen)
597
+ buf.Write(yBytes)
598
+ })
599
+ // Check no allocation occurs in write, as long as we're single-threaded.
600
+ if allocs != 0 {
601
+ t.Errorf("allocation occurred during write")
602
+ }
603
+ // Check that buffer has correct data.
604
+ if !Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) {
605
+ t.Errorf("bad initial data at %d %d", startLen, growLen)
606
+ }
607
+ if !Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) {
608
+ t.Errorf("bad written data at %d %d", startLen, growLen)
609
+ }
610
+ }
611
+ }
612
+ }
613
+
614
+ func TestGrowOverflow(t *testing.T) {
615
+ defer func() {
616
+ if err := recover(); err != ErrTooLarge {
617
+ t.Errorf("after too-large Grow, recover() = %v; want %v", err, ErrTooLarge)
618
+ }
619
+ }()
620
+
621
+ buf := NewBuffer(make([]byte, 1))
622
+ const maxInt = int(^uint(0) >> 1)
623
+ buf.Grow(maxInt)
624
+ }
625
+
626
+ // Was a bug: used to give EOF reading empty slice at EOF.
627
+ func TestReadEmptyAtEOF(t *testing.T) {
628
+ b := new(Buffer)
629
+ slice := make([]byte, 0)
630
+ n, err := b.Read(slice)
631
+ if err != nil {
632
+ t.Errorf("read error: %v", err)
633
+ }
634
+ if n != 0 {
635
+ t.Errorf("wrong count; got %d want 0", n)
636
+ }
637
+ }
638
+
639
+ func TestUnreadByte(t *testing.T) {
640
+ b := new(Buffer)
641
+
642
+ // check at EOF
643
+ if err := b.UnreadByte(); err == nil {
644
+ t.Fatal("UnreadByte at EOF: got no error")
645
+ }
646
+ if _, err := b.ReadByte(); err == nil {
647
+ t.Fatal("ReadByte at EOF: got no error")
648
+ }
649
+ if err := b.UnreadByte(); err == nil {
650
+ t.Fatal("UnreadByte after ReadByte at EOF: got no error")
651
+ }
652
+
653
+ // check not at EOF
654
+ b.WriteString("abcdefghijklmnopqrstuvwxyz")
655
+
656
+ // after unsuccessful read
657
+ if n, err := b.Read(nil); n != 0 || err != nil {
658
+ t.Fatalf("Read(nil) = %d,%v; want 0,nil", n, err)
659
+ }
660
+ if err := b.UnreadByte(); err == nil {
661
+ t.Fatal("UnreadByte after Read(nil): got no error")
662
+ }
663
+
664
+ // after successful read
665
+ if _, err := b.ReadBytes('m'); err != nil {
666
+ t.Fatalf("ReadBytes: %v", err)
667
+ }
668
+ if err := b.UnreadByte(); err != nil {
669
+ t.Fatalf("UnreadByte: %v", err)
670
+ }
671
+ c, err := b.ReadByte()
672
+ if err != nil {
673
+ t.Fatalf("ReadByte: %v", err)
674
+ }
675
+ if c != 'm' {
676
+ t.Errorf("ReadByte = %q; want %q", c, 'm')
677
+ }
678
+ }
679
+
680
+ // Tests that we occasionally compact. Issue 5154.
681
+ func TestBufferGrowth(t *testing.T) {
682
+ var b Buffer
683
+ buf := make([]byte, 1024)
684
+ b.Write(buf[0:1])
685
+ var cap0 int
686
+ for i := 0; i < 5<<10; i++ {
687
+ b.Write(buf)
688
+ b.Read(buf)
689
+ if i == 0 {
690
+ cap0 = b.Cap()
691
+ }
692
+ }
693
+ cap1 := b.Cap()
694
+ // (*Buffer).grow allows for 2x capacity slop before sliding,
695
+ // so set our error threshold at 3x.
696
+ if cap1 > cap0*3 {
697
+ t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0)
698
+ }
699
+ }
700
+
701
+ func BenchmarkWriteByte(b *testing.B) {
702
+ const n = 4 << 10
703
+ b.SetBytes(n)
704
+ buf := NewBuffer(make([]byte, n))
705
+ for i := 0; i < b.N; i++ {
706
+ buf.Reset()
707
+ for i := 0; i < n; i++ {
708
+ buf.WriteByte('x')
709
+ }
710
+ }
711
+ }
712
+
713
+ func BenchmarkWriteRune(b *testing.B) {
714
+ const n = 4 << 10
715
+ const r = '☺'
716
+ b.SetBytes(int64(n * utf8.RuneLen(r)))
717
+ buf := NewBuffer(make([]byte, n*utf8.UTFMax))
718
+ for i := 0; i < b.N; i++ {
719
+ buf.Reset()
720
+ for i := 0; i < n; i++ {
721
+ buf.WriteRune(r)
722
+ }
723
+ }
724
+ }
725
+
726
+ // From Issue 5154.
727
+ func BenchmarkBufferNotEmptyWriteRead(b *testing.B) {
728
+ buf := make([]byte, 1024)
729
+ for i := 0; i < b.N; i++ {
730
+ var b Buffer
731
+ b.Write(buf[0:1])
732
+ for i := 0; i < 5<<10; i++ {
733
+ b.Write(buf)
734
+ b.Read(buf)
735
+ }
736
+ }
737
+ }
738
+
739
+ // Check that we don't compact too often. From Issue 5154.
740
+ func BenchmarkBufferFullSmallReads(b *testing.B) {
741
+ buf := make([]byte, 1024)
742
+ for i := 0; i < b.N; i++ {
743
+ var b Buffer
744
+ b.Write(buf)
745
+ for b.Len()+20 < b.Cap() {
746
+ b.Write(buf[:10])
747
+ }
748
+ for i := 0; i < 5<<10; i++ {
749
+ b.Read(buf[:1])
750
+ b.Write(buf[:1])
751
+ }
752
+ }
753
+ }
754
+
755
+ func BenchmarkBufferWriteBlock(b *testing.B) {
756
+ block := make([]byte, 1024)
757
+ for _, n := range []int{1 << 12, 1 << 16, 1 << 20} {
758
+ b.Run(fmt.Sprintf("N%d", n), func(b *testing.B) {
759
+ b.ReportAllocs()
760
+ for i := 0; i < b.N; i++ {
761
+ var bb Buffer
762
+ for bb.Len() < n {
763
+ bb.Write(block)
764
+ }
765
+ }
766
+ })
767
+ }
768
+ }
769
+
770
+ func BenchmarkBufferAppendNoCopy(b *testing.B) {
771
+ var bb Buffer
772
+ bb.Grow(16 << 20)
773
+ b.SetBytes(int64(bb.Available()))
774
+ b.ReportAllocs()
775
+ for i := 0; i < b.N; i++ {
776
+ bb.Reset()
777
+ b := bb.AvailableBuffer()
778
+ b = b[:cap(b)] // use max capacity to simulate a large append operation
779
+ bb.Write(b) // should be nearly infinitely fast
780
+ }
781
+ }
go/src/bytes/bytes.go ADDED
@@ -0,0 +1,1415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package bytes implements functions for the manipulation of byte slices.
6
+ // It is analogous to the facilities of the [strings] package.
7
+ package bytes
8
+
9
+ import (
10
+ "internal/bytealg"
11
+ "math/bits"
12
+ "unicode"
13
+ "unicode/utf8"
14
+ _ "unsafe" // for linkname
15
+ )
16
+
17
+ // Equal reports whether a and b
18
+ // are the same length and contain the same bytes.
19
+ // A nil argument is equivalent to an empty slice.
20
+ func Equal(a, b []byte) bool {
21
+ // Neither cmd/compile nor gccgo allocates for these string conversions.
22
+ return string(a) == string(b)
23
+ }
24
+
25
+ // Compare returns an integer comparing two byte slices lexicographically.
26
+ // The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
27
+ // A nil argument is equivalent to an empty slice.
28
+ func Compare(a, b []byte) int {
29
+ return bytealg.Compare(a, b)
30
+ }
31
+
32
+ // explode splits s into a slice of UTF-8 sequences, one per Unicode code point (still slices of bytes),
33
+ // up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes.
34
+ func explode(s []byte, n int) [][]byte {
35
+ if n <= 0 || n > len(s) {
36
+ n = len(s)
37
+ }
38
+ a := make([][]byte, n)
39
+ var size int
40
+ na := 0
41
+ for len(s) > 0 {
42
+ if na+1 >= n {
43
+ a[na] = s
44
+ na++
45
+ break
46
+ }
47
+ _, size = utf8.DecodeRune(s)
48
+ a[na] = s[0:size:size]
49
+ s = s[size:]
50
+ na++
51
+ }
52
+ return a[0:na]
53
+ }
54
+
55
+ // Count counts the number of non-overlapping instances of sep in s.
56
+ // If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
57
+ func Count(s, sep []byte) int {
58
+ // special case
59
+ if len(sep) == 0 {
60
+ return utf8.RuneCount(s) + 1
61
+ }
62
+ if len(sep) == 1 {
63
+ return bytealg.Count(s, sep[0])
64
+ }
65
+ n := 0
66
+ for {
67
+ i := Index(s, sep)
68
+ if i == -1 {
69
+ return n
70
+ }
71
+ n++
72
+ s = s[i+len(sep):]
73
+ }
74
+ }
75
+
76
+ // Contains reports whether subslice is within b.
77
+ func Contains(b, subslice []byte) bool {
78
+ return Index(b, subslice) != -1
79
+ }
80
+
81
+ // ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.
82
+ func ContainsAny(b []byte, chars string) bool {
83
+ return IndexAny(b, chars) >= 0
84
+ }
85
+
86
+ // ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.
87
+ func ContainsRune(b []byte, r rune) bool {
88
+ return IndexRune(b, r) >= 0
89
+ }
90
+
91
+ // ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).
92
+ func ContainsFunc(b []byte, f func(rune) bool) bool {
93
+ return IndexFunc(b, f) >= 0
94
+ }
95
+
96
+ // IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.
97
+ func IndexByte(b []byte, c byte) int {
98
+ return bytealg.IndexByte(b, c)
99
+ }
100
+
101
+ func indexBytePortable(s []byte, c byte) int {
102
+ for i, b := range s {
103
+ if b == c {
104
+ return i
105
+ }
106
+ }
107
+ return -1
108
+ }
109
+
110
+ // LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
111
+ func LastIndex(s, sep []byte) int {
112
+ n := len(sep)
113
+ switch {
114
+ case n == 0:
115
+ return len(s)
116
+ case n == 1:
117
+ return bytealg.LastIndexByte(s, sep[0])
118
+ case n == len(s):
119
+ if Equal(s, sep) {
120
+ return 0
121
+ }
122
+ return -1
123
+ case n > len(s):
124
+ return -1
125
+ }
126
+ return bytealg.LastIndexRabinKarp(s, sep)
127
+ }
128
+
129
+ // LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.
130
+ func LastIndexByte(s []byte, c byte) int {
131
+ return bytealg.LastIndexByte(s, c)
132
+ }
133
+
134
+ // IndexRune interprets s as a sequence of UTF-8-encoded code points.
135
+ // It returns the byte index of the first occurrence in s of the given rune.
136
+ // It returns -1 if rune is not present in s.
137
+ // If r is [utf8.RuneError], it returns the first instance of any
138
+ // invalid UTF-8 byte sequence.
139
+ func IndexRune(s []byte, r rune) int {
140
+ const haveFastIndex = bytealg.MaxBruteForce > 0
141
+ switch {
142
+ case 0 <= r && r < utf8.RuneSelf:
143
+ return IndexByte(s, byte(r))
144
+ case r == utf8.RuneError:
145
+ for i := 0; i < len(s); {
146
+ r1, n := utf8.DecodeRune(s[i:])
147
+ if r1 == utf8.RuneError {
148
+ return i
149
+ }
150
+ i += n
151
+ }
152
+ return -1
153
+ case !utf8.ValidRune(r):
154
+ return -1
155
+ default:
156
+ // Search for rune r using the last byte of its UTF-8 encoded form.
157
+ // The distribution of the last byte is more uniform compared to the
158
+ // first byte which has a 78% chance of being [240, 243, 244].
159
+ var b [utf8.UTFMax]byte
160
+ n := utf8.EncodeRune(b[:], r)
161
+ last := n - 1
162
+ i := last
163
+ fails := 0
164
+ for i < len(s) {
165
+ if s[i] != b[last] {
166
+ o := IndexByte(s[i+1:], b[last])
167
+ if o < 0 {
168
+ return -1
169
+ }
170
+ i += o + 1
171
+ }
172
+ // Step backwards comparing bytes.
173
+ for j := 1; j < n; j++ {
174
+ if s[i-j] != b[last-j] {
175
+ goto next
176
+ }
177
+ }
178
+ return i - last
179
+ next:
180
+ fails++
181
+ i++
182
+ if (haveFastIndex && fails > bytealg.Cutover(i)) && i < len(s) ||
183
+ (!haveFastIndex && fails >= 4+i>>4 && i < len(s)) {
184
+ goto fallback
185
+ }
186
+ }
187
+ return -1
188
+
189
+ fallback:
190
+ // Switch to bytealg.Index, if available, or a brute force search when
191
+ // IndexByte returns too many false positives.
192
+ if haveFastIndex {
193
+ if j := bytealg.Index(s[i-last:], b[:n]); j >= 0 {
194
+ return i + j - last
195
+ }
196
+ } else {
197
+ // If bytealg.Index is not available a brute force search is
198
+ // ~1.5-3x faster than Rabin-Karp since n is small.
199
+ c0 := b[last]
200
+ c1 := b[last-1] // There are at least 2 chars to match
201
+ loop:
202
+ for ; i < len(s); i++ {
203
+ if s[i] == c0 && s[i-1] == c1 {
204
+ for k := 2; k < n; k++ {
205
+ if s[i-k] != b[last-k] {
206
+ continue loop
207
+ }
208
+ }
209
+ return i - last
210
+ }
211
+ }
212
+ }
213
+ return -1
214
+ }
215
+ }
216
+
217
+ // IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points.
218
+ // It returns the byte index of the first occurrence in s of any of the Unicode
219
+ // code points in chars. It returns -1 if chars is empty or if there is no code
220
+ // point in common.
221
+ func IndexAny(s []byte, chars string) int {
222
+ if chars == "" {
223
+ // Avoid scanning all of s.
224
+ return -1
225
+ }
226
+ if len(s) == 1 {
227
+ r := rune(s[0])
228
+ if r >= utf8.RuneSelf {
229
+ // search utf8.RuneError.
230
+ for _, r = range chars {
231
+ if r == utf8.RuneError {
232
+ return 0
233
+ }
234
+ }
235
+ return -1
236
+ }
237
+ if bytealg.IndexByteString(chars, s[0]) >= 0 {
238
+ return 0
239
+ }
240
+ return -1
241
+ }
242
+ if len(chars) == 1 {
243
+ r := rune(chars[0])
244
+ if r >= utf8.RuneSelf {
245
+ r = utf8.RuneError
246
+ }
247
+ return IndexRune(s, r)
248
+ }
249
+ if len(s) > 8 {
250
+ if as, isASCII := makeASCIISet(chars); isASCII {
251
+ for i, c := range s {
252
+ if as.contains(c) {
253
+ return i
254
+ }
255
+ }
256
+ return -1
257
+ }
258
+ }
259
+ var width int
260
+ for i := 0; i < len(s); i += width {
261
+ r := rune(s[i])
262
+ if r < utf8.RuneSelf {
263
+ if bytealg.IndexByteString(chars, s[i]) >= 0 {
264
+ return i
265
+ }
266
+ width = 1
267
+ continue
268
+ }
269
+ r, width = utf8.DecodeRune(s[i:])
270
+ if r != utf8.RuneError {
271
+ // r is 2 to 4 bytes
272
+ if len(chars) == width {
273
+ if chars == string(r) {
274
+ return i
275
+ }
276
+ continue
277
+ }
278
+ // Use bytealg.IndexString for performance if available.
279
+ if bytealg.MaxLen >= width {
280
+ if bytealg.IndexString(chars, string(r)) >= 0 {
281
+ return i
282
+ }
283
+ continue
284
+ }
285
+ }
286
+ for _, ch := range chars {
287
+ if r == ch {
288
+ return i
289
+ }
290
+ }
291
+ }
292
+ return -1
293
+ }
294
+
295
+ // LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code
296
+ // points. It returns the byte index of the last occurrence in s of any of
297
+ // the Unicode code points in chars. It returns -1 if chars is empty or if
298
+ // there is no code point in common.
299
+ func LastIndexAny(s []byte, chars string) int {
300
+ if chars == "" {
301
+ // Avoid scanning all of s.
302
+ return -1
303
+ }
304
+ if len(s) > 8 {
305
+ if as, isASCII := makeASCIISet(chars); isASCII {
306
+ for i := len(s) - 1; i >= 0; i-- {
307
+ if as.contains(s[i]) {
308
+ return i
309
+ }
310
+ }
311
+ return -1
312
+ }
313
+ }
314
+ if len(s) == 1 {
315
+ r := rune(s[0])
316
+ if r >= utf8.RuneSelf {
317
+ for _, r = range chars {
318
+ if r == utf8.RuneError {
319
+ return 0
320
+ }
321
+ }
322
+ return -1
323
+ }
324
+ if bytealg.IndexByteString(chars, s[0]) >= 0 {
325
+ return 0
326
+ }
327
+ return -1
328
+ }
329
+ if len(chars) == 1 {
330
+ cr := rune(chars[0])
331
+ if cr >= utf8.RuneSelf {
332
+ cr = utf8.RuneError
333
+ }
334
+ for i := len(s); i > 0; {
335
+ r, size := utf8.DecodeLastRune(s[:i])
336
+ i -= size
337
+ if r == cr {
338
+ return i
339
+ }
340
+ }
341
+ return -1
342
+ }
343
+ for i := len(s); i > 0; {
344
+ r := rune(s[i-1])
345
+ if r < utf8.RuneSelf {
346
+ if bytealg.IndexByteString(chars, s[i-1]) >= 0 {
347
+ return i - 1
348
+ }
349
+ i--
350
+ continue
351
+ }
352
+ r, size := utf8.DecodeLastRune(s[:i])
353
+ i -= size
354
+ if r != utf8.RuneError {
355
+ // r is 2 to 4 bytes
356
+ if len(chars) == size {
357
+ if chars == string(r) {
358
+ return i
359
+ }
360
+ continue
361
+ }
362
+ // Use bytealg.IndexString for performance if available.
363
+ if bytealg.MaxLen >= size {
364
+ if bytealg.IndexString(chars, string(r)) >= 0 {
365
+ return i
366
+ }
367
+ continue
368
+ }
369
+ }
370
+ for _, ch := range chars {
371
+ if r == ch {
372
+ return i
373
+ }
374
+ }
375
+ }
376
+ return -1
377
+ }
378
+
379
+ // Generic split: splits after each instance of sep,
380
+ // including sepSave bytes of sep in the subslices.
381
+ func genSplit(s, sep []byte, sepSave, n int) [][]byte {
382
+ if n == 0 {
383
+ return nil
384
+ }
385
+ if len(sep) == 0 {
386
+ return explode(s, n)
387
+ }
388
+ if n < 0 {
389
+ n = Count(s, sep) + 1
390
+ }
391
+ if n > len(s)+1 {
392
+ n = len(s) + 1
393
+ }
394
+
395
+ a := make([][]byte, n)
396
+ n--
397
+ i := 0
398
+ for i < n {
399
+ m := Index(s, sep)
400
+ if m < 0 {
401
+ break
402
+ }
403
+ a[i] = s[: m+sepSave : m+sepSave]
404
+ s = s[m+len(sep):]
405
+ i++
406
+ }
407
+ a[i] = s
408
+ return a[:i+1]
409
+ }
410
+
411
+ // SplitN slices s into subslices separated by sep and returns a slice of
412
+ // the subslices between those separators.
413
+ // If sep is empty, SplitN splits after each UTF-8 sequence.
414
+ // The count determines the number of subslices to return:
415
+ // - n > 0: at most n subslices; the last subslice will be the unsplit remainder;
416
+ // - n == 0: the result is nil (zero subslices);
417
+ // - n < 0: all subslices.
418
+ //
419
+ // To split around the first instance of a separator, see [Cut].
420
+ func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
421
+
422
+ // SplitAfterN slices s into subslices after each instance of sep and
423
+ // returns a slice of those subslices.
424
+ // If sep is empty, SplitAfterN splits after each UTF-8 sequence.
425
+ // The count determines the number of subslices to return:
426
+ // - n > 0: at most n subslices; the last subslice will be the unsplit remainder;
427
+ // - n == 0: the result is nil (zero subslices);
428
+ // - n < 0: all subslices.
429
+ func SplitAfterN(s, sep []byte, n int) [][]byte {
430
+ return genSplit(s, sep, len(sep), n)
431
+ }
432
+
433
+ // Split slices s into all subslices separated by sep and returns a slice of
434
+ // the subslices between those separators.
435
+ // If sep is empty, Split splits after each UTF-8 sequence.
436
+ // It is equivalent to SplitN with a count of -1.
437
+ //
438
+ // To split around the first instance of a separator, see [Cut].
439
+ func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) }
440
+
441
+ // SplitAfter slices s into all subslices after each instance of sep and
442
+ // returns a slice of those subslices.
443
+ // If sep is empty, SplitAfter splits after each UTF-8 sequence.
444
+ // It is equivalent to SplitAfterN with a count of -1.
445
+ func SplitAfter(s, sep []byte) [][]byte {
446
+ return genSplit(s, sep, len(sep), -1)
447
+ }
448
+
449
+ var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
450
+
451
+ // Fields interprets s as a sequence of UTF-8-encoded code points.
452
+ // It splits the slice s around each instance of one or more consecutive white space
453
+ // characters, as defined by [unicode.IsSpace], returning a slice of subslices of s or an
454
+ // empty slice if s contains only white space. Every element of the returned slice is
455
+ // non-empty. Unlike [Split], leading and trailing runs of white space characters
456
+ // are discarded.
457
+ func Fields(s []byte) [][]byte {
458
+ // First count the fields.
459
+ // This is an exact count if s is ASCII, otherwise it is an approximation.
460
+ n := 0
461
+ wasSpace := 1
462
+ // setBits is used to track which bits are set in the bytes of s.
463
+ setBits := uint8(0)
464
+ for i := 0; i < len(s); i++ {
465
+ r := s[i]
466
+ setBits |= r
467
+ isSpace := int(asciiSpace[r])
468
+ n += wasSpace & ^isSpace
469
+ wasSpace = isSpace
470
+ }
471
+
472
+ if setBits >= utf8.RuneSelf {
473
+ // Some runes in the input slice are not ASCII.
474
+ return FieldsFunc(s, unicode.IsSpace)
475
+ }
476
+
477
+ // ASCII fast path
478
+ a := make([][]byte, n)
479
+ na := 0
480
+ fieldStart := 0
481
+ i := 0
482
+ // Skip spaces in the front of the input.
483
+ for i < len(s) && asciiSpace[s[i]] != 0 {
484
+ i++
485
+ }
486
+ fieldStart = i
487
+ for i < len(s) {
488
+ if asciiSpace[s[i]] == 0 {
489
+ i++
490
+ continue
491
+ }
492
+ a[na] = s[fieldStart:i:i]
493
+ na++
494
+ i++
495
+ // Skip spaces in between fields.
496
+ for i < len(s) && asciiSpace[s[i]] != 0 {
497
+ i++
498
+ }
499
+ fieldStart = i
500
+ }
501
+ if fieldStart < len(s) { // Last field might end at EOF.
502
+ a[na] = s[fieldStart:len(s):len(s)]
503
+ }
504
+ return a
505
+ }
506
+
507
+ // FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
508
+ // It splits the slice s at each run of code points c satisfying f(c) and
509
+ // returns a slice of subslices of s. If all code points in s satisfy f(c), or
510
+ // len(s) == 0, an empty slice is returned. Every element of the returned slice is
511
+ // non-empty. Unlike [Split], leading and trailing runs of code points
512
+ // satisfying f(c) are discarded.
513
+ //
514
+ // FieldsFunc makes no guarantees about the order in which it calls f(c)
515
+ // and assumes that f always returns the same value for a given c.
516
+ func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
517
+ // A span is used to record a slice of s of the form s[start:end].
518
+ // The start index is inclusive and the end index is exclusive.
519
+ type span struct {
520
+ start int
521
+ end int
522
+ }
523
+ spans := make([]span, 0, 32)
524
+
525
+ // Find the field start and end indices.
526
+ // Doing this in a separate pass (rather than slicing the string s
527
+ // and collecting the result substrings right away) is significantly
528
+ // more efficient, possibly due to cache effects.
529
+ start := -1 // valid span start if >= 0
530
+ for i := 0; i < len(s); {
531
+ r, size := utf8.DecodeRune(s[i:])
532
+ if f(r) {
533
+ if start >= 0 {
534
+ spans = append(spans, span{start, i})
535
+ start = -1
536
+ }
537
+ } else {
538
+ if start < 0 {
539
+ start = i
540
+ }
541
+ }
542
+ i += size
543
+ }
544
+
545
+ // Last field might end at EOF.
546
+ if start >= 0 {
547
+ spans = append(spans, span{start, len(s)})
548
+ }
549
+
550
+ // Create subslices from recorded field indices.
551
+ a := make([][]byte, len(spans))
552
+ for i, span := range spans {
553
+ a[i] = s[span.start:span.end:span.end]
554
+ }
555
+
556
+ return a
557
+ }
558
+
559
+ // Join concatenates the elements of s to create a new byte slice. The separator
560
+ // sep is placed between elements in the resulting slice.
561
+ func Join(s [][]byte, sep []byte) []byte {
562
+ if len(s) == 0 {
563
+ return []byte{}
564
+ }
565
+ if len(s) == 1 {
566
+ // Just return a copy.
567
+ return append([]byte(nil), s[0]...)
568
+ }
569
+
570
+ var n int
571
+ if len(sep) > 0 {
572
+ if len(sep) >= maxInt/(len(s)-1) {
573
+ panic("bytes: Join output length overflow")
574
+ }
575
+ n += len(sep) * (len(s) - 1)
576
+ }
577
+ for _, v := range s {
578
+ if len(v) > maxInt-n {
579
+ panic("bytes: Join output length overflow")
580
+ }
581
+ n += len(v)
582
+ }
583
+
584
+ b := bytealg.MakeNoZero(n)[:n:n]
585
+ bp := copy(b, s[0])
586
+ for _, v := range s[1:] {
587
+ bp += copy(b[bp:], sep)
588
+ bp += copy(b[bp:], v)
589
+ }
590
+ return b
591
+ }
592
+
593
+ // HasPrefix reports whether the byte slice s begins with prefix.
594
+ func HasPrefix(s, prefix []byte) bool {
595
+ return len(s) >= len(prefix) && Equal(s[:len(prefix)], prefix)
596
+ }
597
+
598
+ // HasSuffix reports whether the byte slice s ends with suffix.
599
+ func HasSuffix(s, suffix []byte) bool {
600
+ return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix)
601
+ }
602
+
603
+ // Map returns a copy of the byte slice s with all its characters modified
604
+ // according to the mapping function. If mapping returns a negative value, the character is
605
+ // dropped from the byte slice with no replacement. The characters in s and the
606
+ // output are interpreted as UTF-8-encoded code points.
607
+ func Map(mapping func(r rune) rune, s []byte) []byte {
608
+ // In the worst case, the slice can grow when mapped, making
609
+ // things unpleasant. But it's so rare we barge in assuming it's
610
+ // fine. It could also shrink but that falls out naturally.
611
+ b := make([]byte, 0, len(s))
612
+ for i := 0; i < len(s); {
613
+ r, wid := utf8.DecodeRune(s[i:])
614
+ r = mapping(r)
615
+ if r >= 0 {
616
+ b = utf8.AppendRune(b, r)
617
+ }
618
+ i += wid
619
+ }
620
+ return b
621
+ }
622
+
623
+ // Despite being an exported symbol,
624
+ // Repeat is linknamed by widely used packages.
625
+ // Notable members of the hall of shame include:
626
+ // - gitee.com/quant1x/num
627
+ //
628
+ // Do not remove or change the type signature.
629
+ // See go.dev/issue/67401.
630
+ //
631
+ // Note that this comment is not part of the doc comment.
632
+ //
633
+ //go:linkname Repeat
634
+
635
+ // Repeat returns a new byte slice consisting of count copies of b.
636
+ //
637
+ // It panics if count is negative or if the result of (len(b) * count)
638
+ // overflows.
639
+ func Repeat(b []byte, count int) []byte {
640
+ if count == 0 {
641
+ return []byte{}
642
+ }
643
+
644
+ // Since we cannot return an error on overflow,
645
+ // we should panic if the repeat will generate an overflow.
646
+ // See golang.org/issue/16237.
647
+ if count < 0 {
648
+ panic("bytes: negative Repeat count")
649
+ }
650
+ hi, lo := bits.Mul(uint(len(b)), uint(count))
651
+ if hi > 0 || lo > uint(maxInt) {
652
+ panic("bytes: Repeat output length overflow")
653
+ }
654
+ n := int(lo) // lo = len(b) * count
655
+
656
+ if len(b) == 0 {
657
+ return []byte{}
658
+ }
659
+
660
+ // Past a certain chunk size it is counterproductive to use
661
+ // larger chunks as the source of the write, as when the source
662
+ // is too large we are basically just thrashing the CPU D-cache.
663
+ // So if the result length is larger than an empirically-found
664
+ // limit (8KB), we stop growing the source string once the limit
665
+ // is reached and keep reusing the same source string - that
666
+ // should therefore be always resident in the L1 cache - until we
667
+ // have completed the construction of the result.
668
+ // This yields significant speedups (up to +100%) in cases where
669
+ // the result length is large (roughly, over L2 cache size).
670
+ const chunkLimit = 8 * 1024
671
+ chunkMax := n
672
+ if chunkMax > chunkLimit {
673
+ chunkMax = chunkLimit / len(b) * len(b)
674
+ if chunkMax == 0 {
675
+ chunkMax = len(b)
676
+ }
677
+ }
678
+ nb := bytealg.MakeNoZero(n)[:n:n]
679
+ bp := copy(nb, b)
680
+ for bp < n {
681
+ chunk := min(bp, chunkMax)
682
+ bp += copy(nb[bp:], nb[:chunk])
683
+ }
684
+ return nb
685
+ }
686
+
687
+ // ToUpper returns a copy of the byte slice s with all Unicode letters mapped to
688
+ // their upper case.
689
+ func ToUpper(s []byte) []byte {
690
+ isASCII, hasLower := true, false
691
+ for i := 0; i < len(s); i++ {
692
+ c := s[i]
693
+ if c >= utf8.RuneSelf {
694
+ isASCII = false
695
+ break
696
+ }
697
+ hasLower = hasLower || ('a' <= c && c <= 'z')
698
+ }
699
+
700
+ if isASCII { // optimize for ASCII-only byte slices.
701
+ if !hasLower {
702
+ // Just return a copy.
703
+ return append([]byte(""), s...)
704
+ }
705
+ b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
706
+ for i := 0; i < len(s); i++ {
707
+ c := s[i]
708
+ if 'a' <= c && c <= 'z' {
709
+ c -= 'a' - 'A'
710
+ }
711
+ b[i] = c
712
+ }
713
+ return b
714
+ }
715
+ return Map(unicode.ToUpper, s)
716
+ }
717
+
718
+ // ToLower returns a copy of the byte slice s with all Unicode letters mapped to
719
+ // their lower case.
720
+ func ToLower(s []byte) []byte {
721
+ isASCII, hasUpper := true, false
722
+ for i := 0; i < len(s); i++ {
723
+ c := s[i]
724
+ if c >= utf8.RuneSelf {
725
+ isASCII = false
726
+ break
727
+ }
728
+ hasUpper = hasUpper || ('A' <= c && c <= 'Z')
729
+ }
730
+
731
+ if isASCII { // optimize for ASCII-only byte slices.
732
+ if !hasUpper {
733
+ return append([]byte(""), s...)
734
+ }
735
+ b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
736
+ for i := 0; i < len(s); i++ {
737
+ c := s[i]
738
+ if 'A' <= c && c <= 'Z' {
739
+ c += 'a' - 'A'
740
+ }
741
+ b[i] = c
742
+ }
743
+ return b
744
+ }
745
+ return Map(unicode.ToLower, s)
746
+ }
747
+
748
+ // ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.
749
+ func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
750
+
751
+ // ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
752
+ // upper case, giving priority to the special casing rules.
753
+ func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte {
754
+ return Map(c.ToUpper, s)
755
+ }
756
+
757
+ // ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
758
+ // lower case, giving priority to the special casing rules.
759
+ func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte {
760
+ return Map(c.ToLower, s)
761
+ }
762
+
763
+ // ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
764
+ // title case, giving priority to the special casing rules.
765
+ func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte {
766
+ return Map(c.ToTitle, s)
767
+ }
768
+
769
+ // ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes
770
+ // representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.
771
+ func ToValidUTF8(s, replacement []byte) []byte {
772
+ b := make([]byte, 0, len(s)+len(replacement))
773
+ invalid := false // previous byte was from an invalid UTF-8 sequence
774
+ for i := 0; i < len(s); {
775
+ c := s[i]
776
+ if c < utf8.RuneSelf {
777
+ i++
778
+ invalid = false
779
+ b = append(b, c)
780
+ continue
781
+ }
782
+ _, wid := utf8.DecodeRune(s[i:])
783
+ if wid == 1 {
784
+ i++
785
+ if !invalid {
786
+ invalid = true
787
+ b = append(b, replacement...)
788
+ }
789
+ continue
790
+ }
791
+ invalid = false
792
+ b = append(b, s[i:i+wid]...)
793
+ i += wid
794
+ }
795
+ return b
796
+ }
797
+
798
+ // isSeparator reports whether the rune could mark a word boundary.
799
+ // TODO: update when package unicode captures more of the properties.
800
+ func isSeparator(r rune) bool {
801
+ // ASCII alphanumerics and underscore are not separators
802
+ if r <= 0x7F {
803
+ switch {
804
+ case '0' <= r && r <= '9':
805
+ return false
806
+ case 'a' <= r && r <= 'z':
807
+ return false
808
+ case 'A' <= r && r <= 'Z':
809
+ return false
810
+ case r == '_':
811
+ return false
812
+ }
813
+ return true
814
+ }
815
+ // Letters and digits are not separators
816
+ if unicode.IsLetter(r) || unicode.IsDigit(r) {
817
+ return false
818
+ }
819
+ // Otherwise, all we can do for now is treat spaces as separators.
820
+ return unicode.IsSpace(r)
821
+ }
822
+
823
+ // Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin
824
+ // words mapped to their title case.
825
+ //
826
+ // Deprecated: The rule Title uses for word boundaries does not handle Unicode
827
+ // punctuation properly. Use golang.org/x/text/cases instead.
828
+ func Title(s []byte) []byte {
829
+ // Use a closure here to remember state.
830
+ // Hackish but effective. Depends on Map scanning in order and calling
831
+ // the closure once per rune.
832
+ prev := ' '
833
+ return Map(
834
+ func(r rune) rune {
835
+ if isSeparator(prev) {
836
+ prev = r
837
+ return unicode.ToTitle(r)
838
+ }
839
+ prev = r
840
+ return r
841
+ },
842
+ s)
843
+ }
844
+
845
+ // TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off
846
+ // all leading UTF-8-encoded code points c that satisfy f(c).
847
+ func TrimLeftFunc(s []byte, f func(r rune) bool) []byte {
848
+ i := indexFunc(s, f, false)
849
+ if i == -1 {
850
+ return nil
851
+ }
852
+ return s[i:]
853
+ }
854
+
855
+ // TrimRightFunc returns a subslice of s by slicing off all trailing
856
+ // UTF-8-encoded code points c that satisfy f(c).
857
+ func TrimRightFunc(s []byte, f func(r rune) bool) []byte {
858
+ i := lastIndexFunc(s, f, false)
859
+ if i >= 0 && s[i] >= utf8.RuneSelf {
860
+ _, wid := utf8.DecodeRune(s[i:])
861
+ i += wid
862
+ } else {
863
+ i++
864
+ }
865
+ return s[0:i]
866
+ }
867
+
868
+ // TrimFunc returns a subslice of s by slicing off all leading and trailing
869
+ // UTF-8-encoded code points c that satisfy f(c).
870
+ func TrimFunc(s []byte, f func(r rune) bool) []byte {
871
+ return TrimRightFunc(TrimLeftFunc(s, f), f)
872
+ }
873
+
874
+ // TrimPrefix returns s without the provided leading prefix string.
875
+ // If s doesn't start with prefix, s is returned unchanged.
876
+ func TrimPrefix(s, prefix []byte) []byte {
877
+ if HasPrefix(s, prefix) {
878
+ return s[len(prefix):]
879
+ }
880
+ return s
881
+ }
882
+
883
+ // TrimSuffix returns s without the provided trailing suffix string.
884
+ // If s doesn't end with suffix, s is returned unchanged.
885
+ func TrimSuffix(s, suffix []byte) []byte {
886
+ if HasSuffix(s, suffix) {
887
+ return s[:len(s)-len(suffix)]
888
+ }
889
+ return s
890
+ }
891
+
892
+ // IndexFunc interprets s as a sequence of UTF-8-encoded code points.
893
+ // It returns the byte index in s of the first Unicode
894
+ // code point satisfying f(c), or -1 if none do.
895
+ func IndexFunc(s []byte, f func(r rune) bool) int {
896
+ return indexFunc(s, f, true)
897
+ }
898
+
899
+ // LastIndexFunc interprets s as a sequence of UTF-8-encoded code points.
900
+ // It returns the byte index in s of the last Unicode
901
+ // code point satisfying f(c), or -1 if none do.
902
+ func LastIndexFunc(s []byte, f func(r rune) bool) int {
903
+ return lastIndexFunc(s, f, true)
904
+ }
905
+
906
+ // indexFunc is the same as IndexFunc except that if
907
+ // truth==false, the sense of the predicate function is
908
+ // inverted.
909
+ func indexFunc(s []byte, f func(r rune) bool, truth bool) int {
910
+ start := 0
911
+ for start < len(s) {
912
+ r, wid := utf8.DecodeRune(s[start:])
913
+ if f(r) == truth {
914
+ return start
915
+ }
916
+ start += wid
917
+ }
918
+ return -1
919
+ }
920
+
921
+ // lastIndexFunc is the same as LastIndexFunc except that if
922
+ // truth==false, the sense of the predicate function is
923
+ // inverted.
924
+ func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int {
925
+ for i := len(s); i > 0; {
926
+ r, size := rune(s[i-1]), 1
927
+ if r >= utf8.RuneSelf {
928
+ r, size = utf8.DecodeLastRune(s[0:i])
929
+ }
930
+ i -= size
931
+ if f(r) == truth {
932
+ return i
933
+ }
934
+ }
935
+ return -1
936
+ }
937
+
938
+ // asciiSet is a 32-byte value, where each bit represents the presence of a
939
+ // given ASCII character in the set. The 128-bits of the lower 16 bytes,
940
+ // starting with the least-significant bit of the lowest word to the
941
+ // most-significant bit of the highest word, map to the full range of all
942
+ // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
943
+ // ensuring that any non-ASCII character will be reported as not in the set.
944
+ // This allocates a total of 32 bytes even though the upper half
945
+ // is unused to avoid bounds checks in asciiSet.contains.
946
+ type asciiSet [8]uint32
947
+
948
+ // makeASCIISet creates a set of ASCII characters and reports whether all
949
+ // characters in chars are ASCII.
950
+ func makeASCIISet(chars string) (as asciiSet, ok bool) {
951
+ for i := 0; i < len(chars); i++ {
952
+ c := chars[i]
953
+ if c >= utf8.RuneSelf {
954
+ return as, false
955
+ }
956
+ as[c/32] |= 1 << (c % 32)
957
+ }
958
+ return as, true
959
+ }
960
+
961
+ // contains reports whether c is inside the set.
962
+ func (as *asciiSet) contains(c byte) bool {
963
+ return (as[c/32] & (1 << (c % 32))) != 0
964
+ }
965
+
966
+ // containsRune is a simplified version of strings.ContainsRune
967
+ // to avoid importing the strings package.
968
+ // We avoid bytes.ContainsRune to avoid allocating a temporary copy of s.
969
+ func containsRune(s string, r rune) bool {
970
+ for _, c := range s {
971
+ if c == r {
972
+ return true
973
+ }
974
+ }
975
+ return false
976
+ }
977
+
978
+ // Trim returns a subslice of s by slicing off all leading and
979
+ // trailing UTF-8-encoded code points contained in cutset.
980
+ func Trim(s []byte, cutset string) []byte {
981
+ if len(s) == 0 {
982
+ // This is what we've historically done.
983
+ return nil
984
+ }
985
+ if cutset == "" {
986
+ return s
987
+ }
988
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
989
+ return trimLeftByte(trimRightByte(s, cutset[0]), cutset[0])
990
+ }
991
+ if as, ok := makeASCIISet(cutset); ok {
992
+ return trimLeftASCII(trimRightASCII(s, &as), &as)
993
+ }
994
+ return trimLeftUnicode(trimRightUnicode(s, cutset), cutset)
995
+ }
996
+
997
+ // TrimLeft returns a subslice of s by slicing off all leading
998
+ // UTF-8-encoded code points contained in cutset.
999
+ func TrimLeft(s []byte, cutset string) []byte {
1000
+ if len(s) == 0 {
1001
+ // This is what we've historically done.
1002
+ return nil
1003
+ }
1004
+ if cutset == "" {
1005
+ return s
1006
+ }
1007
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
1008
+ return trimLeftByte(s, cutset[0])
1009
+ }
1010
+ if as, ok := makeASCIISet(cutset); ok {
1011
+ return trimLeftASCII(s, &as)
1012
+ }
1013
+ return trimLeftUnicode(s, cutset)
1014
+ }
1015
+
1016
+ func trimLeftByte(s []byte, c byte) []byte {
1017
+ for len(s) > 0 && s[0] == c {
1018
+ s = s[1:]
1019
+ }
1020
+ if len(s) == 0 {
1021
+ // This is what we've historically done.
1022
+ return nil
1023
+ }
1024
+ return s
1025
+ }
1026
+
1027
+ func trimLeftASCII(s []byte, as *asciiSet) []byte {
1028
+ for len(s) > 0 {
1029
+ if !as.contains(s[0]) {
1030
+ break
1031
+ }
1032
+ s = s[1:]
1033
+ }
1034
+ if len(s) == 0 {
1035
+ // This is what we've historically done.
1036
+ return nil
1037
+ }
1038
+ return s
1039
+ }
1040
+
1041
+ func trimLeftUnicode(s []byte, cutset string) []byte {
1042
+ for len(s) > 0 {
1043
+ r, n := utf8.DecodeRune(s)
1044
+ if !containsRune(cutset, r) {
1045
+ break
1046
+ }
1047
+ s = s[n:]
1048
+ }
1049
+ if len(s) == 0 {
1050
+ // This is what we've historically done.
1051
+ return nil
1052
+ }
1053
+ return s
1054
+ }
1055
+
1056
+ // TrimRight returns a subslice of s by slicing off all trailing
1057
+ // UTF-8-encoded code points that are contained in cutset.
1058
+ func TrimRight(s []byte, cutset string) []byte {
1059
+ if len(s) == 0 || cutset == "" {
1060
+ return s
1061
+ }
1062
+ if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
1063
+ return trimRightByte(s, cutset[0])
1064
+ }
1065
+ if as, ok := makeASCIISet(cutset); ok {
1066
+ return trimRightASCII(s, &as)
1067
+ }
1068
+ return trimRightUnicode(s, cutset)
1069
+ }
1070
+
1071
+ func trimRightByte(s []byte, c byte) []byte {
1072
+ for len(s) > 0 && s[len(s)-1] == c {
1073
+ s = s[:len(s)-1]
1074
+ }
1075
+ return s
1076
+ }
1077
+
1078
+ func trimRightASCII(s []byte, as *asciiSet) []byte {
1079
+ for len(s) > 0 {
1080
+ if !as.contains(s[len(s)-1]) {
1081
+ break
1082
+ }
1083
+ s = s[:len(s)-1]
1084
+ }
1085
+ return s
1086
+ }
1087
+
1088
+ func trimRightUnicode(s []byte, cutset string) []byte {
1089
+ for len(s) > 0 {
1090
+ r, n := rune(s[len(s)-1]), 1
1091
+ if r >= utf8.RuneSelf {
1092
+ r, n = utf8.DecodeLastRune(s)
1093
+ }
1094
+ if !containsRune(cutset, r) {
1095
+ break
1096
+ }
1097
+ s = s[:len(s)-n]
1098
+ }
1099
+ return s
1100
+ }
1101
+
1102
+ // TrimSpace returns a subslice of s by slicing off all leading and
1103
+ // trailing white space, as defined by Unicode.
1104
+ func TrimSpace(s []byte) []byte {
1105
+ // Fast path for ASCII: look for the first ASCII non-space byte.
1106
+ for lo, c := range s {
1107
+ if c >= utf8.RuneSelf {
1108
+ // If we run into a non-ASCII byte, fall back to the
1109
+ // slower unicode-aware method on the remaining bytes.
1110
+ return TrimFunc(s[lo:], unicode.IsSpace)
1111
+ }
1112
+ if asciiSpace[c] != 0 {
1113
+ continue
1114
+ }
1115
+ s = s[lo:]
1116
+ // Now look for the first ASCII non-space byte from the end.
1117
+ for hi := len(s) - 1; hi >= 0; hi-- {
1118
+ c := s[hi]
1119
+ if c >= utf8.RuneSelf {
1120
+ return TrimFunc(s[:hi+1], unicode.IsSpace)
1121
+ }
1122
+ if asciiSpace[c] == 0 {
1123
+ // At this point, s[:hi+1] starts and ends with ASCII
1124
+ // non-space bytes, so we're done. Non-ASCII cases have
1125
+ // already been handled above.
1126
+ return s[:hi+1]
1127
+ }
1128
+ }
1129
+ }
1130
+ // Special case to preserve previous TrimLeftFunc behavior,
1131
+ // returning nil instead of empty slice if all spaces.
1132
+ return nil
1133
+ }
1134
+
1135
+ // Runes interprets s as a sequence of UTF-8-encoded code points.
1136
+ // It returns a slice of runes (Unicode code points) equivalent to s.
1137
+ func Runes(s []byte) []rune {
1138
+ t := make([]rune, utf8.RuneCount(s))
1139
+ i := 0
1140
+ for len(s) > 0 {
1141
+ r, l := utf8.DecodeRune(s)
1142
+ t[i] = r
1143
+ i++
1144
+ s = s[l:]
1145
+ }
1146
+ return t
1147
+ }
1148
+
1149
+ // Replace returns a copy of the slice s with the first n
1150
+ // non-overlapping instances of old replaced by new.
1151
+ // If old is empty, it matches at the beginning of the slice
1152
+ // and after each UTF-8 sequence, yielding up to k+1 replacements
1153
+ // for a k-rune slice.
1154
+ // If n < 0, there is no limit on the number of replacements.
1155
+ func Replace(s, old, new []byte, n int) []byte {
1156
+ m := 0
1157
+ if n != 0 {
1158
+ // Compute number of replacements.
1159
+ m = Count(s, old)
1160
+ }
1161
+ if m == 0 {
1162
+ // Just return a copy.
1163
+ return append([]byte(nil), s...)
1164
+ }
1165
+ if n < 0 || m < n {
1166
+ n = m
1167
+ }
1168
+
1169
+ // Apply replacements to buffer.
1170
+ t := make([]byte, len(s)+n*(len(new)-len(old)))
1171
+ w := 0
1172
+ start := 0
1173
+ if len(old) > 0 {
1174
+ for range n {
1175
+ j := start + Index(s[start:], old)
1176
+ w += copy(t[w:], s[start:j])
1177
+ w += copy(t[w:], new)
1178
+ start = j + len(old)
1179
+ }
1180
+ } else { // len(old) == 0
1181
+ w += copy(t[w:], new)
1182
+ for range n - 1 {
1183
+ _, wid := utf8.DecodeRune(s[start:])
1184
+ j := start + wid
1185
+ w += copy(t[w:], s[start:j])
1186
+ w += copy(t[w:], new)
1187
+ start = j
1188
+ }
1189
+ }
1190
+ w += copy(t[w:], s[start:])
1191
+ return t[0:w]
1192
+ }
1193
+
1194
+ // ReplaceAll returns a copy of the slice s with all
1195
+ // non-overlapping instances of old replaced by new.
1196
+ // If old is empty, it matches at the beginning of the slice
1197
+ // and after each UTF-8 sequence, yielding up to k+1 replacements
1198
+ // for a k-rune slice.
1199
+ func ReplaceAll(s, old, new []byte) []byte {
1200
+ return Replace(s, old, new, -1)
1201
+ }
1202
+
1203
+ // EqualFold reports whether s and t, interpreted as UTF-8 strings,
1204
+ // are equal under simple Unicode case-folding, which is a more general
1205
+ // form of case-insensitivity.
1206
+ func EqualFold(s, t []byte) bool {
1207
+ // ASCII fast path
1208
+ i := 0
1209
+ for n := min(len(s), len(t)); i < n; i++ {
1210
+ sr := s[i]
1211
+ tr := t[i]
1212
+ if sr|tr >= utf8.RuneSelf {
1213
+ goto hasUnicode
1214
+ }
1215
+
1216
+ // Easy case.
1217
+ if tr == sr {
1218
+ continue
1219
+ }
1220
+
1221
+ // Make sr < tr to simplify what follows.
1222
+ if tr < sr {
1223
+ tr, sr = sr, tr
1224
+ }
1225
+ // ASCII only, sr/tr must be upper/lower case
1226
+ if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
1227
+ continue
1228
+ }
1229
+ return false
1230
+ }
1231
+ // Check if we've exhausted both strings.
1232
+ return len(s) == len(t)
1233
+
1234
+ hasUnicode:
1235
+ s = s[i:]
1236
+ t = t[i:]
1237
+ for len(s) != 0 && len(t) != 0 {
1238
+ // Extract first rune from each.
1239
+ sr, size := utf8.DecodeRune(s)
1240
+ s = s[size:]
1241
+ tr, size := utf8.DecodeRune(t)
1242
+ t = t[size:]
1243
+
1244
+ // If they match, keep going; if not, return false.
1245
+
1246
+ // Easy case.
1247
+ if tr == sr {
1248
+ continue
1249
+ }
1250
+
1251
+ // Make sr < tr to simplify what follows.
1252
+ if tr < sr {
1253
+ tr, sr = sr, tr
1254
+ }
1255
+ // Fast check for ASCII.
1256
+ if tr < utf8.RuneSelf {
1257
+ // ASCII only, sr/tr must be upper/lower case
1258
+ if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
1259
+ continue
1260
+ }
1261
+ return false
1262
+ }
1263
+
1264
+ // General case. SimpleFold(x) returns the next equivalent rune > x
1265
+ // or wraps around to smaller values.
1266
+ r := unicode.SimpleFold(sr)
1267
+ for r != sr && r < tr {
1268
+ r = unicode.SimpleFold(r)
1269
+ }
1270
+ if r == tr {
1271
+ continue
1272
+ }
1273
+ return false
1274
+ }
1275
+
1276
+ // One string is empty. Are both?
1277
+ return len(s) == len(t)
1278
+ }
1279
+
1280
+ // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
1281
+ func Index(s, sep []byte) int {
1282
+ n := len(sep)
1283
+ switch {
1284
+ case n == 0:
1285
+ return 0
1286
+ case n == 1:
1287
+ return IndexByte(s, sep[0])
1288
+ case n == len(s):
1289
+ if Equal(sep, s) {
1290
+ return 0
1291
+ }
1292
+ return -1
1293
+ case n > len(s):
1294
+ return -1
1295
+ case n <= bytealg.MaxLen:
1296
+ // Use brute force when s and sep both are small
1297
+ if len(s) <= bytealg.MaxBruteForce {
1298
+ return bytealg.Index(s, sep)
1299
+ }
1300
+ c0 := sep[0]
1301
+ c1 := sep[1]
1302
+ i := 0
1303
+ t := len(s) - n + 1
1304
+ fails := 0
1305
+ for i < t {
1306
+ if s[i] != c0 {
1307
+ // IndexByte is faster than bytealg.Index, so use it as long as
1308
+ // we're not getting lots of false positives.
1309
+ o := IndexByte(s[i+1:t], c0)
1310
+ if o < 0 {
1311
+ return -1
1312
+ }
1313
+ i += o + 1
1314
+ }
1315
+ if s[i+1] == c1 && Equal(s[i:i+n], sep) {
1316
+ return i
1317
+ }
1318
+ fails++
1319
+ i++
1320
+ // Switch to bytealg.Index when IndexByte produces too many false positives.
1321
+ if fails > bytealg.Cutover(i) {
1322
+ r := bytealg.Index(s[i:], sep)
1323
+ if r >= 0 {
1324
+ return r + i
1325
+ }
1326
+ return -1
1327
+ }
1328
+ }
1329
+ return -1
1330
+ }
1331
+ c0 := sep[0]
1332
+ c1 := sep[1]
1333
+ i := 0
1334
+ fails := 0
1335
+ t := len(s) - n + 1
1336
+ for i < t {
1337
+ if s[i] != c0 {
1338
+ o := IndexByte(s[i+1:t], c0)
1339
+ if o < 0 {
1340
+ break
1341
+ }
1342
+ i += o + 1
1343
+ }
1344
+ if s[i+1] == c1 && Equal(s[i:i+n], sep) {
1345
+ return i
1346
+ }
1347
+ i++
1348
+ fails++
1349
+ if fails >= 4+i>>4 && i < t {
1350
+ // Give up on IndexByte, it isn't skipping ahead
1351
+ // far enough to be better than Rabin-Karp.
1352
+ // Experiments (using IndexPeriodic) suggest
1353
+ // the cutover is about 16 byte skips.
1354
+ // TODO: if large prefixes of sep are matching
1355
+ // we should cutover at even larger average skips,
1356
+ // because Equal becomes that much more expensive.
1357
+ // This code does not take that effect into account.
1358
+ j := bytealg.IndexRabinKarp(s[i:], sep)
1359
+ if j < 0 {
1360
+ return -1
1361
+ }
1362
+ return i + j
1363
+ }
1364
+ }
1365
+ return -1
1366
+ }
1367
+
1368
+ // Cut slices s around the first instance of sep,
1369
+ // returning the text before and after sep.
1370
+ // The found result reports whether sep appears in s.
1371
+ // If sep does not appear in s, cut returns s, nil, false.
1372
+ //
1373
+ // Cut returns slices of the original slice s, not copies.
1374
+ func Cut(s, sep []byte) (before, after []byte, found bool) {
1375
+ if i := Index(s, sep); i >= 0 {
1376
+ return s[:i], s[i+len(sep):], true
1377
+ }
1378
+ return s, nil, false
1379
+ }
1380
+
1381
+ // Clone returns a copy of b[:len(b)].
1382
+ // The result may have additional unused capacity.
1383
+ // Clone(nil) returns nil.
1384
+ func Clone(b []byte) []byte {
1385
+ if b == nil {
1386
+ return nil
1387
+ }
1388
+ return append([]byte{}, b...)
1389
+ }
1390
+
1391
+ // CutPrefix returns s without the provided leading prefix byte slice
1392
+ // and reports whether it found the prefix.
1393
+ // If s doesn't start with prefix, CutPrefix returns s, false.
1394
+ // If prefix is the empty byte slice, CutPrefix returns s, true.
1395
+ //
1396
+ // CutPrefix returns slices of the original slice s, not copies.
1397
+ func CutPrefix(s, prefix []byte) (after []byte, found bool) {
1398
+ if !HasPrefix(s, prefix) {
1399
+ return s, false
1400
+ }
1401
+ return s[len(prefix):], true
1402
+ }
1403
+
1404
+ // CutSuffix returns s without the provided ending suffix byte slice
1405
+ // and reports whether it found the suffix.
1406
+ // If s doesn't end with suffix, CutSuffix returns s, false.
1407
+ // If suffix is the empty byte slice, CutSuffix returns s, true.
1408
+ //
1409
+ // CutSuffix returns slices of the original slice s, not copies.
1410
+ func CutSuffix(s, suffix []byte) (before []byte, found bool) {
1411
+ if !HasSuffix(s, suffix) {
1412
+ return s, false
1413
+ }
1414
+ return s[:len(s)-len(suffix)], true
1415
+ }
go/src/bytes/bytes_js_wasm_test.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build js && wasm
6
+
7
+ package bytes_test
8
+
9
+ import (
10
+ "bytes"
11
+ "testing"
12
+ )
13
+
14
+ func TestIssue65571(t *testing.T) {
15
+ b := make([]byte, 1<<31+1)
16
+ b[1<<31] = 1
17
+ i := bytes.IndexByte(b, 1)
18
+ if i != 1<<31 {
19
+ t.Errorf("IndexByte(b, 1) = %d; want %d", i, 1<<31)
20
+ }
21
+ }
go/src/bytes/bytes_test.go ADDED
@@ -0,0 +1,2501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ . "bytes"
9
+ "fmt"
10
+ "internal/asan"
11
+ "internal/testenv"
12
+ "iter"
13
+ "math"
14
+ "math/rand"
15
+ "slices"
16
+ "strings"
17
+ "testing"
18
+ "unicode"
19
+ "unicode/utf8"
20
+ "unsafe"
21
+ )
22
+
23
+ func sliceOfString(s [][]byte) []string {
24
+ result := make([]string, len(s))
25
+ for i, v := range s {
26
+ result[i] = string(v)
27
+ }
28
+ return result
29
+ }
30
+
31
+ func collect(t *testing.T, seq iter.Seq[[]byte]) [][]byte {
32
+ out := slices.Collect(seq)
33
+ out1 := slices.Collect(seq)
34
+ if !slices.Equal(sliceOfString(out), sliceOfString(out1)) {
35
+ t.Fatalf("inconsistent seq:\n%s\n%s", out, out1)
36
+ }
37
+ return out
38
+ }
39
+
40
+ type LinesTest struct {
41
+ a string
42
+ b []string
43
+ }
44
+
45
+ var linesTests = []LinesTest{
46
+ {a: "abc\nabc\n", b: []string{"abc\n", "abc\n"}},
47
+ {a: "abc\r\nabc", b: []string{"abc\r\n", "abc"}},
48
+ {a: "abc\r\n", b: []string{"abc\r\n"}},
49
+ {a: "\nabc", b: []string{"\n", "abc"}},
50
+ {a: "\nabc\n\n", b: []string{"\n", "abc\n", "\n"}},
51
+ }
52
+
53
+ func TestLines(t *testing.T) {
54
+ for _, s := range linesTests {
55
+ result := sliceOfString(slices.Collect(Lines([]byte(s.a))))
56
+ if !slices.Equal(result, s.b) {
57
+ t.Errorf(`slices.Collect(Lines(%q)) = %q; want %q`, s.a, result, s.b)
58
+ }
59
+ }
60
+ }
61
+
62
+ // For ease of reading, the test cases use strings that are converted to byte
63
+ // slices before invoking the functions.
64
+
65
+ var abcd = "abcd"
66
+ var faces = "☺☻☹"
67
+ var commas = "1,2,3,4"
68
+ var dots = "1....2....3....4"
69
+
70
+ type BinOpTest struct {
71
+ a string
72
+ b string
73
+ i int
74
+ }
75
+
76
+ func TestEqual(t *testing.T) {
77
+ // Run the tests and check for allocation at the same time.
78
+ allocs := testing.AllocsPerRun(10, func() {
79
+ for _, tt := range compareTests {
80
+ eql := Equal(tt.a, tt.b)
81
+ if eql != (tt.i == 0) {
82
+ t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql)
83
+ }
84
+ }
85
+ })
86
+ if allocs > 0 {
87
+ t.Errorf("Equal allocated %v times", allocs)
88
+ }
89
+ }
90
+
91
+ func TestEqualExhaustive(t *testing.T) {
92
+ var size = 128
93
+ if testing.Short() {
94
+ size = 32
95
+ }
96
+ a := make([]byte, size)
97
+ b := make([]byte, size)
98
+ b_init := make([]byte, size)
99
+ // randomish but deterministic data
100
+ for i := 0; i < size; i++ {
101
+ a[i] = byte(17 * i)
102
+ b_init[i] = byte(23*i + 100)
103
+ }
104
+
105
+ for len := 0; len <= size; len++ {
106
+ for x := 0; x <= size-len; x++ {
107
+ for y := 0; y <= size-len; y++ {
108
+ copy(b, b_init)
109
+ copy(b[y:y+len], a[x:x+len])
110
+ if !Equal(a[x:x+len], b[y:y+len]) || !Equal(b[y:y+len], a[x:x+len]) {
111
+ t.Errorf("Equal(%d, %d, %d) = false", len, x, y)
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ // make sure Equal returns false for minimally different strings. The data
119
+ // is all zeros except for a single one in one location.
120
+ func TestNotEqual(t *testing.T) {
121
+ var size = 128
122
+ if testing.Short() {
123
+ size = 32
124
+ }
125
+ a := make([]byte, size)
126
+ b := make([]byte, size)
127
+
128
+ for len := 0; len <= size; len++ {
129
+ for x := 0; x <= size-len; x++ {
130
+ for y := 0; y <= size-len; y++ {
131
+ for diffpos := x; diffpos < x+len; diffpos++ {
132
+ a[diffpos] = 1
133
+ if Equal(a[x:x+len], b[y:y+len]) || Equal(b[y:y+len], a[x:x+len]) {
134
+ t.Errorf("NotEqual(%d, %d, %d, %d) = true", len, x, y, diffpos)
135
+ }
136
+ a[diffpos] = 0
137
+ }
138
+ }
139
+ }
140
+ }
141
+ }
142
+
143
+ var indexTests = []BinOpTest{
144
+ {"", "", 0},
145
+ {"", "a", -1},
146
+ {"", "foo", -1},
147
+ {"fo", "foo", -1},
148
+ {"foo", "baz", -1},
149
+ {"foo", "foo", 0},
150
+ {"oofofoofooo", "f", 2},
151
+ {"oofofoofooo", "foo", 4},
152
+ {"barfoobarfoo", "foo", 3},
153
+ {"foo", "", 0},
154
+ {"foo", "o", 1},
155
+ {"abcABCabc", "A", 3},
156
+ // cases with one byte strings - test IndexByte and special case in Index()
157
+ {"", "a", -1},
158
+ {"x", "a", -1},
159
+ {"x", "x", 0},
160
+ {"abc", "a", 0},
161
+ {"abc", "b", 1},
162
+ {"abc", "c", 2},
163
+ {"abc", "x", -1},
164
+ {"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33},
165
+ {"fofofofooofoboo", "oo", 7},
166
+ {"fofofofofofoboo", "ob", 11},
167
+ {"fofofofofofoboo", "boo", 12},
168
+ {"fofofofofofoboo", "oboo", 11},
169
+ {"fofofofofoooboo", "fooo", 8},
170
+ {"fofofofofofoboo", "foboo", 10},
171
+ {"fofofofofofoboo", "fofob", 8},
172
+ {"fofofofofofofoffofoobarfoo", "foffof", 12},
173
+ {"fofofofofoofofoffofoobarfoo", "foffof", 13},
174
+ {"fofofofofofofoffofoobarfoo", "foffofo", 12},
175
+ {"fofofofofoofofoffofoobarfoo", "foffofo", 13},
176
+ {"fofofofofoofofoffofoobarfoo", "foffofoo", 13},
177
+ {"fofofofofofofoffofoobarfoo", "foffofoo", 12},
178
+ {"fofofofofoofofoffofoobarfoo", "foffofoob", 13},
179
+ {"fofofofofofofoffofoobarfoo", "foffofoob", 12},
180
+ {"fofofofofoofofoffofoobarfoo", "foffofooba", 13},
181
+ {"fofofofofofofoffofoobarfoo", "foffofooba", 12},
182
+ {"fofofofofoofofoffofoobarfoo", "foffofoobar", 13},
183
+ {"fofofofofofofoffofoobarfoo", "foffofoobar", 12},
184
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarf", 13},
185
+ {"fofofofofofofoffofoobarfoo", "foffofoobarf", 12},
186
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarfo", 13},
187
+ {"fofofofofofofoffofoobarfoo", "foffofoobarfo", 12},
188
+ {"fofofofofoofofoffofoobarfoo", "foffofoobarfoo", 13},
189
+ {"fofofofofofofoffofoobarfoo", "foffofoobarfoo", 12},
190
+ {"fofofofofoofofoffofoobarfoo", "ofoffofoobarfoo", 12},
191
+ {"fofofofofofofoffofoobarfoo", "ofoffofoobarfoo", 11},
192
+ {"fofofofofoofofoffofoobarfoo", "fofoffofoobarfoo", 11},
193
+ {"fofofofofofofoffofoobarfoo", "fofoffofoobarfoo", 10},
194
+ {"fofofofofoofofoffofoobarfoo", "foobars", -1},
195
+ {"foofyfoobarfoobar", "y", 4},
196
+ {"oooooooooooooooooooooo", "r", -1},
197
+ {"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
198
+ {"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
199
+ // test fallback to Rabin-Karp.
200
+ {"000000000000000000000000000000000000000000000000000000000000000000000001", "0000000000000000000000000000000000000000000000000000000000000000001", 5},
201
+ // test fallback to IndexRune
202
+ {"oxoxoxoxoxoxoxoxoxoxox☺", "☺", 22},
203
+ // invalid UTF-8 byte sequence (must be longer than bytealg.MaxBruteForce to
204
+ // test that we don't use IndexRune)
205
+ {"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx\xed\x9f\xc0", "\xed\x9f\xc0", 105},
206
+ }
207
+
208
+ var lastIndexTests = []BinOpTest{
209
+ {"", "", 0},
210
+ {"", "a", -1},
211
+ {"", "foo", -1},
212
+ {"fo", "foo", -1},
213
+ {"foo", "foo", 0},
214
+ {"foo", "f", 0},
215
+ {"oofofoofooo", "f", 7},
216
+ {"oofofoofooo", "foo", 7},
217
+ {"barfoobarfoo", "foo", 9},
218
+ {"foo", "", 3},
219
+ {"foo", "o", 2},
220
+ {"abcABCabc", "A", 3},
221
+ {"abcABCabc", "a", 6},
222
+ }
223
+
224
+ var indexAnyTests = []BinOpTest{
225
+ {"", "", -1},
226
+ {"", "a", -1},
227
+ {"", "abc", -1},
228
+ {"a", "", -1},
229
+ {"a", "a", 0},
230
+ {"\x80", "\xffb", 0},
231
+ {"aaa", "a", 0},
232
+ {"abc", "xyz", -1},
233
+ {"abc", "xcz", 2},
234
+ {"ab☺c", "x☺yz", 2},
235
+ {"a☺b☻c☹d", "cx", len("a☺b☻")},
236
+ {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
237
+ {"aRegExp*", ".(|)*+?^$[]", 7},
238
+ {dots + dots + dots, " ", -1},
239
+ {"012abcba210", "\xffb", 4},
240
+ {"012\x80bcb\x80210", "\xffb", 3},
241
+ {"0123456\xcf\x80abc", "\xcfb\x80", 10},
242
+ }
243
+
244
+ var lastIndexAnyTests = []BinOpTest{
245
+ {"", "", -1},
246
+ {"", "a", -1},
247
+ {"", "abc", -1},
248
+ {"a", "", -1},
249
+ {"a", "a", 0},
250
+ {"\x80", "\xffb", 0},
251
+ {"aaa", "a", 2},
252
+ {"abc", "xyz", -1},
253
+ {"abc", "ab", 1},
254
+ {"ab☺c", "x☺yz", 2},
255
+ {"a☺b☻c☹d", "cx", len("a☺b☻")},
256
+ {"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
257
+ {"a.RegExp*", ".(|)*+?^$[]", 8},
258
+ {dots + dots + dots, " ", -1},
259
+ {"012abcba210", "\xffb", 6},
260
+ {"012\x80bcb\x80210", "\xffb", 7},
261
+ {"0123456\xcf\x80abc", "\xcfb\x80", 10},
262
+ }
263
+
264
+ // Execute f on each test case. funcName should be the name of f; it's used
265
+ // in failure reports.
266
+ func runIndexTests(t *testing.T, f func(s, sep []byte) int, funcName string, testCases []BinOpTest) {
267
+ for _, test := range testCases {
268
+ a := []byte(test.a)
269
+ b := []byte(test.b)
270
+ actual := f(a, b)
271
+ if actual != test.i {
272
+ t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, b, actual, test.i)
273
+ }
274
+ }
275
+ var allocTests = []struct {
276
+ a []byte
277
+ b []byte
278
+ i int
279
+ }{
280
+ // case for function Index.
281
+ {[]byte("000000000000000000000000000000000000000000000000000000000000000000000001"), []byte("0000000000000000000000000000000000000000000000000000000000000000001"), 5},
282
+ // case for function LastIndex.
283
+ {[]byte("000000000000000000000000000000000000000000000000000000000000000010000"), []byte("00000000000000000000000000000000000000000000000000000000000001"), 3},
284
+ }
285
+ allocs := testing.AllocsPerRun(100, func() {
286
+ if i := Index(allocTests[1].a, allocTests[1].b); i != allocTests[1].i {
287
+ t.Errorf("Index([]byte(%q), []byte(%q)) = %v; want %v", allocTests[1].a, allocTests[1].b, i, allocTests[1].i)
288
+ }
289
+ if i := LastIndex(allocTests[0].a, allocTests[0].b); i != allocTests[0].i {
290
+ t.Errorf("LastIndex([]byte(%q), []byte(%q)) = %v; want %v", allocTests[0].a, allocTests[0].b, i, allocTests[0].i)
291
+ }
292
+ })
293
+ if allocs != 0 {
294
+ t.Errorf("expected no allocations, got %f", allocs)
295
+ }
296
+ }
297
+
298
+ func runIndexAnyTests(t *testing.T, f func(s []byte, chars string) int, funcName string, testCases []BinOpTest) {
299
+ for _, test := range testCases {
300
+ a := []byte(test.a)
301
+ actual := f(a, test.b)
302
+ if actual != test.i {
303
+ t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, test.b, actual, test.i)
304
+ }
305
+ }
306
+ }
307
+
308
+ func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) }
309
+ func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
310
+ func TestIndexAny(t *testing.T) { runIndexAnyTests(t, IndexAny, "IndexAny", indexAnyTests) }
311
+ func TestLastIndexAny(t *testing.T) {
312
+ runIndexAnyTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests)
313
+ }
314
+
315
+ func TestIndexByte(t *testing.T) {
316
+ for _, tt := range indexTests {
317
+ if len(tt.b) != 1 {
318
+ continue
319
+ }
320
+ a := []byte(tt.a)
321
+ b := tt.b[0]
322
+ pos := IndexByte(a, b)
323
+ if pos != tt.i {
324
+ t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos)
325
+ }
326
+ posp := IndexBytePortable(a, b)
327
+ if posp != tt.i {
328
+ t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp)
329
+ }
330
+ }
331
+ }
332
+
333
+ func TestLastIndexByte(t *testing.T) {
334
+ testCases := []BinOpTest{
335
+ {"", "q", -1},
336
+ {"abcdef", "q", -1},
337
+ {"abcdefabcdef", "a", len("abcdef")}, // something in the middle
338
+ {"abcdefabcdef", "f", len("abcdefabcde")}, // last byte
339
+ {"zabcdefabcdef", "z", 0}, // first byte
340
+ {"a☺b☻c☹d", "b", len("a☺")}, // non-ascii
341
+ }
342
+ for _, test := range testCases {
343
+ actual := LastIndexByte([]byte(test.a), test.b[0])
344
+ if actual != test.i {
345
+ t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.a, test.b[0], actual, test.i)
346
+ }
347
+ }
348
+ }
349
+
350
+ // test a larger buffer with different sizes and alignments
351
+ func TestIndexByteBig(t *testing.T) {
352
+ var n = 1024
353
+ if testing.Short() {
354
+ n = 128
355
+ }
356
+ b := make([]byte, n)
357
+ for i := 0; i < n; i++ {
358
+ // different start alignments
359
+ b1 := b[i:]
360
+ for j := 0; j < len(b1); j++ {
361
+ b1[j] = 'x'
362
+ pos := IndexByte(b1, 'x')
363
+ if pos != j {
364
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
365
+ }
366
+ b1[j] = 0
367
+ pos = IndexByte(b1, 'x')
368
+ if pos != -1 {
369
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
370
+ }
371
+ }
372
+ // different end alignments
373
+ b1 = b[:i]
374
+ for j := 0; j < len(b1); j++ {
375
+ b1[j] = 'x'
376
+ pos := IndexByte(b1, 'x')
377
+ if pos != j {
378
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
379
+ }
380
+ b1[j] = 0
381
+ pos = IndexByte(b1, 'x')
382
+ if pos != -1 {
383
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
384
+ }
385
+ }
386
+ // different start and end alignments
387
+ b1 = b[i/2 : n-(i+1)/2]
388
+ for j := 0; j < len(b1); j++ {
389
+ b1[j] = 'x'
390
+ pos := IndexByte(b1, 'x')
391
+ if pos != j {
392
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
393
+ }
394
+ b1[j] = 0
395
+ pos = IndexByte(b1, 'x')
396
+ if pos != -1 {
397
+ t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
398
+ }
399
+ }
400
+ }
401
+ }
402
+
403
+ // test a small index across all page offsets
404
+ func TestIndexByteSmall(t *testing.T) {
405
+ b := make([]byte, 5015) // bigger than a page
406
+ // Make sure we find the correct byte even when straddling a page.
407
+ for i := 0; i <= len(b)-15; i++ {
408
+ for j := 0; j < 15; j++ {
409
+ b[i+j] = byte(100 + j)
410
+ }
411
+ for j := 0; j < 15; j++ {
412
+ p := IndexByte(b[i:i+15], byte(100+j))
413
+ if p != j {
414
+ t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 100+j, p)
415
+ }
416
+ }
417
+ for j := 0; j < 15; j++ {
418
+ b[i+j] = 0
419
+ }
420
+ }
421
+ // Make sure matches outside the slice never trigger.
422
+ for i := 0; i <= len(b)-15; i++ {
423
+ for j := 0; j < 15; j++ {
424
+ b[i+j] = 1
425
+ }
426
+ for j := 0; j < 15; j++ {
427
+ p := IndexByte(b[i:i+15], byte(0))
428
+ if p != -1 {
429
+ t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 0, p)
430
+ }
431
+ }
432
+ for j := 0; j < 15; j++ {
433
+ b[i+j] = 0
434
+ }
435
+ }
436
+ }
437
+
438
+ func TestIndexRune(t *testing.T) {
439
+ tests := []struct {
440
+ in string
441
+ rune rune
442
+ want int
443
+ }{
444
+ {"", 'a', -1},
445
+ {"", '☺', -1},
446
+ {"foo", '☹', -1},
447
+ {"foo", 'o', 1},
448
+ {"foo☺bar", '☺', 3},
449
+ {"foo☺☻☹bar", '☹', 9},
450
+ {"a A x", 'A', 2},
451
+ {"some_text=some_value", '=', 9},
452
+ {"☺a", 'a', 3},
453
+ {"a☻☺b", '☺', 4},
454
+ {"𠀳𠀗𠀾𠁄𠀧𠁆𠁂𠀫𠀖𠀪𠀲𠀴𠁀𠀨𠀿", '𠀿', 56},
455
+
456
+ // 2 bytes
457
+ {"ӆ", 'ӆ', 0},
458
+ {"a", 'ӆ', -1},
459
+ {" ӆ", 'ӆ', 2},
460
+ {" a", 'ӆ', -1},
461
+ {strings.Repeat("ц", 64) + "ӆ", 'ӆ', 128}, // test cutover
462
+ {strings.Repeat("ц", 64), 'ӆ', -1},
463
+
464
+ // 3 bytes
465
+ {"Ꚁ", 'Ꚁ', 0},
466
+ {"a", 'Ꚁ', -1},
467
+ {" Ꚁ", 'Ꚁ', 2},
468
+ {" a", 'Ꚁ', -1},
469
+ {strings.Repeat("Ꙁ", 64) + "Ꚁ", 'Ꚁ', 192}, // test cutover
470
+ {strings.Repeat("Ꙁ", 64) + "Ꚁ", '䚀', -1}, // 'Ꚁ' and '䚀' share the same last two bytes
471
+
472
+ // 4 bytes
473
+ {"𡌀", '𡌀', 0},
474
+ {"a", '𡌀', -1},
475
+ {" 𡌀", '𡌀', 2},
476
+ {" a", '𡌀', -1},
477
+ {strings.Repeat("𡋀", 64) + "𡌀", '𡌀', 256}, // test cutover
478
+ {strings.Repeat("𡋀", 64) + "𡌀", '𣌀', -1}, // '𡌀' and '𣌀' share the same last two bytes
479
+
480
+ // RuneError should match any invalid UTF-8 byte sequence.
481
+ {"�", '�', 0},
482
+ {"\xff", '�', 0},
483
+ {"☻x�", '�', len("☻x")},
484
+ {"☻x\xe2\x98", '�', len("☻x")},
485
+ {"☻x\xe2\x98�", '�', len("☻x")},
486
+ {"☻x\xe2\x98x", '�', len("☻x")},
487
+
488
+ // Invalid rune values should never match.
489
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
490
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair
491
+ {"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
492
+
493
+ // Test the cutover to bytealg.Index when it is triggered in
494
+ // the middle of rune that contains consecutive runs of equal bytes.
495
+ {"aaaaaKKKK\U000bc104", '\U000bc104', 17}, // cutover: (n + 16) / 8
496
+ {"aaaaaKKKK鄄", '鄄', 17},
497
+ {"aaKKKKKa\U000bc104", '\U000bc104', 18}, // cutover: 4 + n>>4
498
+ {"aaKKKKKa鄄", '鄄', 18},
499
+ }
500
+ for _, tt := range tests {
501
+ if got := IndexRune([]byte(tt.in), tt.rune); got != tt.want {
502
+ t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
503
+ }
504
+ }
505
+
506
+ haystack := []byte("test世界")
507
+ allocs := testing.AllocsPerRun(1000, func() {
508
+ if i := IndexRune(haystack, 's'); i != 2 {
509
+ t.Fatalf("'s' at %d; want 2", i)
510
+ }
511
+ if i := IndexRune(haystack, '世'); i != 4 {
512
+ t.Fatalf("'世' at %d; want 4", i)
513
+ }
514
+ })
515
+ if allocs != 0 {
516
+ t.Errorf("expected no allocations, got %f", allocs)
517
+ }
518
+ }
519
+
520
+ // test count of a single byte across page offsets
521
+ func TestCountByte(t *testing.T) {
522
+ b := make([]byte, 5015) // bigger than a page
523
+ windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
524
+ testCountWindow := func(i, window int) {
525
+ for j := 0; j < window; j++ {
526
+ b[i+j] = byte(100)
527
+ p := Count(b[i:i+window], []byte{100})
528
+ if p != j+1 {
529
+ t.Errorf("TestCountByte.Count(%q, 100) = %d", b[i:i+window], p)
530
+ }
531
+ }
532
+ }
533
+
534
+ maxWnd := windows[len(windows)-1]
535
+
536
+ for i := 0; i <= 2*maxWnd; i++ {
537
+ for _, window := range windows {
538
+ if window > len(b[i:]) {
539
+ window = len(b[i:])
540
+ }
541
+ testCountWindow(i, window)
542
+ for j := 0; j < window; j++ {
543
+ b[i+j] = byte(0)
544
+ }
545
+ }
546
+ }
547
+ for i := 4096 - (maxWnd + 1); i < len(b); i++ {
548
+ for _, window := range windows {
549
+ if window > len(b[i:]) {
550
+ window = len(b[i:])
551
+ }
552
+ testCountWindow(i, window)
553
+ for j := 0; j < window; j++ {
554
+ b[i+j] = byte(0)
555
+ }
556
+ }
557
+ }
558
+ }
559
+
560
+ // Make sure we don't count bytes outside our window
561
+ func TestCountByteNoMatch(t *testing.T) {
562
+ b := make([]byte, 5015)
563
+ windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
564
+ for i := 0; i <= len(b); i++ {
565
+ for _, window := range windows {
566
+ if window > len(b[i:]) {
567
+ window = len(b[i:])
568
+ }
569
+ // Fill the window with non-match
570
+ for j := 0; j < window; j++ {
571
+ b[i+j] = byte(100)
572
+ }
573
+ // Try to find something that doesn't exist
574
+ p := Count(b[i:i+window], []byte{0})
575
+ if p != 0 {
576
+ t.Errorf("TestCountByteNoMatch(%q, 0) = %d", b[i:i+window], p)
577
+ }
578
+ for j := 0; j < window; j++ {
579
+ b[i+j] = byte(0)
580
+ }
581
+ }
582
+ }
583
+ }
584
+
585
+ var bmbuf []byte
586
+
587
+ func valName(x int) string {
588
+ if s := x >> 20; s<<20 == x {
589
+ return fmt.Sprintf("%dM", s)
590
+ }
591
+ if s := x >> 10; s<<10 == x {
592
+ return fmt.Sprintf("%dK", s)
593
+ }
594
+ return fmt.Sprint(x)
595
+ }
596
+
597
+ func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
598
+ for _, n := range sizes {
599
+ if isRaceBuilder && n > 4<<10 {
600
+ continue
601
+ }
602
+ b.Run(valName(n), func(b *testing.B) {
603
+ if len(bmbuf) < n {
604
+ bmbuf = make([]byte, n)
605
+ }
606
+ b.SetBytes(int64(n))
607
+ f(b, n)
608
+ })
609
+ }
610
+ }
611
+
612
+ var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
613
+
614
+ var isRaceBuilder = strings.HasSuffix(testenv.Builder(), "-race")
615
+
616
+ func BenchmarkIndexByte(b *testing.B) {
617
+ benchBytes(b, indexSizes, bmIndexByte(IndexByte))
618
+ }
619
+
620
+ func BenchmarkIndexBytePortable(b *testing.B) {
621
+ benchBytes(b, indexSizes, bmIndexByte(IndexBytePortable))
622
+ }
623
+
624
+ func bmIndexByte(index func([]byte, byte) int) func(b *testing.B, n int) {
625
+ return func(b *testing.B, n int) {
626
+ buf := bmbuf[0:n]
627
+ buf[n-1] = 'x'
628
+ for i := 0; i < b.N; i++ {
629
+ j := index(buf, 'x')
630
+ if j != n-1 {
631
+ b.Fatal("bad index", j)
632
+ }
633
+ }
634
+ buf[n-1] = '\x00'
635
+ }
636
+ }
637
+
638
+ func BenchmarkIndexRune(b *testing.B) {
639
+ benchBytes(b, indexSizes, bmIndexRune(IndexRune))
640
+ }
641
+
642
+ func BenchmarkIndexRuneASCII(b *testing.B) {
643
+ benchBytes(b, indexSizes, bmIndexRuneASCII(IndexRune))
644
+ }
645
+
646
+ func BenchmarkIndexRuneUnicode(b *testing.B) {
647
+ b.Run("Latin", func(b *testing.B) {
648
+ // Latin is mostly 1, 2, 3 byte runes.
649
+ benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Latin, 'é'))
650
+ })
651
+ b.Run("Cyrillic", func(b *testing.B) {
652
+ // Cyrillic is mostly 2 and 3 byte runes.
653
+ benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Cyrillic, 'Ꙁ'))
654
+ })
655
+ b.Run("Han", func(b *testing.B) {
656
+ // Han consists only of 3 and 4 byte runes.
657
+ benchBytes(b, indexSizes, bmIndexRuneUnicode(unicode.Han, '𠀿'))
658
+ })
659
+ }
660
+
661
+ func bmIndexRuneASCII(index func([]byte, rune) int) func(b *testing.B, n int) {
662
+ return func(b *testing.B, n int) {
663
+ buf := bmbuf[0:n]
664
+ buf[n-1] = 'x'
665
+ for i := 0; i < b.N; i++ {
666
+ j := index(buf, 'x')
667
+ if j != n-1 {
668
+ b.Fatal("bad index", j)
669
+ }
670
+ }
671
+ buf[n-1] = '\x00'
672
+ }
673
+ }
674
+
675
+ func bmIndexRune(index func([]byte, rune) int) func(b *testing.B, n int) {
676
+ return func(b *testing.B, n int) {
677
+ buf := bmbuf[0:n]
678
+ utf8.EncodeRune(buf[n-3:], '世')
679
+ for i := 0; i < b.N; i++ {
680
+ j := index(buf, '世')
681
+ if j != n-3 {
682
+ b.Fatal("bad index", j)
683
+ }
684
+ }
685
+ buf[n-3] = '\x00'
686
+ buf[n-2] = '\x00'
687
+ buf[n-1] = '\x00'
688
+ }
689
+ }
690
+
691
+ func bmIndexRuneUnicode(rt *unicode.RangeTable, needle rune) func(b *testing.B, n int) {
692
+ var rs []rune
693
+ for _, r16 := range rt.R16 {
694
+ for r := rune(r16.Lo); r <= rune(r16.Hi); r += rune(r16.Stride) {
695
+ if r != needle {
696
+ rs = append(rs, r)
697
+ }
698
+ }
699
+ }
700
+ for _, r32 := range rt.R32 {
701
+ for r := rune(r32.Lo); r <= rune(r32.Hi); r += rune(r32.Stride) {
702
+ if r != needle {
703
+ rs = append(rs, r)
704
+ }
705
+ }
706
+ }
707
+ // Shuffle the runes so that they are not in descending order.
708
+ // The sort is deterministic since this is used for benchmarks,
709
+ // which need to be repeatable.
710
+ rr := rand.New(rand.NewSource(1))
711
+ rr.Shuffle(len(rs), func(i, j int) {
712
+ rs[i], rs[j] = rs[j], rs[i]
713
+ })
714
+ uchars := string(rs)
715
+
716
+ return func(b *testing.B, n int) {
717
+ buf := bmbuf[0:n]
718
+ o := copy(buf, uchars)
719
+ for o < len(buf) {
720
+ o += copy(buf[o:], uchars)
721
+ }
722
+
723
+ // Make space for the needle rune at the end of buf.
724
+ m := utf8.RuneLen(needle)
725
+ for o := m; o > 0; {
726
+ _, sz := utf8.DecodeLastRune(buf)
727
+ copy(buf[len(buf)-sz:], "\x00\x00\x00\x00")
728
+ buf = buf[:len(buf)-sz]
729
+ o -= sz
730
+ }
731
+ buf = utf8.AppendRune(buf[:n-m], needle)
732
+
733
+ n -= m // adjust for rune len
734
+ for i := 0; i < b.N; i++ {
735
+ j := IndexRune(buf, needle)
736
+ if j != n {
737
+ b.Fatal("bad index", j)
738
+ }
739
+ }
740
+ for i := range buf {
741
+ buf[i] = '\x00'
742
+ }
743
+ }
744
+ }
745
+
746
+ func BenchmarkEqual(b *testing.B) {
747
+ b.Run("0", func(b *testing.B) {
748
+ var buf [4]byte
749
+ buf1 := buf[0:0]
750
+ buf2 := buf[1:1]
751
+ for i := 0; i < b.N; i++ {
752
+ eq := Equal(buf1, buf2)
753
+ if !eq {
754
+ b.Fatal("bad equal")
755
+ }
756
+ }
757
+ })
758
+
759
+ sizes := []int{1, 6, 9, 15, 16, 20, 32, 4 << 10, 4 << 20, 64 << 20}
760
+
761
+ b.Run("same", func(b *testing.B) {
762
+ benchBytes(b, sizes, bmEqual(func(a, b []byte) bool { return Equal(a, a) }))
763
+ })
764
+
765
+ benchBytes(b, sizes, bmEqual(Equal))
766
+ }
767
+
768
+ func bmEqual(equal func([]byte, []byte) bool) func(b *testing.B, n int) {
769
+ return func(b *testing.B, n int) {
770
+ if len(bmbuf) < 2*n {
771
+ bmbuf = make([]byte, 2*n)
772
+ }
773
+ buf1 := bmbuf[0:n]
774
+ buf2 := bmbuf[n : 2*n]
775
+ buf1[n-1] = 'x'
776
+ buf2[n-1] = 'x'
777
+ for i := 0; i < b.N; i++ {
778
+ eq := equal(buf1, buf2)
779
+ if !eq {
780
+ b.Fatal("bad equal")
781
+ }
782
+ }
783
+ buf1[n-1] = '\x00'
784
+ buf2[n-1] = '\x00'
785
+ }
786
+ }
787
+
788
+ func BenchmarkEqualBothUnaligned(b *testing.B) {
789
+ sizes := []int{64, 4 << 10}
790
+ if !isRaceBuilder {
791
+ sizes = append(sizes, []int{4 << 20, 64 << 20}...)
792
+ }
793
+ maxSize := 2 * (sizes[len(sizes)-1] + 8)
794
+ if len(bmbuf) < maxSize {
795
+ bmbuf = make([]byte, maxSize)
796
+ }
797
+
798
+ for _, n := range sizes {
799
+ for _, off := range []int{0, 1, 4, 7} {
800
+ buf1 := bmbuf[off : off+n]
801
+ buf2Start := (len(bmbuf) / 2) + off
802
+ buf2 := bmbuf[buf2Start : buf2Start+n]
803
+ buf1[n-1] = 'x'
804
+ buf2[n-1] = 'x'
805
+ b.Run(fmt.Sprint(n, off), func(b *testing.B) {
806
+ b.SetBytes(int64(n))
807
+ for i := 0; i < b.N; i++ {
808
+ eq := Equal(buf1, buf2)
809
+ if !eq {
810
+ b.Fatal("bad equal")
811
+ }
812
+ }
813
+ })
814
+ buf1[n-1] = '\x00'
815
+ buf2[n-1] = '\x00'
816
+ }
817
+ }
818
+ }
819
+
820
+ func BenchmarkIndex(b *testing.B) {
821
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
822
+ buf := bmbuf[0:n]
823
+ buf[n-1] = 'x'
824
+ for i := 0; i < b.N; i++ {
825
+ j := Index(buf, buf[n-7:])
826
+ if j != n-7 {
827
+ b.Fatal("bad index", j)
828
+ }
829
+ }
830
+ buf[n-1] = '\x00'
831
+ })
832
+ }
833
+
834
+ func BenchmarkIndexEasy(b *testing.B) {
835
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
836
+ buf := bmbuf[0:n]
837
+ buf[n-1] = 'x'
838
+ buf[n-7] = 'x'
839
+ for i := 0; i < b.N; i++ {
840
+ j := Index(buf, buf[n-7:])
841
+ if j != n-7 {
842
+ b.Fatal("bad index", j)
843
+ }
844
+ }
845
+ buf[n-1] = '\x00'
846
+ buf[n-7] = '\x00'
847
+ })
848
+ }
849
+
850
+ func BenchmarkCount(b *testing.B) {
851
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
852
+ buf := bmbuf[0:n]
853
+ buf[n-1] = 'x'
854
+ for i := 0; i < b.N; i++ {
855
+ j := Count(buf, buf[n-7:])
856
+ if j != 1 {
857
+ b.Fatal("bad count", j)
858
+ }
859
+ }
860
+ buf[n-1] = '\x00'
861
+ })
862
+ }
863
+
864
+ func BenchmarkCountEasy(b *testing.B) {
865
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
866
+ buf := bmbuf[0:n]
867
+ buf[n-1] = 'x'
868
+ buf[n-7] = 'x'
869
+ for i := 0; i < b.N; i++ {
870
+ j := Count(buf, buf[n-7:])
871
+ if j != 1 {
872
+ b.Fatal("bad count", j)
873
+ }
874
+ }
875
+ buf[n-1] = '\x00'
876
+ buf[n-7] = '\x00'
877
+ })
878
+ }
879
+
880
+ func BenchmarkCountSingle(b *testing.B) {
881
+ benchBytes(b, indexSizes, func(b *testing.B, n int) {
882
+ buf := bmbuf[0:n]
883
+ step := 8
884
+ for i := 0; i < len(buf); i += step {
885
+ buf[i] = 1
886
+ }
887
+ expect := (len(buf) + (step - 1)) / step
888
+ for i := 0; i < b.N; i++ {
889
+ j := Count(buf, []byte{1})
890
+ if j != expect {
891
+ b.Fatal("bad count", j, expect)
892
+ }
893
+ }
894
+ clear(buf)
895
+ })
896
+ }
897
+
898
+ type SplitTest struct {
899
+ s string
900
+ sep string
901
+ n int
902
+ a []string
903
+ }
904
+
905
+ var splittests = []SplitTest{
906
+ {"", "", -1, []string{}},
907
+ {abcd, "a", 0, nil},
908
+ {abcd, "", 2, []string{"a", "bcd"}},
909
+ {abcd, "a", -1, []string{"", "bcd"}},
910
+ {abcd, "z", -1, []string{"abcd"}},
911
+ {abcd, "", -1, []string{"a", "b", "c", "d"}},
912
+ {commas, ",", -1, []string{"1", "2", "3", "4"}},
913
+ {dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
914
+ {faces, "☹", -1, []string{"☺☻", ""}},
915
+ {faces, "~", -1, []string{faces}},
916
+ {faces, "", -1, []string{"☺", "☻", "☹"}},
917
+ {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
918
+ {"1 2", " ", 3, []string{"1", "2"}},
919
+ {"123", "", 2, []string{"1", "23"}},
920
+ {"123", "", 17, []string{"1", "2", "3"}},
921
+ {"bT", "T", math.MaxInt / 4, []string{"b", ""}},
922
+ {"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}},
923
+ {"\xff-\xff", "-", -1, []string{"\xff", "\xff"}},
924
+ }
925
+
926
+ func TestSplit(t *testing.T) {
927
+ for _, tt := range splittests {
928
+ a := SplitN([]byte(tt.s), []byte(tt.sep), tt.n)
929
+
930
+ // Appending to the results should not change future results.
931
+ var x []byte
932
+ for _, v := range a {
933
+ x = append(v, 'z')
934
+ }
935
+
936
+ result := sliceOfString(a)
937
+ if !slices.Equal(result, tt.a) {
938
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
939
+ continue
940
+ }
941
+
942
+ if tt.n < 0 {
943
+ b := sliceOfString(slices.Collect(SplitSeq([]byte(tt.s), []byte(tt.sep))))
944
+ if !slices.Equal(b, tt.a) {
945
+ t.Errorf(`collect(SplitSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, b, tt.a)
946
+ }
947
+ }
948
+
949
+ if tt.n == 0 || len(a) == 0 {
950
+ continue
951
+ }
952
+
953
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
954
+ t.Errorf("last appended result was %s; want %s", x, want)
955
+ }
956
+
957
+ s := Join(a, []byte(tt.sep))
958
+ if string(s) != tt.s {
959
+ t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
960
+ }
961
+ if tt.n < 0 {
962
+ b := sliceOfString(Split([]byte(tt.s), []byte(tt.sep)))
963
+ if !slices.Equal(result, b) {
964
+ t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
965
+ }
966
+ }
967
+ if len(a) > 0 {
968
+ in, out := a[0], s
969
+ if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
970
+ t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep)
971
+ }
972
+ }
973
+ }
974
+ }
975
+
976
+ var splitaftertests = []SplitTest{
977
+ {abcd, "a", -1, []string{"a", "bcd"}},
978
+ {abcd, "z", -1, []string{"abcd"}},
979
+ {abcd, "", -1, []string{"a", "b", "c", "d"}},
980
+ {commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
981
+ {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
982
+ {faces, "☹", -1, []string{"☺☻☹", ""}},
983
+ {faces, "~", -1, []string{faces}},
984
+ {faces, "", -1, []string{"☺", "☻", "☹"}},
985
+ {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
986
+ {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
987
+ {"1 2", " ", 3, []string{"1 ", "2"}},
988
+ {"123", "", 2, []string{"1", "23"}},
989
+ {"123", "", 17, []string{"1", "2", "3"}},
990
+ }
991
+
992
+ func TestSplitAfter(t *testing.T) {
993
+ for _, tt := range splitaftertests {
994
+ a := SplitAfterN([]byte(tt.s), []byte(tt.sep), tt.n)
995
+
996
+ // Appending to the results should not change future results.
997
+ var x []byte
998
+ for _, v := range a {
999
+ x = append(v, 'z')
1000
+ }
1001
+
1002
+ result := sliceOfString(a)
1003
+ if !slices.Equal(result, tt.a) {
1004
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
1005
+ continue
1006
+ }
1007
+
1008
+ if tt.n < 0 {
1009
+ b := sliceOfString(slices.Collect(SplitAfterSeq([]byte(tt.s), []byte(tt.sep))))
1010
+ if !slices.Equal(b, tt.a) {
1011
+ t.Errorf(`collect(SplitAfterSeq(%q, %q)) = %v; want %v`, tt.s, tt.sep, b, tt.a)
1012
+ }
1013
+ }
1014
+
1015
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
1016
+ t.Errorf("last appended result was %s; want %s", x, want)
1017
+ }
1018
+
1019
+ s := Join(a, nil)
1020
+ if string(s) != tt.s {
1021
+ t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
1022
+ }
1023
+ if tt.n < 0 {
1024
+ b := sliceOfString(SplitAfter([]byte(tt.s), []byte(tt.sep)))
1025
+ if !slices.Equal(result, b) {
1026
+ t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
1027
+ }
1028
+ }
1029
+ }
1030
+ }
1031
+
1032
+ type FieldsTest struct {
1033
+ s string
1034
+ a []string
1035
+ }
1036
+
1037
+ var fieldstests = []FieldsTest{
1038
+ {"", []string{}},
1039
+ {" ", []string{}},
1040
+ {" \t ", []string{}},
1041
+ {" abc ", []string{"abc"}},
1042
+ {"1 2 3 4", []string{"1", "2", "3", "4"}},
1043
+ {"1 2 3 4", []string{"1", "2", "3", "4"}},
1044
+ {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
1045
+ {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
1046
+ {"\u2000\u2001\u2002", []string{}},
1047
+ {"\n™\t™\n", []string{"™", "™"}},
1048
+ {faces, []string{faces}},
1049
+ }
1050
+
1051
+ func TestFields(t *testing.T) {
1052
+ for _, tt := range fieldstests {
1053
+ b := []byte(tt.s)
1054
+ a := Fields(b)
1055
+
1056
+ // Appending to the results should not change future results.
1057
+ var x []byte
1058
+ for _, v := range a {
1059
+ x = append(v, 'z')
1060
+ }
1061
+
1062
+ result := sliceOfString(a)
1063
+ if !slices.Equal(result, tt.a) {
1064
+ t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
1065
+ continue
1066
+ }
1067
+
1068
+ result2 := sliceOfString(collect(t, FieldsSeq([]byte(tt.s))))
1069
+ if !slices.Equal(result2, tt.a) {
1070
+ t.Errorf(`collect(FieldsSeq(%q)) = %v; want %v`, tt.s, result2, tt.a)
1071
+ }
1072
+
1073
+ if string(b) != tt.s {
1074
+ t.Errorf("slice changed to %s; want %s", string(b), tt.s)
1075
+ }
1076
+ if len(tt.a) > 0 {
1077
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
1078
+ t.Errorf("last appended result was %s; want %s", x, want)
1079
+ }
1080
+ }
1081
+ }
1082
+ }
1083
+
1084
+ func TestFieldsFunc(t *testing.T) {
1085
+ for _, tt := range fieldstests {
1086
+ a := FieldsFunc([]byte(tt.s), unicode.IsSpace)
1087
+ result := sliceOfString(a)
1088
+ if !slices.Equal(result, tt.a) {
1089
+ t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
1090
+ continue
1091
+ }
1092
+ }
1093
+ pred := func(c rune) bool { return c == 'X' }
1094
+ var fieldsFuncTests = []FieldsTest{
1095
+ {"", []string{}},
1096
+ {"XX", []string{}},
1097
+ {"XXhiXXX", []string{"hi"}},
1098
+ {"aXXbXXXcX", []string{"a", "b", "c"}},
1099
+ }
1100
+ for _, tt := range fieldsFuncTests {
1101
+ b := []byte(tt.s)
1102
+ a := FieldsFunc(b, pred)
1103
+
1104
+ // Appending to the results should not change future results.
1105
+ var x []byte
1106
+ for _, v := range a {
1107
+ x = append(v, 'z')
1108
+ }
1109
+
1110
+ result := sliceOfString(a)
1111
+ if !slices.Equal(result, tt.a) {
1112
+ t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
1113
+ }
1114
+
1115
+ result2 := sliceOfString(collect(t, FieldsFuncSeq([]byte(tt.s), pred)))
1116
+ if !slices.Equal(result2, tt.a) {
1117
+ t.Errorf(`collect(FieldsFuncSeq(%q)) = %v; want %v`, tt.s, result2, tt.a)
1118
+ }
1119
+
1120
+ if string(b) != tt.s {
1121
+ t.Errorf("slice changed to %s; want %s", b, tt.s)
1122
+ }
1123
+ if len(tt.a) > 0 {
1124
+ if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
1125
+ t.Errorf("last appended result was %s; want %s", x, want)
1126
+ }
1127
+ }
1128
+ }
1129
+ }
1130
+
1131
+ // Test case for any function which accepts and returns a byte slice.
1132
+ // For ease of creation, we write the input byte slice as a string.
1133
+ type StringTest struct {
1134
+ in string
1135
+ out []byte
1136
+ }
1137
+
1138
+ var upperTests = []StringTest{
1139
+ {"", []byte("")},
1140
+ {"ONLYUPPER", []byte("ONLYUPPER")},
1141
+ {"abc", []byte("ABC")},
1142
+ {"AbC123", []byte("ABC123")},
1143
+ {"azAZ09_", []byte("AZAZ09_")},
1144
+ {"longStrinGwitHmixofsmaLLandcAps", []byte("LONGSTRINGWITHMIXOFSMALLANDCAPS")},
1145
+ {"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", []byte("LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS")},
1146
+ {"\u0250\u0250\u0250\u0250\u0250", []byte("\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F")}, // grows one byte per char
1147
+ {"a\u0080\U0010FFFF", []byte("A\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune
1148
+ }
1149
+
1150
+ var lowerTests = []StringTest{
1151
+ {"", []byte("")},
1152
+ {"abc", []byte("abc")},
1153
+ {"AbC123", []byte("abc123")},
1154
+ {"azAZ09_", []byte("azaz09_")},
1155
+ {"longStrinGwitHmixofsmaLLandcAps", []byte("longstringwithmixofsmallandcaps")},
1156
+ {"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", []byte("long\u0250string\u0250with\u0250nonascii\u0250chars")},
1157
+ {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", []byte("\u0251\u0251\u0251\u0251\u0251")}, // shrinks one byte per char
1158
+ {"A\u0080\U0010FFFF", []byte("a\u0080\U0010FFFF")}, // test utf8.RuneSelf and utf8.MaxRune
1159
+ }
1160
+
1161
+ const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
1162
+
1163
+ var trimSpaceTests = []StringTest{
1164
+ {"", nil},
1165
+ {" a", []byte("a")},
1166
+ {"b ", []byte("b")},
1167
+ {"abc", []byte("abc")},
1168
+ {space + "abc" + space, []byte("abc")},
1169
+ {" ", nil},
1170
+ {"\u3000 ", nil},
1171
+ {" \u3000", nil},
1172
+ {" \t\r\n \t\t\r\r\n\n ", nil},
1173
+ {" \t\r\n x\t\t\r\r\n\n ", []byte("x")},
1174
+ {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", []byte("x\t\t\r\r\ny")},
1175
+ {"1 \t\r\n2", []byte("1 \t\r\n2")},
1176
+ {" x\x80", []byte("x\x80")},
1177
+ {" x\xc0", []byte("x\xc0")},
1178
+ {"x \xc0\xc0 ", []byte("x \xc0\xc0")},
1179
+ {"x \xc0", []byte("x \xc0")},
1180
+ {"x \xc0 ", []byte("x \xc0")},
1181
+ {"x \xc0\xc0 ", []byte("x \xc0\xc0")},
1182
+ {"x ☺\xc0\xc0 ", []byte("x ☺\xc0\xc0")},
1183
+ {"x ☺ ", []byte("x ☺")},
1184
+ }
1185
+
1186
+ // Execute f on each test case. funcName should be the name of f; it's used
1187
+ // in failure reports.
1188
+ func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) {
1189
+ for _, tc := range testCases {
1190
+ actual := f([]byte(tc.in))
1191
+ if actual == nil && tc.out != nil {
1192
+ t.Errorf("%s(%q) = nil; want %q", funcName, tc.in, tc.out)
1193
+ }
1194
+ if actual != nil && tc.out == nil {
1195
+ t.Errorf("%s(%q) = %q; want nil", funcName, tc.in, actual)
1196
+ }
1197
+ if !Equal(actual, tc.out) {
1198
+ t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
1199
+ }
1200
+ }
1201
+ }
1202
+
1203
+ func tenRunes(r rune) string {
1204
+ runes := make([]rune, 10)
1205
+ for i := range runes {
1206
+ runes[i] = r
1207
+ }
1208
+ return string(runes)
1209
+ }
1210
+
1211
+ // User-defined self-inverse mapping function
1212
+ func rot13(r rune) rune {
1213
+ const step = 13
1214
+ if r >= 'a' && r <= 'z' {
1215
+ return ((r - 'a' + step) % 26) + 'a'
1216
+ }
1217
+ if r >= 'A' && r <= 'Z' {
1218
+ return ((r - 'A' + step) % 26) + 'A'
1219
+ }
1220
+ return r
1221
+ }
1222
+
1223
+ func TestMap(t *testing.T) {
1224
+ // Run a couple of awful growth/shrinkage tests
1225
+ a := tenRunes('a')
1226
+
1227
+ // 1. Grow. This triggers two reallocations in Map.
1228
+ maxRune := func(r rune) rune { return unicode.MaxRune }
1229
+ m := Map(maxRune, []byte(a))
1230
+ expect := tenRunes(unicode.MaxRune)
1231
+ if string(m) != expect {
1232
+ t.Errorf("growing: expected %q got %q", expect, m)
1233
+ }
1234
+
1235
+ // 2. Shrink
1236
+ minRune := func(r rune) rune { return 'a' }
1237
+ m = Map(minRune, []byte(tenRunes(unicode.MaxRune)))
1238
+ expect = a
1239
+ if string(m) != expect {
1240
+ t.Errorf("shrinking: expected %q got %q", expect, m)
1241
+ }
1242
+
1243
+ // 3. Rot13
1244
+ m = Map(rot13, []byte("a to zed"))
1245
+ expect = "n gb mrq"
1246
+ if string(m) != expect {
1247
+ t.Errorf("rot13: expected %q got %q", expect, m)
1248
+ }
1249
+
1250
+ // 4. Rot13^2
1251
+ m = Map(rot13, Map(rot13, []byte("a to zed")))
1252
+ expect = "a to zed"
1253
+ if string(m) != expect {
1254
+ t.Errorf("rot13: expected %q got %q", expect, m)
1255
+ }
1256
+
1257
+ // 5. Drop
1258
+ dropNotLatin := func(r rune) rune {
1259
+ if unicode.Is(unicode.Latin, r) {
1260
+ return r
1261
+ }
1262
+ return -1
1263
+ }
1264
+ m = Map(dropNotLatin, []byte("Hello, 세계"))
1265
+ expect = "Hello"
1266
+ if string(m) != expect {
1267
+ t.Errorf("drop: expected %q got %q", expect, m)
1268
+ }
1269
+
1270
+ // 6. Invalid rune
1271
+ invalidRune := func(r rune) rune {
1272
+ return utf8.MaxRune + 1
1273
+ }
1274
+ m = Map(invalidRune, []byte("x"))
1275
+ expect = "\uFFFD"
1276
+ if string(m) != expect {
1277
+ t.Errorf("invalidRune: expected %q got %q", expect, m)
1278
+ }
1279
+ }
1280
+
1281
+ func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
1282
+
1283
+ func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
1284
+
1285
+ func BenchmarkToUpper(b *testing.B) {
1286
+ for _, tc := range upperTests {
1287
+ tin := []byte(tc.in)
1288
+ b.Run(tc.in, func(b *testing.B) {
1289
+ for i := 0; i < b.N; i++ {
1290
+ actual := ToUpper(tin)
1291
+ if !Equal(actual, tc.out) {
1292
+ b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out)
1293
+ }
1294
+ }
1295
+ })
1296
+ }
1297
+ }
1298
+
1299
+ func BenchmarkToLower(b *testing.B) {
1300
+ for _, tc := range lowerTests {
1301
+ tin := []byte(tc.in)
1302
+ b.Run(tc.in, func(b *testing.B) {
1303
+ for i := 0; i < b.N; i++ {
1304
+ actual := ToLower(tin)
1305
+ if !Equal(actual, tc.out) {
1306
+ b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out)
1307
+ }
1308
+ }
1309
+ })
1310
+ }
1311
+ }
1312
+
1313
+ var toValidUTF8Tests = []struct {
1314
+ in string
1315
+ repl string
1316
+ out string
1317
+ }{
1318
+ {"", "\uFFFD", ""},
1319
+ {"abc", "\uFFFD", "abc"},
1320
+ {"\uFDDD", "\uFFFD", "\uFDDD"},
1321
+ {"a\xffb", "\uFFFD", "a\uFFFDb"},
1322
+ {"a\xffb\uFFFD", "X", "aXb\uFFFD"},
1323
+ {"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"},
1324
+ {"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"},
1325
+ {"\xC0\xAF", "\uFFFD", "\uFFFD"},
1326
+ {"\xE0\x80\xAF", "\uFFFD", "\uFFFD"},
1327
+ {"\xed\xa0\x80", "abc", "abc"},
1328
+ {"\xed\xbf\xbf", "\uFFFD", "\uFFFD"},
1329
+ {"\xF0\x80\x80\xaf", "☺", "☺"},
1330
+ {"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
1331
+ {"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
1332
+ }
1333
+
1334
+ func TestToValidUTF8(t *testing.T) {
1335
+ for _, tc := range toValidUTF8Tests {
1336
+ got := ToValidUTF8([]byte(tc.in), []byte(tc.repl))
1337
+ if !Equal(got, []byte(tc.out)) {
1338
+ t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out)
1339
+ }
1340
+ }
1341
+ }
1342
+
1343
+ func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
1344
+
1345
+ type RepeatTest struct {
1346
+ in, out string
1347
+ count int
1348
+ }
1349
+
1350
+ var longString = "a" + string(make([]byte, 1<<16)) + "z"
1351
+
1352
+ var RepeatTests = []RepeatTest{
1353
+ {"", "", 0},
1354
+ {"", "", 1},
1355
+ {"", "", 2},
1356
+ {"-", "", 0},
1357
+ {"-", "-", 1},
1358
+ {"-", "----------", 10},
1359
+ {"abc ", "abc abc abc ", 3},
1360
+ // Tests for results over the chunkLimit
1361
+ {string(rune(0)), string(make([]byte, 1<<16)), 1 << 16},
1362
+ {longString, longString + longString, 2},
1363
+ }
1364
+
1365
+ func TestRepeat(t *testing.T) {
1366
+ for _, tt := range RepeatTests {
1367
+ tin := []byte(tt.in)
1368
+ tout := []byte(tt.out)
1369
+ a := Repeat(tin, tt.count)
1370
+ if !Equal(a, tout) {
1371
+ t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout)
1372
+ continue
1373
+ }
1374
+ }
1375
+ }
1376
+
1377
+ func repeat(b []byte, count int) (err error) {
1378
+ defer func() {
1379
+ if r := recover(); r != nil {
1380
+ switch v := r.(type) {
1381
+ case error:
1382
+ err = v
1383
+ default:
1384
+ err = fmt.Errorf("%s", v)
1385
+ }
1386
+ }
1387
+ }()
1388
+
1389
+ Repeat(b, count)
1390
+
1391
+ return
1392
+ }
1393
+
1394
+ // See Issue golang.org/issue/16237
1395
+ func TestRepeatCatchesOverflow(t *testing.T) {
1396
+ type testCase struct {
1397
+ s string
1398
+ count int
1399
+ errStr string
1400
+ }
1401
+
1402
+ runTestCases := func(prefix string, tests []testCase) {
1403
+ for i, tt := range tests {
1404
+ err := repeat([]byte(tt.s), tt.count)
1405
+ if tt.errStr == "" {
1406
+ if err != nil {
1407
+ t.Errorf("#%d panicked %v", i, err)
1408
+ }
1409
+ continue
1410
+ }
1411
+
1412
+ if err == nil || !strings.Contains(err.Error(), tt.errStr) {
1413
+ t.Errorf("%s#%d got %q want %q", prefix, i, err, tt.errStr)
1414
+ }
1415
+ }
1416
+ }
1417
+
1418
+ const maxInt = int(^uint(0) >> 1)
1419
+
1420
+ runTestCases("", []testCase{
1421
+ 0: {"--", -2147483647, "negative"},
1422
+ 1: {"", maxInt, ""},
1423
+ 2: {"-", 10, ""},
1424
+ 3: {"gopher", 0, ""},
1425
+ 4: {"-", -1, "negative"},
1426
+ 5: {"--", -102, "negative"},
1427
+ 6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
1428
+ })
1429
+
1430
+ const is64Bit = 1<<(^uintptr(0)>>63)/2 != 0
1431
+ if !is64Bit {
1432
+ return
1433
+ }
1434
+
1435
+ runTestCases("64-bit", []testCase{
1436
+ 0: {"-", maxInt, "out of range"},
1437
+ })
1438
+ }
1439
+
1440
+ type RunesTest struct {
1441
+ in string
1442
+ out []rune
1443
+ lossy bool
1444
+ }
1445
+
1446
+ var RunesTests = []RunesTest{
1447
+ {"", []rune{}, false},
1448
+ {" ", []rune{32}, false},
1449
+ {"ABC", []rune{65, 66, 67}, false},
1450
+ {"abc", []rune{97, 98, 99}, false},
1451
+ {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
1452
+ {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
1453
+ {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
1454
+ }
1455
+
1456
+ func TestRunes(t *testing.T) {
1457
+ for _, tt := range RunesTests {
1458
+ tin := []byte(tt.in)
1459
+ a := Runes(tin)
1460
+ if !slices.Equal(a, tt.out) {
1461
+ t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out)
1462
+ continue
1463
+ }
1464
+ if !tt.lossy {
1465
+ // can only test reassembly if we didn't lose information
1466
+ s := string(a)
1467
+ if s != tt.in {
1468
+ t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin)
1469
+ }
1470
+ }
1471
+ }
1472
+ }
1473
+
1474
+ type TrimTest struct {
1475
+ f string
1476
+ in, arg, out string
1477
+ }
1478
+
1479
+ var trimTests = []TrimTest{
1480
+ {"Trim", "abba", "a", "bb"},
1481
+ {"Trim", "abba", "ab", ""},
1482
+ {"TrimLeft", "abba", "ab", ""},
1483
+ {"TrimRight", "abba", "ab", ""},
1484
+ {"TrimLeft", "abba", "a", "bba"},
1485
+ {"TrimLeft", "abba", "b", "abba"},
1486
+ {"TrimRight", "abba", "a", "abb"},
1487
+ {"TrimRight", "abba", "b", "abba"},
1488
+ {"Trim", "<tag>", "<>", "tag"},
1489
+ {"Trim", "* listitem", " *", "listitem"},
1490
+ {"Trim", `"quote"`, `"`, "quote"},
1491
+ {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
1492
+ {"Trim", "\x80test\xff", "\xff", "test"},
1493
+ {"Trim", " Ġ ", " ", "Ġ"},
1494
+ {"Trim", " Ġİ0", "0 ", "Ġİ"},
1495
+ //empty string tests
1496
+ {"Trim", "abba", "", "abba"},
1497
+ {"Trim", "", "123", ""},
1498
+ {"Trim", "", "", ""},
1499
+ {"TrimLeft", "abba", "", "abba"},
1500
+ {"TrimLeft", "", "123", ""},
1501
+ {"TrimLeft", "", "", ""},
1502
+ {"TrimRight", "abba", "", "abba"},
1503
+ {"TrimRight", "", "123", ""},
1504
+ {"TrimRight", "", "", ""},
1505
+ {"TrimRight", "☺\xc0", "☺", "☺\xc0"},
1506
+ {"TrimPrefix", "aabb", "a", "abb"},
1507
+ {"TrimPrefix", "aabb", "b", "aabb"},
1508
+ {"TrimSuffix", "aabb", "a", "aabb"},
1509
+ {"TrimSuffix", "aabb", "b", "aab"},
1510
+ }
1511
+
1512
+ type TrimNilTest struct {
1513
+ f string
1514
+ in []byte
1515
+ arg string
1516
+ out []byte
1517
+ }
1518
+
1519
+ var trimNilTests = []TrimNilTest{
1520
+ {"Trim", nil, "", nil},
1521
+ {"Trim", []byte{}, "", nil},
1522
+ {"Trim", []byte{'a'}, "a", nil},
1523
+ {"Trim", []byte{'a', 'a'}, "a", nil},
1524
+ {"Trim", []byte{'a'}, "ab", nil},
1525
+ {"Trim", []byte{'a', 'b'}, "ab", nil},
1526
+ {"Trim", []byte("☺"), "☺", nil},
1527
+ {"TrimLeft", nil, "", nil},
1528
+ {"TrimLeft", []byte{}, "", nil},
1529
+ {"TrimLeft", []byte{'a'}, "a", nil},
1530
+ {"TrimLeft", []byte{'a', 'a'}, "a", nil},
1531
+ {"TrimLeft", []byte{'a'}, "ab", nil},
1532
+ {"TrimLeft", []byte{'a', 'b'}, "ab", nil},
1533
+ {"TrimLeft", []byte("☺"), "☺", nil},
1534
+ {"TrimRight", nil, "", nil},
1535
+ {"TrimRight", []byte{}, "", []byte{}},
1536
+ {"TrimRight", []byte{'a'}, "a", []byte{}},
1537
+ {"TrimRight", []byte{'a', 'a'}, "a", []byte{}},
1538
+ {"TrimRight", []byte{'a'}, "ab", []byte{}},
1539
+ {"TrimRight", []byte{'a', 'b'}, "ab", []byte{}},
1540
+ {"TrimRight", []byte("☺"), "☺", []byte{}},
1541
+ {"TrimPrefix", nil, "", nil},
1542
+ {"TrimPrefix", []byte{}, "", []byte{}},
1543
+ {"TrimPrefix", []byte{'a'}, "a", []byte{}},
1544
+ {"TrimPrefix", []byte("☺"), "☺", []byte{}},
1545
+ {"TrimSuffix", nil, "", nil},
1546
+ {"TrimSuffix", []byte{}, "", []byte{}},
1547
+ {"TrimSuffix", []byte{'a'}, "a", []byte{}},
1548
+ {"TrimSuffix", []byte("☺"), "☺", []byte{}},
1549
+ }
1550
+
1551
+ func TestTrim(t *testing.T) {
1552
+ toFn := func(name string) (func([]byte, string) []byte, func([]byte, []byte) []byte) {
1553
+ switch name {
1554
+ case "Trim":
1555
+ return Trim, nil
1556
+ case "TrimLeft":
1557
+ return TrimLeft, nil
1558
+ case "TrimRight":
1559
+ return TrimRight, nil
1560
+ case "TrimPrefix":
1561
+ return nil, TrimPrefix
1562
+ case "TrimSuffix":
1563
+ return nil, TrimSuffix
1564
+ default:
1565
+ t.Errorf("Undefined trim function %s", name)
1566
+ return nil, nil
1567
+ }
1568
+ }
1569
+
1570
+ for _, tc := range trimTests {
1571
+ name := tc.f
1572
+ f, fb := toFn(name)
1573
+ if f == nil && fb == nil {
1574
+ continue
1575
+ }
1576
+ var actual string
1577
+ if f != nil {
1578
+ actual = string(f([]byte(tc.in), tc.arg))
1579
+ } else {
1580
+ actual = string(fb([]byte(tc.in), []byte(tc.arg)))
1581
+ }
1582
+ if actual != tc.out {
1583
+ t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
1584
+ }
1585
+ }
1586
+
1587
+ for _, tc := range trimNilTests {
1588
+ name := tc.f
1589
+ f, fb := toFn(name)
1590
+ if f == nil && fb == nil {
1591
+ continue
1592
+ }
1593
+ var actual []byte
1594
+ if f != nil {
1595
+ actual = f(tc.in, tc.arg)
1596
+ } else {
1597
+ actual = fb(tc.in, []byte(tc.arg))
1598
+ }
1599
+ report := func(s []byte) string {
1600
+ if s == nil {
1601
+ return "nil"
1602
+ } else {
1603
+ return fmt.Sprintf("%q", s)
1604
+ }
1605
+ }
1606
+ if len(actual) != 0 {
1607
+ t.Errorf("%s(%s, %q) returned non-empty value", name, report(tc.in), tc.arg)
1608
+ } else {
1609
+ actualNil := actual == nil
1610
+ outNil := tc.out == nil
1611
+ if actualNil != outNil {
1612
+ t.Errorf("%s(%s, %q) got nil %t; want nil %t", name, report(tc.in), tc.arg, actualNil, outNil)
1613
+ }
1614
+ }
1615
+ }
1616
+ }
1617
+
1618
+ type predicate struct {
1619
+ f func(r rune) bool
1620
+ name string
1621
+ }
1622
+
1623
+ var isSpace = predicate{unicode.IsSpace, "IsSpace"}
1624
+ var isDigit = predicate{unicode.IsDigit, "IsDigit"}
1625
+ var isUpper = predicate{unicode.IsUpper, "IsUpper"}
1626
+ var isValidRune = predicate{
1627
+ func(r rune) bool {
1628
+ return r != utf8.RuneError
1629
+ },
1630
+ "IsValidRune",
1631
+ }
1632
+
1633
+ type TrimFuncTest struct {
1634
+ f predicate
1635
+ in string
1636
+ trimOut []byte
1637
+ leftOut []byte
1638
+ rightOut []byte
1639
+ }
1640
+
1641
+ func not(p predicate) predicate {
1642
+ return predicate{
1643
+ func(r rune) bool {
1644
+ return !p.f(r)
1645
+ },
1646
+ "not " + p.name,
1647
+ }
1648
+ }
1649
+
1650
+ var trimFuncTests = []TrimFuncTest{
1651
+ {isSpace, space + " hello " + space,
1652
+ []byte("hello"),
1653
+ []byte("hello " + space),
1654
+ []byte(space + " hello")},
1655
+ {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51",
1656
+ []byte("hello"),
1657
+ []byte("hello34\u0e50\u0e51"),
1658
+ []byte("\u0e50\u0e5212hello")},
1659
+ {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
1660
+ []byte("hello"),
1661
+ []byte("helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F"),
1662
+ []byte("\u2C6F\u2C6F\u2C6F\u2C6FABCDhello")},
1663
+ {not(isSpace), "hello" + space + "hello",
1664
+ []byte(space),
1665
+ []byte(space + "hello"),
1666
+ []byte("hello" + space)},
1667
+ {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo",
1668
+ []byte("\u0e50\u0e521234\u0e50\u0e51"),
1669
+ []byte("\u0e50\u0e521234\u0e50\u0e51helo"),
1670
+ []byte("hello\u0e50\u0e521234\u0e50\u0e51")},
1671
+ {isValidRune, "ab\xc0a\xc0cd",
1672
+ []byte("\xc0a\xc0"),
1673
+ []byte("\xc0a\xc0cd"),
1674
+ []byte("ab\xc0a\xc0")},
1675
+ {not(isValidRune), "\xc0a\xc0",
1676
+ []byte("a"),
1677
+ []byte("a\xc0"),
1678
+ []byte("\xc0a")},
1679
+ // The nils returned by TrimLeftFunc are odd behavior, but we need
1680
+ // to preserve backwards compatibility.
1681
+ {isSpace, "",
1682
+ nil,
1683
+ nil,
1684
+ []byte("")},
1685
+ {isSpace, " ",
1686
+ nil,
1687
+ nil,
1688
+ []byte("")},
1689
+ }
1690
+
1691
+ func TestTrimFunc(t *testing.T) {
1692
+ for _, tc := range trimFuncTests {
1693
+ trimmers := []struct {
1694
+ name string
1695
+ trim func(s []byte, f func(r rune) bool) []byte
1696
+ out []byte
1697
+ }{
1698
+ {"TrimFunc", TrimFunc, tc.trimOut},
1699
+ {"TrimLeftFunc", TrimLeftFunc, tc.leftOut},
1700
+ {"TrimRightFunc", TrimRightFunc, tc.rightOut},
1701
+ }
1702
+ for _, trimmer := range trimmers {
1703
+ actual := trimmer.trim([]byte(tc.in), tc.f.f)
1704
+ if actual == nil && trimmer.out != nil {
1705
+ t.Errorf("%s(%q, %q) = nil; want %q", trimmer.name, tc.in, tc.f.name, trimmer.out)
1706
+ }
1707
+ if actual != nil && trimmer.out == nil {
1708
+ t.Errorf("%s(%q, %q) = %q; want nil", trimmer.name, tc.in, tc.f.name, actual)
1709
+ }
1710
+ if !Equal(actual, trimmer.out) {
1711
+ t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out)
1712
+ }
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ type IndexFuncTest struct {
1718
+ in string
1719
+ f predicate
1720
+ first, last int
1721
+ }
1722
+
1723
+ var indexFuncTests = []IndexFuncTest{
1724
+ {"", isValidRune, -1, -1},
1725
+ {"abc", isDigit, -1, -1},
1726
+ {"0123", isDigit, 0, 3},
1727
+ {"a1b", isDigit, 1, 1},
1728
+ {space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes
1729
+ {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
1730
+ {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
1731
+ {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
1732
+
1733
+ // tests of invalid UTF-8
1734
+ {"\x801", isDigit, 1, 1},
1735
+ {"\x80abc", isDigit, -1, -1},
1736
+ {"\xc0a\xc0", isValidRune, 1, 1},
1737
+ {"\xc0a\xc0", not(isValidRune), 0, 2},
1738
+ {"\xc0☺\xc0", not(isValidRune), 0, 4},
1739
+ {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
1740
+ {"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
1741
+ {"a\xe0\x80cd", not(isValidRune), 1, 2},
1742
+ }
1743
+
1744
+ func TestIndexFunc(t *testing.T) {
1745
+ for _, tc := range indexFuncTests {
1746
+ first := IndexFunc([]byte(tc.in), tc.f.f)
1747
+ if first != tc.first {
1748
+ t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
1749
+ }
1750
+ last := LastIndexFunc([]byte(tc.in), tc.f.f)
1751
+ if last != tc.last {
1752
+ t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
1753
+ }
1754
+ }
1755
+ }
1756
+
1757
+ type ReplaceTest struct {
1758
+ in string
1759
+ old, new string
1760
+ n int
1761
+ out string
1762
+ }
1763
+
1764
+ var ReplaceTests = []ReplaceTest{
1765
+ {"hello", "l", "L", 0, "hello"},
1766
+ {"hello", "l", "L", -1, "heLLo"},
1767
+ {"hello", "x", "X", -1, "hello"},
1768
+ {"", "x", "X", -1, ""},
1769
+ {"radar", "r", "<r>", -1, "<r>ada<r>"},
1770
+ {"", "", "<>", -1, "<>"},
1771
+ {"banana", "a", "<>", -1, "b<>n<>n<>"},
1772
+ {"banana", "a", "<>", 1, "b<>nana"},
1773
+ {"banana", "a", "<>", 1000, "b<>n<>n<>"},
1774
+ {"banana", "an", "<>", -1, "b<><>a"},
1775
+ {"banana", "ana", "<>", -1, "b<>na"},
1776
+ {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
1777
+ {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
1778
+ {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
1779
+ {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
1780
+ {"banana", "", "<>", 1, "<>banana"},
1781
+ {"banana", "a", "a", -1, "banana"},
1782
+ {"banana", "a", "a", 1, "banana"},
1783
+ {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
1784
+ }
1785
+
1786
+ func TestReplace(t *testing.T) {
1787
+ for _, tt := range ReplaceTests {
1788
+ var (
1789
+ in = []byte(tt.in)
1790
+ old = []byte(tt.old)
1791
+ new = []byte(tt.new)
1792
+ )
1793
+ if !asan.Enabled {
1794
+ allocs := testing.AllocsPerRun(10, func() { Replace(in, old, new, tt.n) })
1795
+ if allocs > 1 {
1796
+ t.Errorf("Replace(%q, %q, %q, %d) allocates %.2f objects", tt.in, tt.old, tt.new, tt.n, allocs)
1797
+ }
1798
+ }
1799
+ in = append(in, "<spare>"...)
1800
+ in = in[:len(tt.in)]
1801
+ out := Replace(in, old, new, tt.n)
1802
+ if s := string(out); s != tt.out {
1803
+ t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
1804
+ }
1805
+ if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
1806
+ t.Errorf("Replace(%q, %q, %q, %d) didn't copy", tt.in, tt.old, tt.new, tt.n)
1807
+ }
1808
+ if tt.n == -1 {
1809
+ out := ReplaceAll(in, old, new)
1810
+ if s := string(out); s != tt.out {
1811
+ t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out)
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+
1817
+ func FuzzReplace(f *testing.F) {
1818
+ for _, tt := range ReplaceTests {
1819
+ f.Add([]byte(tt.in), []byte(tt.old), []byte(tt.new), tt.n)
1820
+ }
1821
+ f.Fuzz(func(t *testing.T, in, old, new []byte, n int) {
1822
+ differentImpl := func(in, old, new []byte, n int) []byte {
1823
+ var out Buffer
1824
+ if n < 0 {
1825
+ n = math.MaxInt
1826
+ }
1827
+ for i := 0; i < len(in); {
1828
+ if n == 0 {
1829
+ out.Write(in[i:])
1830
+ break
1831
+ }
1832
+ if HasPrefix(in[i:], old) {
1833
+ out.Write(new)
1834
+ i += len(old)
1835
+ n--
1836
+ if len(old) != 0 {
1837
+ continue
1838
+ }
1839
+ if i == len(in) {
1840
+ break
1841
+ }
1842
+ }
1843
+ if len(old) == 0 {
1844
+ _, length := utf8.DecodeRune(in[i:])
1845
+ out.Write(in[i : i+length])
1846
+ i += length
1847
+ } else {
1848
+ out.WriteByte(in[i])
1849
+ i++
1850
+ }
1851
+ }
1852
+ if len(old) == 0 && n != 0 {
1853
+ out.Write(new)
1854
+ }
1855
+ return out.Bytes()
1856
+ }
1857
+ if simple, replace := differentImpl(in, old, new, n), Replace(in, old, new, n); !slices.Equal(simple, replace) {
1858
+ t.Errorf("The two implementations do not match %q != %q for Replace(%q, %q, %q, %d)", simple, replace, in, old, new, n)
1859
+ }
1860
+ })
1861
+ }
1862
+
1863
+ func BenchmarkReplace(b *testing.B) {
1864
+ for _, tt := range ReplaceTests {
1865
+ desc := fmt.Sprintf("%q %q %q %d", tt.in, tt.old, tt.new, tt.n)
1866
+ var (
1867
+ in = []byte(tt.in)
1868
+ old = []byte(tt.old)
1869
+ new = []byte(tt.new)
1870
+ )
1871
+ b.Run(desc, func(b *testing.B) {
1872
+ b.ReportAllocs()
1873
+ for b.Loop() {
1874
+ Replace(in, old, new, tt.n)
1875
+ }
1876
+ })
1877
+ }
1878
+ }
1879
+
1880
+ type TitleTest struct {
1881
+ in, out string
1882
+ }
1883
+
1884
+ var TitleTests = []TitleTest{
1885
+ {"", ""},
1886
+ {"a", "A"},
1887
+ {" aaa aaa aaa ", " Aaa Aaa Aaa "},
1888
+ {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
1889
+ {"123a456", "123a456"},
1890
+ {"double-blind", "Double-Blind"},
1891
+ {"ÿøû", "Ÿøû"},
1892
+ {"with_underscore", "With_underscore"},
1893
+ {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
1894
+ }
1895
+
1896
+ func TestTitle(t *testing.T) {
1897
+ for _, tt := range TitleTests {
1898
+ if s := string(Title([]byte(tt.in))); s != tt.out {
1899
+ t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
1900
+ }
1901
+ }
1902
+ }
1903
+
1904
+ var ToTitleTests = []TitleTest{
1905
+ {"", ""},
1906
+ {"a", "A"},
1907
+ {" aaa aaa aaa ", " AAA AAA AAA "},
1908
+ {" Aaa Aaa Aaa ", " AAA AAA AAA "},
1909
+ {"123a456", "123A456"},
1910
+ {"double-blind", "DOUBLE-BLIND"},
1911
+ {"ÿøû", "ŸØÛ"},
1912
+ }
1913
+
1914
+ func TestToTitle(t *testing.T) {
1915
+ for _, tt := range ToTitleTests {
1916
+ if s := string(ToTitle([]byte(tt.in))); s != tt.out {
1917
+ t.Errorf("ToTitle(%q) = %q, want %q", tt.in, s, tt.out)
1918
+ }
1919
+ }
1920
+ }
1921
+
1922
+ var EqualFoldTests = []struct {
1923
+ s, t string
1924
+ out bool
1925
+ }{
1926
+ {"abc", "abc", true},
1927
+ {"ABcd", "ABcd", true},
1928
+ {"123abc", "123ABC", true},
1929
+ {"αβδ", "ΑΒΔ", true},
1930
+ {"abc", "xyz", false},
1931
+ {"abc", "XYZ", false},
1932
+ {"abcdefghijk", "abcdefghijX", false},
1933
+ {"abcdefghijk", "abcdefghij\u212A", true},
1934
+ {"abcdefghijK", "abcdefghij\u212A", true},
1935
+ {"abcdefghijkz", "abcdefghij\u212Ay", false},
1936
+ {"abcdefghijKz", "abcdefghij\u212Ay", false},
1937
+ }
1938
+
1939
+ func TestEqualFold(t *testing.T) {
1940
+ for _, tt := range EqualFoldTests {
1941
+ if out := EqualFold([]byte(tt.s), []byte(tt.t)); out != tt.out {
1942
+ t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
1943
+ }
1944
+ if out := EqualFold([]byte(tt.t), []byte(tt.s)); out != tt.out {
1945
+ t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
1946
+ }
1947
+ }
1948
+ }
1949
+
1950
+ var cutTests = []struct {
1951
+ s, sep string
1952
+ before, after string
1953
+ found bool
1954
+ }{
1955
+ {"abc", "b", "a", "c", true},
1956
+ {"abc", "a", "", "bc", true},
1957
+ {"abc", "c", "ab", "", true},
1958
+ {"abc", "abc", "", "", true},
1959
+ {"abc", "", "", "abc", true},
1960
+ {"abc", "d", "abc", "", false},
1961
+ {"", "d", "", "", false},
1962
+ {"", "", "", "", true},
1963
+ }
1964
+
1965
+ func TestCut(t *testing.T) {
1966
+ for _, tt := range cutTests {
1967
+ if before, after, found := Cut([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(after) != tt.after || found != tt.found {
1968
+ t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
1969
+ }
1970
+ }
1971
+ }
1972
+
1973
+ var cutPrefixTests = []struct {
1974
+ s, sep string
1975
+ after string
1976
+ found bool
1977
+ }{
1978
+ {"abc", "a", "bc", true},
1979
+ {"abc", "abc", "", true},
1980
+ {"abc", "", "abc", true},
1981
+ {"abc", "d", "abc", false},
1982
+ {"", "d", "", false},
1983
+ {"", "", "", true},
1984
+ }
1985
+
1986
+ func TestCutPrefix(t *testing.T) {
1987
+ for _, tt := range cutPrefixTests {
1988
+ if after, found := CutPrefix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found {
1989
+ t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
1990
+ }
1991
+ }
1992
+ }
1993
+
1994
+ var cutSuffixTests = []struct {
1995
+ s, sep string
1996
+ before string
1997
+ found bool
1998
+ }{
1999
+ {"abc", "bc", "a", true},
2000
+ {"abc", "abc", "", true},
2001
+ {"abc", "", "abc", true},
2002
+ {"abc", "d", "abc", false},
2003
+ {"", "d", "", false},
2004
+ {"", "", "", true},
2005
+ }
2006
+
2007
+ func TestCutSuffix(t *testing.T) {
2008
+ for _, tt := range cutSuffixTests {
2009
+ if before, found := CutSuffix([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || found != tt.found {
2010
+ t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found)
2011
+ }
2012
+ }
2013
+ }
2014
+
2015
+ func TestBufferGrowNegative(t *testing.T) {
2016
+ defer func() {
2017
+ if err := recover(); err == nil {
2018
+ t.Fatal("Grow(-1) should have panicked")
2019
+ }
2020
+ }()
2021
+ var b Buffer
2022
+ b.Grow(-1)
2023
+ }
2024
+
2025
+ func TestBufferTruncateNegative(t *testing.T) {
2026
+ defer func() {
2027
+ if err := recover(); err == nil {
2028
+ t.Fatal("Truncate(-1) should have panicked")
2029
+ }
2030
+ }()
2031
+ var b Buffer
2032
+ b.Truncate(-1)
2033
+ }
2034
+
2035
+ func TestBufferTruncateOutOfRange(t *testing.T) {
2036
+ defer func() {
2037
+ if err := recover(); err == nil {
2038
+ t.Fatal("Truncate(20) should have panicked")
2039
+ }
2040
+ }()
2041
+ var b Buffer
2042
+ b.Write(make([]byte, 10))
2043
+ b.Truncate(20)
2044
+ }
2045
+
2046
+ var containsTests = []struct {
2047
+ b, subslice []byte
2048
+ want bool
2049
+ }{
2050
+ {[]byte("hello"), []byte("hel"), true},
2051
+ {[]byte("日本語"), []byte("日本"), true},
2052
+ {[]byte("hello"), []byte("Hello, world"), false},
2053
+ {[]byte("東京"), []byte("京東"), false},
2054
+ }
2055
+
2056
+ func TestContains(t *testing.T) {
2057
+ for _, tt := range containsTests {
2058
+ if got := Contains(tt.b, tt.subslice); got != tt.want {
2059
+ t.Errorf("Contains(%q, %q) = %v, want %v", tt.b, tt.subslice, got, tt.want)
2060
+ }
2061
+ }
2062
+ }
2063
+
2064
+ var ContainsAnyTests = []struct {
2065
+ b []byte
2066
+ substr string
2067
+ expected bool
2068
+ }{
2069
+ {[]byte(""), "", false},
2070
+ {[]byte(""), "a", false},
2071
+ {[]byte(""), "abc", false},
2072
+ {[]byte("a"), "", false},
2073
+ {[]byte("a"), "a", true},
2074
+ {[]byte("aaa"), "a", true},
2075
+ {[]byte("abc"), "xyz", false},
2076
+ {[]byte("abc"), "xcz", true},
2077
+ {[]byte("a☺b☻c☹d"), "uvw☻xyz", true},
2078
+ {[]byte("aRegExp*"), ".(|)*+?^$[]", true},
2079
+ {[]byte(dots + dots + dots), " ", false},
2080
+ }
2081
+
2082
+ func TestContainsAny(t *testing.T) {
2083
+ for _, ct := range ContainsAnyTests {
2084
+ if ContainsAny(ct.b, ct.substr) != ct.expected {
2085
+ t.Errorf("ContainsAny(%s, %s) = %v, want %v",
2086
+ ct.b, ct.substr, !ct.expected, ct.expected)
2087
+ }
2088
+ }
2089
+ }
2090
+
2091
+ var ContainsRuneTests = []struct {
2092
+ b []byte
2093
+ r rune
2094
+ expected bool
2095
+ }{
2096
+ {[]byte(""), 'a', false},
2097
+ {[]byte("a"), 'a', true},
2098
+ {[]byte("aaa"), 'a', true},
2099
+ {[]byte("abc"), 'y', false},
2100
+ {[]byte("abc"), 'c', true},
2101
+ {[]byte("a☺b☻c☹d"), 'x', false},
2102
+ {[]byte("a☺b☻c☹d"), '☻', true},
2103
+ {[]byte("aRegExp*"), '*', true},
2104
+ }
2105
+
2106
+ func TestContainsRune(t *testing.T) {
2107
+ for _, ct := range ContainsRuneTests {
2108
+ if ContainsRune(ct.b, ct.r) != ct.expected {
2109
+ t.Errorf("ContainsRune(%q, %q) = %v, want %v",
2110
+ ct.b, ct.r, !ct.expected, ct.expected)
2111
+ }
2112
+ }
2113
+ }
2114
+
2115
+ func TestContainsFunc(t *testing.T) {
2116
+ for _, ct := range ContainsRuneTests {
2117
+ if ContainsFunc(ct.b, func(r rune) bool {
2118
+ return ct.r == r
2119
+ }) != ct.expected {
2120
+ t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v",
2121
+ ct.b, ct.r, !ct.expected, ct.expected)
2122
+ }
2123
+ }
2124
+ }
2125
+
2126
+ var makeFieldsInput = func() []byte {
2127
+ x := make([]byte, 1<<20)
2128
+ // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.
2129
+ r := rand.New(rand.NewSource(99))
2130
+ for i := range x {
2131
+ switch r.Intn(10) {
2132
+ case 0:
2133
+ x[i] = ' '
2134
+ case 1:
2135
+ if i > 0 && x[i-1] == 'x' {
2136
+ copy(x[i-1:], "χ")
2137
+ break
2138
+ }
2139
+ fallthrough
2140
+ default:
2141
+ x[i] = 'x'
2142
+ }
2143
+ }
2144
+ return x
2145
+ }
2146
+
2147
+ var makeFieldsInputASCII = func() []byte {
2148
+ x := make([]byte, 1<<20)
2149
+ // Input is ~10% space, rest ASCII non-space.
2150
+ r := rand.New(rand.NewSource(99))
2151
+ for i := range x {
2152
+ if r.Intn(10) == 0 {
2153
+ x[i] = ' '
2154
+ } else {
2155
+ x[i] = 'x'
2156
+ }
2157
+ }
2158
+ return x
2159
+ }
2160
+
2161
+ var bytesdata = []struct {
2162
+ name string
2163
+ data []byte
2164
+ }{
2165
+ {"ASCII", makeFieldsInputASCII()},
2166
+ {"Mixed", makeFieldsInput()},
2167
+ }
2168
+
2169
+ func BenchmarkFields(b *testing.B) {
2170
+ for _, sd := range bytesdata {
2171
+ b.Run(sd.name, func(b *testing.B) {
2172
+ for j := 1 << 4; j <= 1<<20; j <<= 4 {
2173
+ b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
2174
+ b.ReportAllocs()
2175
+ b.SetBytes(int64(j))
2176
+ data := sd.data[:j]
2177
+ for i := 0; i < b.N; i++ {
2178
+ Fields(data)
2179
+ }
2180
+ })
2181
+ }
2182
+ })
2183
+ }
2184
+ }
2185
+
2186
+ func BenchmarkFieldsFunc(b *testing.B) {
2187
+ for _, sd := range bytesdata {
2188
+ b.Run(sd.name, func(b *testing.B) {
2189
+ for j := 1 << 4; j <= 1<<20; j <<= 4 {
2190
+ b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
2191
+ b.ReportAllocs()
2192
+ b.SetBytes(int64(j))
2193
+ data := sd.data[:j]
2194
+ for i := 0; i < b.N; i++ {
2195
+ FieldsFunc(data, unicode.IsSpace)
2196
+ }
2197
+ })
2198
+ }
2199
+ })
2200
+ }
2201
+ }
2202
+
2203
+ func BenchmarkTrimSpace(b *testing.B) {
2204
+ tests := []struct {
2205
+ name string
2206
+ input []byte
2207
+ }{
2208
+ {"NoTrim", []byte("typical")},
2209
+ {"ASCII", []byte(" foo bar ")},
2210
+ {"SomeNonASCII", []byte(" \u2000\t\r\n x\t\t\r\r\ny\n \u3000 ")},
2211
+ {"JustNonASCII", []byte("\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000")},
2212
+ }
2213
+ for _, test := range tests {
2214
+ b.Run(test.name, func(b *testing.B) {
2215
+ for i := 0; i < b.N; i++ {
2216
+ TrimSpace(test.input)
2217
+ }
2218
+ })
2219
+ }
2220
+ }
2221
+
2222
+ func BenchmarkToValidUTF8(b *testing.B) {
2223
+ tests := []struct {
2224
+ name string
2225
+ input []byte
2226
+ }{
2227
+ {"Valid", []byte("typical")},
2228
+ {"InvalidASCII", []byte("foo\xffbar")},
2229
+ {"InvalidNonASCII", []byte("日本語\xff日本語")},
2230
+ }
2231
+ replacement := []byte("\uFFFD")
2232
+ b.ResetTimer()
2233
+ for _, test := range tests {
2234
+ b.Run(test.name, func(b *testing.B) {
2235
+ for i := 0; i < b.N; i++ {
2236
+ ToValidUTF8(test.input, replacement)
2237
+ }
2238
+ })
2239
+ }
2240
+ }
2241
+
2242
+ func makeBenchInputHard() []byte {
2243
+ tokens := [...]string{
2244
+ "<a>", "<p>", "<b>", "<strong>",
2245
+ "</a>", "</p>", "</b>", "</strong>",
2246
+ "hello", "world",
2247
+ }
2248
+ x := make([]byte, 0, 1<<20)
2249
+ r := rand.New(rand.NewSource(99))
2250
+ for {
2251
+ i := r.Intn(len(tokens))
2252
+ if len(x)+len(tokens[i]) >= 1<<20 {
2253
+ break
2254
+ }
2255
+ x = append(x, tokens[i]...)
2256
+ }
2257
+ return x
2258
+ }
2259
+
2260
+ var benchInputHard = makeBenchInputHard()
2261
+
2262
+ func benchmarkIndexHard(b *testing.B, sep []byte) {
2263
+ n := Index(benchInputHard, sep)
2264
+ if n < 0 {
2265
+ n = len(benchInputHard)
2266
+ }
2267
+ b.SetBytes(int64(n))
2268
+ for i := 0; i < b.N; i++ {
2269
+ Index(benchInputHard, sep)
2270
+ }
2271
+ }
2272
+
2273
+ func benchmarkLastIndexHard(b *testing.B, sep []byte) {
2274
+ for i := 0; i < b.N; i++ {
2275
+ LastIndex(benchInputHard, sep)
2276
+ }
2277
+ }
2278
+
2279
+ func benchmarkCountHard(b *testing.B, sep []byte) {
2280
+ for i := 0; i < b.N; i++ {
2281
+ Count(benchInputHard, sep)
2282
+ }
2283
+ }
2284
+
2285
+ func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, []byte("<>")) }
2286
+ func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, []byte("</pre>")) }
2287
+ func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, []byte("<b>hello world</b>")) }
2288
+ func BenchmarkIndexHard4(b *testing.B) {
2289
+ benchmarkIndexHard(b, []byte("<pre><b>hello</b><strong>world</strong></pre>"))
2290
+ }
2291
+
2292
+ func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, []byte("<>")) }
2293
+ func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, []byte("</pre>")) }
2294
+ func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, []byte("<b>hello world</b>")) }
2295
+
2296
+ func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, []byte("<>")) }
2297
+ func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, []byte("</pre>")) }
2298
+ func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, []byte("<b>hello world</b>")) }
2299
+
2300
+ func BenchmarkSplitEmptySeparator(b *testing.B) {
2301
+ for i := 0; i < b.N; i++ {
2302
+ Split(benchInputHard, nil)
2303
+ }
2304
+ }
2305
+
2306
+ func BenchmarkSplitSingleByteSeparator(b *testing.B) {
2307
+ sep := []byte("/")
2308
+ for i := 0; i < b.N; i++ {
2309
+ Split(benchInputHard, sep)
2310
+ }
2311
+ }
2312
+
2313
+ func BenchmarkSplitMultiByteSeparator(b *testing.B) {
2314
+ sep := []byte("hello")
2315
+ for i := 0; i < b.N; i++ {
2316
+ Split(benchInputHard, sep)
2317
+ }
2318
+ }
2319
+
2320
+ func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
2321
+ sep := []byte("/")
2322
+ for i := 0; i < b.N; i++ {
2323
+ SplitN(benchInputHard, sep, 10)
2324
+ }
2325
+ }
2326
+
2327
+ func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
2328
+ sep := []byte("hello")
2329
+ for i := 0; i < b.N; i++ {
2330
+ SplitN(benchInputHard, sep, 10)
2331
+ }
2332
+ }
2333
+
2334
+ func BenchmarkRepeat(b *testing.B) {
2335
+ for i := 0; i < b.N; i++ {
2336
+ Repeat([]byte("-"), 80)
2337
+ }
2338
+ }
2339
+
2340
+ func BenchmarkRepeatLarge(b *testing.B) {
2341
+ s := Repeat([]byte("@"), 8*1024)
2342
+ for j := 8; j <= 30; j++ {
2343
+ for _, k := range []int{1, 16, 4097} {
2344
+ s := s[:k]
2345
+ n := (1 << j) / k
2346
+ if n == 0 {
2347
+ continue
2348
+ }
2349
+ b.Run(fmt.Sprintf("%d/%d", 1<<j, k), func(b *testing.B) {
2350
+ for i := 0; i < b.N; i++ {
2351
+ Repeat(s, n)
2352
+ }
2353
+ b.SetBytes(int64(n * len(s)))
2354
+ })
2355
+ }
2356
+ }
2357
+ }
2358
+
2359
+ func BenchmarkBytesCompare(b *testing.B) {
2360
+ for n := 1; n <= 2048; n <<= 1 {
2361
+ b.Run(fmt.Sprint(n), func(b *testing.B) {
2362
+ var x = make([]byte, n)
2363
+ var y = make([]byte, n)
2364
+
2365
+ for i := 0; i < n; i++ {
2366
+ x[i] = 'a'
2367
+ }
2368
+
2369
+ for i := 0; i < n; i++ {
2370
+ y[i] = 'a'
2371
+ }
2372
+
2373
+ b.ResetTimer()
2374
+ for i := 0; i < b.N; i++ {
2375
+ Compare(x, y)
2376
+ }
2377
+ })
2378
+ }
2379
+ }
2380
+
2381
+ func BenchmarkIndexAnyASCII(b *testing.B) {
2382
+ x := Repeat([]byte{'#'}, 2048) // Never matches set
2383
+ cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
2384
+ for k := 1; k <= 2048; k <<= 4 {
2385
+ for j := 1; j <= 64; j <<= 1 {
2386
+ b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2387
+ for i := 0; i < b.N; i++ {
2388
+ IndexAny(x[:k], cs[:j])
2389
+ }
2390
+ })
2391
+ }
2392
+ }
2393
+ }
2394
+
2395
+ func BenchmarkIndexAnyUTF8(b *testing.B) {
2396
+ x := Repeat([]byte{'#'}, 2048) // Never matches set
2397
+ cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
2398
+ for k := 1; k <= 2048; k <<= 4 {
2399
+ for j := 1; j <= 64; j <<= 1 {
2400
+ b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2401
+ for i := 0; i < b.N; i++ {
2402
+ IndexAny(x[:k], cs[:j])
2403
+ }
2404
+ })
2405
+ }
2406
+ }
2407
+ }
2408
+
2409
+ func BenchmarkLastIndexAnyASCII(b *testing.B) {
2410
+ x := Repeat([]byte{'#'}, 2048) // Never matches set
2411
+ cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
2412
+ for k := 1; k <= 2048; k <<= 4 {
2413
+ for j := 1; j <= 64; j <<= 1 {
2414
+ b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2415
+ for i := 0; i < b.N; i++ {
2416
+ LastIndexAny(x[:k], cs[:j])
2417
+ }
2418
+ })
2419
+ }
2420
+ }
2421
+ }
2422
+
2423
+ func BenchmarkLastIndexAnyUTF8(b *testing.B) {
2424
+ x := Repeat([]byte{'#'}, 2048) // Never matches set
2425
+ cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
2426
+ for k := 1; k <= 2048; k <<= 4 {
2427
+ for j := 1; j <= 64; j <<= 1 {
2428
+ b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2429
+ for i := 0; i < b.N; i++ {
2430
+ LastIndexAny(x[:k], cs[:j])
2431
+ }
2432
+ })
2433
+ }
2434
+ }
2435
+ }
2436
+
2437
+ func BenchmarkTrimASCII(b *testing.B) {
2438
+ cs := "0123456789abcdef"
2439
+ for k := 1; k <= 4096; k <<= 4 {
2440
+ for j := 1; j <= 16; j <<= 1 {
2441
+ b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
2442
+ x := Repeat([]byte(cs[:j]), k) // Always matches set
2443
+ for i := 0; i < b.N; i++ {
2444
+ Trim(x[:k], cs[:j])
2445
+ }
2446
+ })
2447
+ }
2448
+ }
2449
+ }
2450
+
2451
+ func BenchmarkTrimByte(b *testing.B) {
2452
+ x := []byte(" the quick brown fox ")
2453
+ for i := 0; i < b.N; i++ {
2454
+ Trim(x, " ")
2455
+ }
2456
+ }
2457
+
2458
+ func BenchmarkIndexPeriodic(b *testing.B) {
2459
+ key := []byte{1, 1}
2460
+ for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
2461
+ b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
2462
+ buf := make([]byte, 1<<16)
2463
+ for i := 0; i < len(buf); i += skip {
2464
+ buf[i] = 1
2465
+ }
2466
+ for i := 0; i < b.N; i++ {
2467
+ Index(buf, key)
2468
+ }
2469
+ })
2470
+ }
2471
+ }
2472
+
2473
+ func TestClone(t *testing.T) {
2474
+ var cloneTests = [][]byte{
2475
+ []byte(nil),
2476
+ []byte{},
2477
+ Clone([]byte{}),
2478
+ []byte(strings.Repeat("a", 42))[:0],
2479
+ []byte(strings.Repeat("a", 42))[:0:0],
2480
+ []byte("short"),
2481
+ []byte(strings.Repeat("a", 42)),
2482
+ }
2483
+ for _, input := range cloneTests {
2484
+ clone := Clone(input)
2485
+ if !Equal(clone, input) {
2486
+ t.Errorf("Clone(%q) = %q; want %q", input, clone, input)
2487
+ }
2488
+
2489
+ if input == nil && clone != nil {
2490
+ t.Errorf("Clone(%#v) return value should be equal to nil slice.", input)
2491
+ }
2492
+
2493
+ if input != nil && clone == nil {
2494
+ t.Errorf("Clone(%#v) return value should not be equal to nil slice.", input)
2495
+ }
2496
+
2497
+ if cap(input) != 0 && unsafe.SliceData(input) == unsafe.SliceData(clone) {
2498
+ t.Errorf("Clone(%q) return value should not reference inputs backing memory.", input)
2499
+ }
2500
+ }
2501
+ }
go/src/bytes/compare_test.go ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ . "bytes"
9
+ "fmt"
10
+ "testing"
11
+ )
12
+
13
+ var compareTests = []struct {
14
+ a, b []byte
15
+ i int
16
+ }{
17
+ {[]byte(""), []byte(""), 0},
18
+ {[]byte("a"), []byte(""), 1},
19
+ {[]byte(""), []byte("a"), -1},
20
+ {[]byte("abc"), []byte("abc"), 0},
21
+ {[]byte("abd"), []byte("abc"), 1},
22
+ {[]byte("abc"), []byte("abd"), -1},
23
+ {[]byte("ab"), []byte("abc"), -1},
24
+ {[]byte("abc"), []byte("ab"), 1},
25
+ {[]byte("x"), []byte("ab"), 1},
26
+ {[]byte("ab"), []byte("x"), -1},
27
+ {[]byte("x"), []byte("a"), 1},
28
+ {[]byte("b"), []byte("x"), -1},
29
+ // test runtime·memeq's chunked implementation
30
+ {[]byte("abcdefgh"), []byte("abcdefgh"), 0},
31
+ {[]byte("abcdefghi"), []byte("abcdefghi"), 0},
32
+ {[]byte("abcdefghi"), []byte("abcdefghj"), -1},
33
+ {[]byte("abcdefghj"), []byte("abcdefghi"), 1},
34
+ // nil tests
35
+ {nil, nil, 0},
36
+ {[]byte(""), nil, 0},
37
+ {nil, []byte(""), 0},
38
+ {[]byte("a"), nil, 1},
39
+ {nil, []byte("a"), -1},
40
+ }
41
+
42
+ func TestCompare(t *testing.T) {
43
+ for _, tt := range compareTests {
44
+ numShifts := 16
45
+ buffer := make([]byte, len(tt.b)+numShifts)
46
+ // vary the input alignment of tt.b
47
+ for offset := 0; offset <= numShifts; offset++ {
48
+ shiftedB := buffer[offset : len(tt.b)+offset]
49
+ copy(shiftedB, tt.b)
50
+ cmp := Compare(tt.a, shiftedB)
51
+ if cmp != tt.i {
52
+ t.Errorf(`Compare(%q, %q), offset %d = %v; want %v`, tt.a, tt.b, offset, cmp, tt.i)
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ func TestCompareIdenticalSlice(t *testing.T) {
59
+ var b = []byte("Hello Gophers!")
60
+ if Compare(b, b) != 0 {
61
+ t.Error("b != b")
62
+ }
63
+ if Compare(b, b[:1]) != 1 {
64
+ t.Error("b > b[:1] failed")
65
+ }
66
+ }
67
+
68
+ func TestCompareBytes(t *testing.T) {
69
+ lengths := make([]int, 0) // lengths to test in ascending order
70
+ for i := 0; i <= 128; i++ {
71
+ lengths = append(lengths, i)
72
+ }
73
+ lengths = append(lengths, 256, 512, 1024, 1333, 4095, 4096, 4097)
74
+
75
+ if !testing.Short() {
76
+ lengths = append(lengths, 65535, 65536, 65537, 99999)
77
+ }
78
+
79
+ n := lengths[len(lengths)-1]
80
+ a := make([]byte, n+1)
81
+ b := make([]byte, n+1)
82
+ for _, len := range lengths {
83
+ // randomish but deterministic data. No 0 or 255.
84
+ for i := 0; i < len; i++ {
85
+ a[i] = byte(1 + 31*i%254)
86
+ b[i] = byte(1 + 31*i%254)
87
+ }
88
+ // data past the end is different
89
+ for i := len; i <= n; i++ {
90
+ a[i] = 8
91
+ b[i] = 9
92
+ }
93
+ cmp := Compare(a[:len], b[:len])
94
+ if cmp != 0 {
95
+ t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
96
+ }
97
+ if len > 0 {
98
+ cmp = Compare(a[:len-1], b[:len])
99
+ if cmp != -1 {
100
+ t.Errorf(`CompareAshorter(%d) = %d`, len, cmp)
101
+ }
102
+ cmp = Compare(a[:len], b[:len-1])
103
+ if cmp != 1 {
104
+ t.Errorf(`CompareBshorter(%d) = %d`, len, cmp)
105
+ }
106
+ }
107
+ for k := 0; k < len; k++ {
108
+ b[k] = a[k] - 1
109
+ cmp = Compare(a[:len], b[:len])
110
+ if cmp != 1 {
111
+ t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
112
+ }
113
+ b[k] = a[k] + 1
114
+ cmp = Compare(a[:len], b[:len])
115
+ if cmp != -1 {
116
+ t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)
117
+ }
118
+ b[k] = a[k]
119
+ }
120
+ }
121
+ }
122
+
123
+ func TestEndianBaseCompare(t *testing.T) {
124
+ // This test compares byte slices that are almost identical, except one
125
+ // difference that for some j, a[j]>b[j] and a[j+1]<b[j+1]. If the implementation
126
+ // compares large chunks with wrong endianness, it gets wrong result.
127
+ // no vector register is larger than 512 bytes for now
128
+ const maxLength = 512
129
+ a := make([]byte, maxLength)
130
+ b := make([]byte, maxLength)
131
+ // randomish but deterministic data. No 0 or 255.
132
+ for i := 0; i < maxLength; i++ {
133
+ a[i] = byte(1 + 31*i%254)
134
+ b[i] = byte(1 + 31*i%254)
135
+ }
136
+ for i := 2; i <= maxLength; i <<= 1 {
137
+ for j := 0; j < i-1; j++ {
138
+ a[j] = b[j] - 1
139
+ a[j+1] = b[j+1] + 1
140
+ cmp := Compare(a[:i], b[:i])
141
+ if cmp != -1 {
142
+ t.Errorf(`CompareBbigger(%d,%d) = %d`, i, j, cmp)
143
+ }
144
+ a[j] = b[j] + 1
145
+ a[j+1] = b[j+1] - 1
146
+ cmp = Compare(a[:i], b[:i])
147
+ if cmp != 1 {
148
+ t.Errorf(`CompareAbigger(%d,%d) = %d`, i, j, cmp)
149
+ }
150
+ a[j] = b[j]
151
+ a[j+1] = b[j+1]
152
+ }
153
+ }
154
+ }
155
+
156
+ func BenchmarkCompareBytesEqual(b *testing.B) {
157
+ b1 := []byte("Hello Gophers!")
158
+ b2 := []byte("Hello Gophers!")
159
+ for i := 0; i < b.N; i++ {
160
+ if Compare(b1, b2) != 0 {
161
+ b.Fatal("b1 != b2")
162
+ }
163
+ }
164
+ }
165
+
166
+ func BenchmarkCompareBytesToNil(b *testing.B) {
167
+ b1 := []byte("Hello Gophers!")
168
+ var b2 []byte
169
+ for i := 0; i < b.N; i++ {
170
+ if Compare(b1, b2) != 1 {
171
+ b.Fatal("b1 > b2 failed")
172
+ }
173
+ }
174
+ }
175
+
176
+ func BenchmarkCompareBytesEmpty(b *testing.B) {
177
+ b1 := []byte("")
178
+ b2 := b1
179
+ for i := 0; i < b.N; i++ {
180
+ if Compare(b1, b2) != 0 {
181
+ b.Fatal("b1 != b2")
182
+ }
183
+ }
184
+ }
185
+
186
+ func BenchmarkCompareBytesIdentical(b *testing.B) {
187
+ b1 := []byte("Hello Gophers!")
188
+ b2 := b1
189
+ for i := 0; i < b.N; i++ {
190
+ if Compare(b1, b2) != 0 {
191
+ b.Fatal("b1 != b2")
192
+ }
193
+ }
194
+ }
195
+
196
+ func BenchmarkCompareBytesSameLength(b *testing.B) {
197
+ b1 := []byte("Hello Gophers!")
198
+ b2 := []byte("Hello, Gophers")
199
+ for i := 0; i < b.N; i++ {
200
+ if Compare(b1, b2) != -1 {
201
+ b.Fatal("b1 < b2 failed")
202
+ }
203
+ }
204
+ }
205
+
206
+ func BenchmarkCompareBytesDifferentLength(b *testing.B) {
207
+ b1 := []byte("Hello Gophers!")
208
+ b2 := []byte("Hello, Gophers!")
209
+ for i := 0; i < b.N; i++ {
210
+ if Compare(b1, b2) != -1 {
211
+ b.Fatal("b1 < b2 failed")
212
+ }
213
+ }
214
+ }
215
+
216
+ func benchmarkCompareBytesBigUnaligned(b *testing.B, offset int) {
217
+ b.StopTimer()
218
+ b1 := make([]byte, 0, 1<<20)
219
+ for len(b1) < 1<<20 {
220
+ b1 = append(b1, "Hello Gophers!"...)
221
+ }
222
+ b2 := append([]byte("12345678")[:offset], b1...)
223
+ b.StartTimer()
224
+ for j := 0; j < b.N; j++ {
225
+ if Compare(b1, b2[offset:]) != 0 {
226
+ b.Fatal("b1 != b2")
227
+ }
228
+ }
229
+ b.SetBytes(int64(len(b1)))
230
+ }
231
+
232
+ func BenchmarkCompareBytesBigUnaligned(b *testing.B) {
233
+ for i := 1; i < 8; i++ {
234
+ b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) {
235
+ benchmarkCompareBytesBigUnaligned(b, i)
236
+ })
237
+ }
238
+ }
239
+
240
+ func benchmarkCompareBytesBigBothUnaligned(b *testing.B, offset int) {
241
+ b.StopTimer()
242
+ pattern := []byte("Hello Gophers!")
243
+ b1 := make([]byte, 0, 1<<20+len(pattern))
244
+ for len(b1) < 1<<20 {
245
+ b1 = append(b1, pattern...)
246
+ }
247
+ b2 := make([]byte, len(b1))
248
+ copy(b2, b1)
249
+ b.StartTimer()
250
+ for j := 0; j < b.N; j++ {
251
+ if Compare(b1[offset:], b2[offset:]) != 0 {
252
+ b.Fatal("b1 != b2")
253
+ }
254
+ }
255
+ b.SetBytes(int64(len(b1[offset:])))
256
+ }
257
+
258
+ func BenchmarkCompareBytesBigBothUnaligned(b *testing.B) {
259
+ for i := 0; i < 8; i++ {
260
+ b.Run(fmt.Sprintf("offset=%d", i), func(b *testing.B) {
261
+ benchmarkCompareBytesBigBothUnaligned(b, i)
262
+ })
263
+ }
264
+ }
265
+
266
+ func BenchmarkCompareBytesBig(b *testing.B) {
267
+ b.StopTimer()
268
+ b1 := make([]byte, 0, 1<<20)
269
+ for len(b1) < 1<<20 {
270
+ b1 = append(b1, "Hello Gophers!"...)
271
+ }
272
+ b2 := append([]byte{}, b1...)
273
+ b.StartTimer()
274
+ for i := 0; i < b.N; i++ {
275
+ if Compare(b1, b2) != 0 {
276
+ b.Fatal("b1 != b2")
277
+ }
278
+ }
279
+ b.SetBytes(int64(len(b1)))
280
+ }
281
+
282
+ func BenchmarkCompareBytesBigIdentical(b *testing.B) {
283
+ b.StopTimer()
284
+ b1 := make([]byte, 0, 1<<20)
285
+ for len(b1) < 1<<20 {
286
+ b1 = append(b1, "Hello Gophers!"...)
287
+ }
288
+ b2 := b1
289
+ b.StartTimer()
290
+ for i := 0; i < b.N; i++ {
291
+ if Compare(b1, b2) != 0 {
292
+ b.Fatal("b1 != b2")
293
+ }
294
+ }
295
+ b.SetBytes(int64(len(b1)))
296
+ }
go/src/bytes/example_test.go ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ "bytes"
9
+ "encoding/base64"
10
+ "fmt"
11
+ "io"
12
+ "os"
13
+ "slices"
14
+ "strconv"
15
+ "unicode"
16
+ )
17
+
18
+ func ExampleBuffer() {
19
+ var b bytes.Buffer // A Buffer needs no initialization.
20
+ b.Write([]byte("Hello "))
21
+ fmt.Fprintf(&b, "world!")
22
+ b.WriteTo(os.Stdout)
23
+ // Output: Hello world!
24
+ }
25
+
26
+ func ExampleBuffer_reader() {
27
+ // A Buffer can turn a string or a []byte into an io.Reader.
28
+ buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
29
+ dec := base64.NewDecoder(base64.StdEncoding, buf)
30
+ io.Copy(os.Stdout, dec)
31
+ // Output: Gophers rule!
32
+ }
33
+
34
+ func ExampleBuffer_Bytes() {
35
+ buf := bytes.Buffer{}
36
+ buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'})
37
+ os.Stdout.Write(buf.Bytes())
38
+ // Output: hello world
39
+ }
40
+
41
+ func ExampleBuffer_AvailableBuffer() {
42
+ var buf bytes.Buffer
43
+ for i := 0; i < 4; i++ {
44
+ b := buf.AvailableBuffer()
45
+ b = strconv.AppendInt(b, int64(i), 10)
46
+ b = append(b, ' ')
47
+ buf.Write(b)
48
+ }
49
+ os.Stdout.Write(buf.Bytes())
50
+ // Output: 0 1 2 3
51
+ }
52
+
53
+ func ExampleBuffer_Cap() {
54
+ buf1 := bytes.NewBuffer(make([]byte, 10))
55
+ buf2 := bytes.NewBuffer(make([]byte, 0, 10))
56
+ fmt.Println(buf1.Cap())
57
+ fmt.Println(buf2.Cap())
58
+ // Output:
59
+ // 10
60
+ // 10
61
+ }
62
+
63
+ func ExampleBuffer_Grow() {
64
+ var b bytes.Buffer
65
+ b.Grow(64)
66
+ bb := b.Bytes()
67
+ b.Write([]byte("64 bytes or fewer"))
68
+ fmt.Printf("%q", bb[:b.Len()])
69
+ // Output: "64 bytes or fewer"
70
+ }
71
+
72
+ func ExampleBuffer_Len() {
73
+ var b bytes.Buffer
74
+ b.Grow(64)
75
+ b.Write([]byte("abcde"))
76
+ fmt.Printf("%d", b.Len())
77
+ // Output: 5
78
+ }
79
+
80
+ func ExampleBuffer_Next() {
81
+ var b bytes.Buffer
82
+ b.Grow(64)
83
+ b.Write([]byte("abcde"))
84
+ fmt.Printf("%s\n", b.Next(2))
85
+ fmt.Printf("%s\n", b.Next(2))
86
+ fmt.Printf("%s", b.Next(2))
87
+ // Output:
88
+ // ab
89
+ // cd
90
+ // e
91
+ }
92
+
93
+ func ExampleBuffer_Read() {
94
+ var b bytes.Buffer
95
+ b.Grow(64)
96
+ b.Write([]byte("abcde"))
97
+ rdbuf := make([]byte, 1)
98
+ n, err := b.Read(rdbuf)
99
+ if err != nil {
100
+ panic(err)
101
+ }
102
+ fmt.Println(n)
103
+ fmt.Println(b.String())
104
+ fmt.Println(string(rdbuf))
105
+ // Output:
106
+ // 1
107
+ // bcde
108
+ // a
109
+ }
110
+
111
+ func ExampleBuffer_ReadByte() {
112
+ var b bytes.Buffer
113
+ b.Grow(64)
114
+ b.Write([]byte("abcde"))
115
+ c, err := b.ReadByte()
116
+ if err != nil {
117
+ panic(err)
118
+ }
119
+ fmt.Println(c)
120
+ fmt.Println(b.String())
121
+ // Output:
122
+ // 97
123
+ // bcde
124
+ }
125
+
126
+ func ExampleClone() {
127
+ b := []byte("abc")
128
+ clone := bytes.Clone(b)
129
+ fmt.Printf("%s\n", clone)
130
+ clone[0] = 'd'
131
+ fmt.Printf("%s\n", b)
132
+ fmt.Printf("%s\n", clone)
133
+ // Output:
134
+ // abc
135
+ // abc
136
+ // dbc
137
+ }
138
+
139
+ func ExampleCompare() {
140
+ // Interpret Compare's result by comparing it to zero.
141
+ var a, b []byte
142
+ if bytes.Compare(a, b) < 0 {
143
+ // a less b
144
+ }
145
+ if bytes.Compare(a, b) <= 0 {
146
+ // a less or equal b
147
+ }
148
+ if bytes.Compare(a, b) > 0 {
149
+ // a greater b
150
+ }
151
+ if bytes.Compare(a, b) >= 0 {
152
+ // a greater or equal b
153
+ }
154
+
155
+ // Prefer Equal to Compare for equality comparisons.
156
+ if bytes.Equal(a, b) {
157
+ // a equal b
158
+ }
159
+ if !bytes.Equal(a, b) {
160
+ // a not equal b
161
+ }
162
+ }
163
+
164
+ func ExampleCompare_search() {
165
+ // Binary search to find a matching byte slice.
166
+ var needle []byte
167
+ var haystack [][]byte // Assume sorted
168
+ _, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare)
169
+ if found {
170
+ // Found it!
171
+ }
172
+ }
173
+
174
+ func ExampleContains() {
175
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
176
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
177
+ fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
178
+ fmt.Println(bytes.Contains([]byte(""), []byte("")))
179
+ // Output:
180
+ // true
181
+ // false
182
+ // true
183
+ // true
184
+ }
185
+
186
+ func ExampleContainsAny() {
187
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
188
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
189
+ fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
190
+ fmt.Println(bytes.ContainsAny([]byte(""), ""))
191
+ // Output:
192
+ // true
193
+ // true
194
+ // false
195
+ // false
196
+ }
197
+
198
+ func ExampleContainsRune() {
199
+ fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
200
+ fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
201
+ fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
202
+ fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
203
+ fmt.Println(bytes.ContainsRune([]byte(""), '@'))
204
+ // Output:
205
+ // true
206
+ // false
207
+ // true
208
+ // true
209
+ // false
210
+ }
211
+
212
+ func ExampleContainsFunc() {
213
+ f := func(r rune) bool {
214
+ return r >= 'a' && r <= 'z'
215
+ }
216
+ fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
217
+ fmt.Println(bytes.ContainsFunc([]byte("World"), f))
218
+ // Output:
219
+ // false
220
+ // true
221
+ }
222
+
223
+ func ExampleCount() {
224
+ fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
225
+ fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune
226
+ // Output:
227
+ // 3
228
+ // 5
229
+ }
230
+
231
+ func ExampleCut() {
232
+ show := func(s, sep string) {
233
+ before, after, found := bytes.Cut([]byte(s), []byte(sep))
234
+ fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
235
+ }
236
+ show("Gopher", "Go")
237
+ show("Gopher", "ph")
238
+ show("Gopher", "er")
239
+ show("Gopher", "Badger")
240
+ // Output:
241
+ // Cut("Gopher", "Go") = "", "pher", true
242
+ // Cut("Gopher", "ph") = "Go", "er", true
243
+ // Cut("Gopher", "er") = "Goph", "", true
244
+ // Cut("Gopher", "Badger") = "Gopher", "", false
245
+ }
246
+
247
+ func ExampleCutPrefix() {
248
+ show := func(s, prefix string) {
249
+ after, found := bytes.CutPrefix([]byte(s), []byte(prefix))
250
+ fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
251
+ }
252
+ show("Gopher", "Go")
253
+ show("Gopher", "ph")
254
+ // Output:
255
+ // CutPrefix("Gopher", "Go") = "pher", true
256
+ // CutPrefix("Gopher", "ph") = "Gopher", false
257
+ }
258
+
259
+ func ExampleCutSuffix() {
260
+ show := func(s, suffix string) {
261
+ before, found := bytes.CutSuffix([]byte(s), []byte(suffix))
262
+ fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
263
+ }
264
+ show("Gopher", "Go")
265
+ show("Gopher", "er")
266
+ // Output:
267
+ // CutSuffix("Gopher", "Go") = "Gopher", false
268
+ // CutSuffix("Gopher", "er") = "Goph", true
269
+ }
270
+
271
+ func ExampleEqual() {
272
+ fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
273
+ fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
274
+ // Output:
275
+ // true
276
+ // false
277
+ }
278
+
279
+ func ExampleEqualFold() {
280
+ fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
281
+ // Output: true
282
+ }
283
+
284
+ func ExampleFields() {
285
+ fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz ")))
286
+ // Output: Fields are: ["foo" "bar" "baz"]
287
+ }
288
+
289
+ func ExampleFieldsFunc() {
290
+ f := func(c rune) bool {
291
+ return !unicode.IsLetter(c) && !unicode.IsNumber(c)
292
+ }
293
+ fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f))
294
+ // Output: Fields are: ["foo1" "bar2" "baz3"]
295
+ }
296
+
297
+ func ExampleHasPrefix() {
298
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
299
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
300
+ fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
301
+ // Output:
302
+ // true
303
+ // false
304
+ // true
305
+ }
306
+
307
+ func ExampleHasSuffix() {
308
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
309
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
310
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
311
+ fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
312
+ // Output:
313
+ // true
314
+ // false
315
+ // false
316
+ // true
317
+ }
318
+
319
+ func ExampleIndex() {
320
+ fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
321
+ fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
322
+ // Output:
323
+ // 4
324
+ // -1
325
+ }
326
+
327
+ func ExampleIndexByte() {
328
+ fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
329
+ fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
330
+ // Output:
331
+ // 4
332
+ // -1
333
+ }
334
+
335
+ func ExampleIndexFunc() {
336
+ f := func(c rune) bool {
337
+ return unicode.Is(unicode.Han, c)
338
+ }
339
+ fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
340
+ fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
341
+ // Output:
342
+ // 7
343
+ // -1
344
+ }
345
+
346
+ func ExampleIndexAny() {
347
+ fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
348
+ fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
349
+ // Output:
350
+ // 2
351
+ // -1
352
+ }
353
+
354
+ func ExampleIndexRune() {
355
+ fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
356
+ fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
357
+ // Output:
358
+ // 4
359
+ // -1
360
+ }
361
+
362
+ func ExampleJoin() {
363
+ s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
364
+ fmt.Printf("%s", bytes.Join(s, []byte(", ")))
365
+ // Output: foo, bar, baz
366
+ }
367
+
368
+ func ExampleLastIndex() {
369
+ fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
370
+ fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
371
+ fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
372
+ // Output:
373
+ // 0
374
+ // 3
375
+ // -1
376
+ }
377
+
378
+ func ExampleLastIndexAny() {
379
+ fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
380
+ fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
381
+ fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
382
+ // Output:
383
+ // 5
384
+ // 3
385
+ // -1
386
+ }
387
+
388
+ func ExampleLastIndexByte() {
389
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
390
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
391
+ fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
392
+ // Output:
393
+ // 3
394
+ // 8
395
+ // -1
396
+ }
397
+
398
+ func ExampleLastIndexFunc() {
399
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
400
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
401
+ fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
402
+ // Output:
403
+ // 8
404
+ // 9
405
+ // -1
406
+ }
407
+
408
+ func ExampleMap() {
409
+ rot13 := func(r rune) rune {
410
+ switch {
411
+ case r >= 'A' && r <= 'Z':
412
+ return 'A' + (r-'A'+13)%26
413
+ case r >= 'a' && r <= 'z':
414
+ return 'a' + (r-'a'+13)%26
415
+ }
416
+ return r
417
+ }
418
+ fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
419
+ // Output:
420
+ // 'Gjnf oevyyvt naq gur fyvgul tbcure...
421
+ }
422
+
423
+ func ExampleReader_Len() {
424
+ fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
425
+ fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
426
+ // Output:
427
+ // 3
428
+ // 16
429
+ }
430
+
431
+ func ExampleRepeat() {
432
+ fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
433
+ // Output: banana
434
+ }
435
+
436
+ func ExampleReplace() {
437
+ fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
438
+ fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
439
+ // Output:
440
+ // oinky oinky oink
441
+ // moo moo moo
442
+ }
443
+
444
+ func ExampleReplaceAll() {
445
+ fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
446
+ // Output:
447
+ // moo moo moo
448
+ }
449
+
450
+ func ExampleRunes() {
451
+ rs := bytes.Runes([]byte("go gopher"))
452
+ for _, r := range rs {
453
+ fmt.Printf("%#U\n", r)
454
+ }
455
+ // Output:
456
+ // U+0067 'g'
457
+ // U+006F 'o'
458
+ // U+0020 ' '
459
+ // U+0067 'g'
460
+ // U+006F 'o'
461
+ // U+0070 'p'
462
+ // U+0068 'h'
463
+ // U+0065 'e'
464
+ // U+0072 'r'
465
+ }
466
+
467
+ func ExampleSplit() {
468
+ fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
469
+ fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
470
+ fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
471
+ fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
472
+ // Output:
473
+ // ["a" "b" "c"]
474
+ // ["" "man " "plan " "canal panama"]
475
+ // [" " "x" "y" "z" " "]
476
+ // [""]
477
+ }
478
+
479
+ func ExampleSplitN() {
480
+ fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
481
+ z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
482
+ fmt.Printf("%q (nil = %v)\n", z, z == nil)
483
+ // Output:
484
+ // ["a" "b,c"]
485
+ // [] (nil = true)
486
+ }
487
+
488
+ func ExampleSplitAfter() {
489
+ fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
490
+ // Output: ["a," "b," "c"]
491
+ }
492
+
493
+ func ExampleSplitAfterN() {
494
+ fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
495
+ // Output: ["a," "b,c"]
496
+ }
497
+
498
+ func ExampleTitle() {
499
+ fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
500
+ // Output: Her Royal Highness
501
+ }
502
+
503
+ func ExampleToTitle() {
504
+ fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
505
+ fmt.Printf("%s\n", bytes.ToTitle([]byte("брат")))
506
+ // Output:
507
+ // LOUD NOISES
508
+ // БРАТ
509
+ }
510
+
511
+ func ExampleToTitleSpecial() {
512
+ str := []byte("ahoj vývojári golang")
513
+ totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
514
+ fmt.Println("Original : " + string(str))
515
+ fmt.Println("ToTitle : " + string(totitle))
516
+ // Output:
517
+ // Original : ahoj vývojári golang
518
+ // ToTitle : AHOJ VÝVOJÁRİ GOLANG
519
+ }
520
+
521
+ func ExampleToValidUTF8() {
522
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
523
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
524
+ fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
525
+ // Output:
526
+ // abc
527
+ // abc
528
+ // abc
529
+ }
530
+
531
+ func ExampleTrim() {
532
+ fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
533
+ // Output: ["Achtung! Achtung"]
534
+ }
535
+
536
+ func ExampleTrimFunc() {
537
+ fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
538
+ fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
539
+ fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
540
+ fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
541
+ // Output:
542
+ // -gopher!
543
+ // "go-gopher!"
544
+ // go-gopher
545
+ // go-gopher!
546
+ }
547
+
548
+ func ExampleTrimLeft() {
549
+ fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
550
+ // Output:
551
+ // gopher8257
552
+ }
553
+
554
+ func ExampleTrimLeftFunc() {
555
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
556
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
557
+ fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
558
+ // Output:
559
+ // -gopher
560
+ // go-gopher!
561
+ // go-gopher!567
562
+ }
563
+
564
+ func ExampleTrimPrefix() {
565
+ var b = []byte("Goodbye,, world!")
566
+ b = bytes.TrimPrefix(b, []byte("Goodbye,"))
567
+ b = bytes.TrimPrefix(b, []byte("See ya,"))
568
+ fmt.Printf("Hello%s", b)
569
+ // Output: Hello, world!
570
+ }
571
+
572
+ func ExampleTrimSpace() {
573
+ fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
574
+ // Output: a lone gopher
575
+ }
576
+
577
+ func ExampleTrimSuffix() {
578
+ var b = []byte("Hello, goodbye, etc!")
579
+ b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
580
+ b = bytes.TrimSuffix(b, []byte("gopher"))
581
+ b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
582
+ os.Stdout.Write(b)
583
+ // Output: Hello, world!
584
+ }
585
+
586
+ func ExampleTrimRight() {
587
+ fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
588
+ // Output:
589
+ // 453gopher
590
+ }
591
+
592
+ func ExampleTrimRightFunc() {
593
+ fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
594
+ fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
595
+ fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
596
+ // Output:
597
+ // go-
598
+ // go-gopher
599
+ // 1234go-gopher!
600
+ }
601
+
602
+ func ExampleToLower() {
603
+ fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
604
+ // Output: gopher
605
+ }
606
+
607
+ func ExampleToLowerSpecial() {
608
+ str := []byte("AHOJ VÝVOJÁRİ GOLANG")
609
+ totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
610
+ fmt.Println("Original : " + string(str))
611
+ fmt.Println("ToLower : " + string(totitle))
612
+ // Output:
613
+ // Original : AHOJ VÝVOJÁRİ GOLANG
614
+ // ToLower : ahoj vývojári golang
615
+ }
616
+
617
+ func ExampleToUpper() {
618
+ fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
619
+ // Output: GOPHER
620
+ }
621
+
622
+ func ExampleToUpperSpecial() {
623
+ str := []byte("ahoj vývojári golang")
624
+ totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
625
+ fmt.Println("Original : " + string(str))
626
+ fmt.Println("ToUpper : " + string(totitle))
627
+ // Output:
628
+ // Original : ahoj vývojári golang
629
+ // ToUpper : AHOJ VÝVOJÁRİ GOLANG
630
+ }
631
+
632
+ func ExampleLines() {
633
+ text := []byte("Hello\nWorld\nGo Programming\n")
634
+ for line := range bytes.Lines(text) {
635
+ fmt.Printf("%q\n", line)
636
+ }
637
+
638
+ // Output:
639
+ // "Hello\n"
640
+ // "World\n"
641
+ // "Go Programming\n"
642
+ }
643
+
644
+ func ExampleSplitSeq() {
645
+ s := []byte("a,b,c,d")
646
+ for part := range bytes.SplitSeq(s, []byte(",")) {
647
+ fmt.Printf("%q\n", part)
648
+ }
649
+
650
+ // Output:
651
+ // "a"
652
+ // "b"
653
+ // "c"
654
+ // "d"
655
+ }
656
+
657
+ func ExampleSplitAfterSeq() {
658
+ s := []byte("a,b,c,d")
659
+ for part := range bytes.SplitAfterSeq(s, []byte(",")) {
660
+ fmt.Printf("%q\n", part)
661
+ }
662
+
663
+ // Output:
664
+ // "a,"
665
+ // "b,"
666
+ // "c,"
667
+ // "d"
668
+ }
669
+
670
+ func ExampleFieldsSeq() {
671
+ text := []byte("The quick brown fox")
672
+ fmt.Println("Split byte slice into fields:")
673
+ for word := range bytes.FieldsSeq(text) {
674
+ fmt.Printf("%q\n", word)
675
+ }
676
+
677
+ textWithSpaces := []byte(" lots of spaces ")
678
+ fmt.Println("\nSplit byte slice with multiple spaces:")
679
+ for word := range bytes.FieldsSeq(textWithSpaces) {
680
+ fmt.Printf("%q\n", word)
681
+ }
682
+
683
+ // Output:
684
+ // Split byte slice into fields:
685
+ // "The"
686
+ // "quick"
687
+ // "brown"
688
+ // "fox"
689
+ //
690
+ // Split byte slice with multiple spaces:
691
+ // "lots"
692
+ // "of"
693
+ // "spaces"
694
+ }
695
+
696
+ func ExampleFieldsFuncSeq() {
697
+ text := []byte("The quick brown fox")
698
+ fmt.Println("Split on whitespace(similar to FieldsSeq):")
699
+ for word := range bytes.FieldsFuncSeq(text, unicode.IsSpace) {
700
+ fmt.Printf("%q\n", word)
701
+ }
702
+
703
+ mixedText := []byte("abc123def456ghi")
704
+ fmt.Println("\nSplit on digits:")
705
+ for word := range bytes.FieldsFuncSeq(mixedText, unicode.IsDigit) {
706
+ fmt.Printf("%q\n", word)
707
+ }
708
+
709
+ // Output:
710
+ // Split on whitespace(similar to FieldsSeq):
711
+ // "The"
712
+ // "quick"
713
+ // "brown"
714
+ // "fox"
715
+ //
716
+ // Split on digits:
717
+ // "abc"
718
+ // "def"
719
+ // "ghi"
720
+ }
go/src/bytes/export_test.go ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes
6
+
7
+ // Export func for testing
8
+ var IndexBytePortable = indexBytePortable
go/src/bytes/iter.go ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes
6
+
7
+ import (
8
+ "iter"
9
+ "unicode"
10
+ "unicode/utf8"
11
+ )
12
+
13
+ // Lines returns an iterator over the newline-terminated lines in the byte slice s.
14
+ // The lines yielded by the iterator include their terminating newlines.
15
+ // If s is empty, the iterator yields no lines at all.
16
+ // If s does not end in a newline, the final yielded line will not end in a newline.
17
+ // It returns a single-use iterator.
18
+ func Lines(s []byte) iter.Seq[[]byte] {
19
+ return func(yield func([]byte) bool) {
20
+ for len(s) > 0 {
21
+ var line []byte
22
+ if i := IndexByte(s, '\n'); i >= 0 {
23
+ line, s = s[:i+1], s[i+1:]
24
+ } else {
25
+ line, s = s, nil
26
+ }
27
+ if !yield(line[:len(line):len(line)]) {
28
+ return
29
+ }
30
+ }
31
+ }
32
+ }
33
+
34
+ // splitSeq is SplitSeq or SplitAfterSeq, configured by how many
35
+ // bytes of sep to include in the results (none or all).
36
+ func splitSeq(s, sep []byte, sepSave int) iter.Seq[[]byte] {
37
+ return func(yield func([]byte) bool) {
38
+ if len(sep) == 0 {
39
+ for len(s) > 0 {
40
+ _, size := utf8.DecodeRune(s)
41
+ if !yield(s[:size:size]) {
42
+ return
43
+ }
44
+ s = s[size:]
45
+ }
46
+ return
47
+ }
48
+ for {
49
+ i := Index(s, sep)
50
+ if i < 0 {
51
+ break
52
+ }
53
+ frag := s[:i+sepSave]
54
+ if !yield(frag[:len(frag):len(frag)]) {
55
+ return
56
+ }
57
+ s = s[i+len(sep):]
58
+ }
59
+ yield(s[:len(s):len(s)])
60
+ }
61
+ }
62
+
63
+ // SplitSeq returns an iterator over all subslices of s separated by sep.
64
+ // The iterator yields the same subslices that would be returned by [Split](s, sep),
65
+ // but without constructing a new slice containing the subslices.
66
+ // It returns a single-use iterator.
67
+ func SplitSeq(s, sep []byte) iter.Seq[[]byte] {
68
+ return splitSeq(s, sep, 0)
69
+ }
70
+
71
+ // SplitAfterSeq returns an iterator over subslices of s split after each instance of sep.
72
+ // The iterator yields the same subslices that would be returned by [SplitAfter](s, sep),
73
+ // but without constructing a new slice containing the subslices.
74
+ // It returns a single-use iterator.
75
+ func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte] {
76
+ return splitSeq(s, sep, len(sep))
77
+ }
78
+
79
+ // FieldsSeq returns an iterator over subslices of s split around runs of
80
+ // whitespace characters, as defined by [unicode.IsSpace].
81
+ // The iterator yields the same subslices that would be returned by [Fields](s),
82
+ // but without constructing a new slice containing the subslices.
83
+ func FieldsSeq(s []byte) iter.Seq[[]byte] {
84
+ return func(yield func([]byte) bool) {
85
+ start := -1
86
+ for i := 0; i < len(s); {
87
+ size := 1
88
+ r := rune(s[i])
89
+ isSpace := asciiSpace[s[i]] != 0
90
+ if r >= utf8.RuneSelf {
91
+ r, size = utf8.DecodeRune(s[i:])
92
+ isSpace = unicode.IsSpace(r)
93
+ }
94
+ if isSpace {
95
+ if start >= 0 {
96
+ if !yield(s[start:i:i]) {
97
+ return
98
+ }
99
+ start = -1
100
+ }
101
+ } else if start < 0 {
102
+ start = i
103
+ }
104
+ i += size
105
+ }
106
+ if start >= 0 {
107
+ yield(s[start:len(s):len(s)])
108
+ }
109
+ }
110
+ }
111
+
112
+ // FieldsFuncSeq returns an iterator over subslices of s split around runs of
113
+ // Unicode code points satisfying f(c).
114
+ // The iterator yields the same subslices that would be returned by [FieldsFunc](s),
115
+ // but without constructing a new slice containing the subslices.
116
+ func FieldsFuncSeq(s []byte, f func(rune) bool) iter.Seq[[]byte] {
117
+ return func(yield func([]byte) bool) {
118
+ start := -1
119
+ for i := 0; i < len(s); {
120
+ r, size := utf8.DecodeRune(s[i:])
121
+ if f(r) {
122
+ if start >= 0 {
123
+ if !yield(s[start:i:i]) {
124
+ return
125
+ }
126
+ start = -1
127
+ }
128
+ } else if start < 0 {
129
+ start = i
130
+ }
131
+ i += size
132
+ }
133
+ if start >= 0 {
134
+ yield(s[start:len(s):len(s)])
135
+ }
136
+ }
137
+ }
go/src/bytes/iter_test.go ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ . "bytes"
9
+ "testing"
10
+ )
11
+
12
+ func BenchmarkSplitSeqEmptySeparator(b *testing.B) {
13
+ for range b.N {
14
+ for range SplitSeq(benchInputHard, nil) {
15
+ }
16
+ }
17
+ }
18
+
19
+ func BenchmarkSplitSeqSingleByteSeparator(b *testing.B) {
20
+ sep := []byte("/")
21
+ for range b.N {
22
+ for range SplitSeq(benchInputHard, sep) {
23
+ }
24
+ }
25
+ }
26
+
27
+ func BenchmarkSplitSeqMultiByteSeparator(b *testing.B) {
28
+ sep := []byte("hello")
29
+ for range b.N {
30
+ for range SplitSeq(benchInputHard, sep) {
31
+ }
32
+ }
33
+ }
34
+
35
+ func BenchmarkSplitAfterSeqEmptySeparator(b *testing.B) {
36
+ for range b.N {
37
+ for range SplitAfterSeq(benchInputHard, nil) {
38
+ }
39
+ }
40
+ }
41
+
42
+ func BenchmarkSplitAfterSeqSingleByteSeparator(b *testing.B) {
43
+ sep := []byte("/")
44
+ for range b.N {
45
+ for range SplitAfterSeq(benchInputHard, sep) {
46
+ }
47
+ }
48
+ }
49
+
50
+ func BenchmarkSplitAfterSeqMultiByteSeparator(b *testing.B) {
51
+ sep := []byte("hello")
52
+ for range b.N {
53
+ for range SplitAfterSeq(benchInputHard, sep) {
54
+ }
55
+ }
56
+ }
go/src/bytes/reader.go ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes
6
+
7
+ import (
8
+ "errors"
9
+ "io"
10
+ "unicode/utf8"
11
+ )
12
+
13
+ // A Reader implements the [io.Reader], [io.ReaderAt], [io.WriterTo], [io.Seeker],
14
+ // [io.ByteScanner], and [io.RuneScanner] interfaces by reading from
15
+ // a byte slice.
16
+ // Unlike a [Buffer], a Reader is read-only and supports seeking.
17
+ // The zero value for Reader operates like a Reader of an empty slice.
18
+ type Reader struct {
19
+ s []byte
20
+ i int64 // current reading index
21
+ prevRune int // index of previous rune; or < 0
22
+ }
23
+
24
+ // Len returns the number of bytes of the unread portion of the
25
+ // slice.
26
+ func (r *Reader) Len() int {
27
+ if r.i >= int64(len(r.s)) {
28
+ return 0
29
+ }
30
+ return int(int64(len(r.s)) - r.i)
31
+ }
32
+
33
+ // Size returns the original length of the underlying byte slice.
34
+ // Size is the number of bytes available for reading via [Reader.ReadAt].
35
+ // The result is unaffected by any method calls except [Reader.Reset].
36
+ func (r *Reader) Size() int64 { return int64(len(r.s)) }
37
+
38
+ // Read implements the [io.Reader] interface.
39
+ func (r *Reader) Read(b []byte) (n int, err error) {
40
+ if r.i >= int64(len(r.s)) {
41
+ return 0, io.EOF
42
+ }
43
+ r.prevRune = -1
44
+ n = copy(b, r.s[r.i:])
45
+ r.i += int64(n)
46
+ return
47
+ }
48
+
49
+ // ReadAt implements the [io.ReaderAt] interface.
50
+ func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) {
51
+ // cannot modify state - see io.ReaderAt
52
+ if off < 0 {
53
+ return 0, errors.New("bytes.Reader.ReadAt: negative offset")
54
+ }
55
+ if off >= int64(len(r.s)) {
56
+ return 0, io.EOF
57
+ }
58
+ n = copy(b, r.s[off:])
59
+ if n < len(b) {
60
+ err = io.EOF
61
+ }
62
+ return
63
+ }
64
+
65
+ // ReadByte implements the [io.ByteReader] interface.
66
+ func (r *Reader) ReadByte() (byte, error) {
67
+ r.prevRune = -1
68
+ if r.i >= int64(len(r.s)) {
69
+ return 0, io.EOF
70
+ }
71
+ b := r.s[r.i]
72
+ r.i++
73
+ return b, nil
74
+ }
75
+
76
+ // UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface.
77
+ func (r *Reader) UnreadByte() error {
78
+ if r.i <= 0 {
79
+ return errors.New("bytes.Reader.UnreadByte: at beginning of slice")
80
+ }
81
+ r.prevRune = -1
82
+ r.i--
83
+ return nil
84
+ }
85
+
86
+ // ReadRune implements the [io.RuneReader] interface.
87
+ func (r *Reader) ReadRune() (ch rune, size int, err error) {
88
+ if r.i >= int64(len(r.s)) {
89
+ r.prevRune = -1
90
+ return 0, 0, io.EOF
91
+ }
92
+ r.prevRune = int(r.i)
93
+ if c := r.s[r.i]; c < utf8.RuneSelf {
94
+ r.i++
95
+ return rune(c), 1, nil
96
+ }
97
+ ch, size = utf8.DecodeRune(r.s[r.i:])
98
+ r.i += int64(size)
99
+ return
100
+ }
101
+
102
+ // UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface.
103
+ func (r *Reader) UnreadRune() error {
104
+ if r.i <= 0 {
105
+ return errors.New("bytes.Reader.UnreadRune: at beginning of slice")
106
+ }
107
+ if r.prevRune < 0 {
108
+ return errors.New("bytes.Reader.UnreadRune: previous operation was not ReadRune")
109
+ }
110
+ r.i = int64(r.prevRune)
111
+ r.prevRune = -1
112
+ return nil
113
+ }
114
+
115
+ // Seek implements the [io.Seeker] interface.
116
+ func (r *Reader) Seek(offset int64, whence int) (int64, error) {
117
+ r.prevRune = -1
118
+ var abs int64
119
+ switch whence {
120
+ case io.SeekStart:
121
+ abs = offset
122
+ case io.SeekCurrent:
123
+ abs = r.i + offset
124
+ case io.SeekEnd:
125
+ abs = int64(len(r.s)) + offset
126
+ default:
127
+ return 0, errors.New("bytes.Reader.Seek: invalid whence")
128
+ }
129
+ if abs < 0 {
130
+ return 0, errors.New("bytes.Reader.Seek: negative position")
131
+ }
132
+ r.i = abs
133
+ return abs, nil
134
+ }
135
+
136
+ // WriteTo implements the [io.WriterTo] interface.
137
+ func (r *Reader) WriteTo(w io.Writer) (n int64, err error) {
138
+ r.prevRune = -1
139
+ if r.i >= int64(len(r.s)) {
140
+ return 0, nil
141
+ }
142
+ b := r.s[r.i:]
143
+ m, err := w.Write(b)
144
+ if m > len(b) {
145
+ panic("bytes.Reader.WriteTo: invalid Write count")
146
+ }
147
+ r.i += int64(m)
148
+ n = int64(m)
149
+ if m != len(b) && err == nil {
150
+ err = io.ErrShortWrite
151
+ }
152
+ return
153
+ }
154
+
155
+ // Reset resets the [Reader] to be reading from b.
156
+ func (r *Reader) Reset(b []byte) { *r = Reader{b, 0, -1} }
157
+
158
+ // NewReader returns a new [Reader] reading from b.
159
+ func NewReader(b []byte) *Reader { return &Reader{b, 0, -1} }
go/src/bytes/reader_test.go ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package bytes_test
6
+
7
+ import (
8
+ . "bytes"
9
+ "fmt"
10
+ "io"
11
+ "sync"
12
+ "testing"
13
+ )
14
+
15
+ func TestReader(t *testing.T) {
16
+ r := NewReader([]byte("0123456789"))
17
+ tests := []struct {
18
+ off int64
19
+ seek int
20
+ n int
21
+ want string
22
+ wantpos int64
23
+ readerr error
24
+ seekerr string
25
+ }{
26
+ {seek: io.SeekStart, off: 0, n: 20, want: "0123456789"},
27
+ {seek: io.SeekStart, off: 1, n: 1, want: "1"},
28
+ {seek: io.SeekCurrent, off: 1, wantpos: 3, n: 2, want: "34"},
29
+ {seek: io.SeekStart, off: -1, seekerr: "bytes.Reader.Seek: negative position"},
30
+ {seek: io.SeekStart, off: 1 << 33, wantpos: 1 << 33, readerr: io.EOF},
31
+ {seek: io.SeekCurrent, off: 1, wantpos: 1<<33 + 1, readerr: io.EOF},
32
+ {seek: io.SeekStart, n: 5, want: "01234"},
33
+ {seek: io.SeekCurrent, n: 5, want: "56789"},
34
+ {seek: io.SeekEnd, off: -1, n: 1, wantpos: 9, want: "9"},
35
+ }
36
+
37
+ for i, tt := range tests {
38
+ pos, err := r.Seek(tt.off, tt.seek)
39
+ if err == nil && tt.seekerr != "" {
40
+ t.Errorf("%d. want seek error %q", i, tt.seekerr)
41
+ continue
42
+ }
43
+ if err != nil && err.Error() != tt.seekerr {
44
+ t.Errorf("%d. seek error = %q; want %q", i, err.Error(), tt.seekerr)
45
+ continue
46
+ }
47
+ if tt.wantpos != 0 && tt.wantpos != pos {
48
+ t.Errorf("%d. pos = %d, want %d", i, pos, tt.wantpos)
49
+ }
50
+ buf := make([]byte, tt.n)
51
+ n, err := r.Read(buf)
52
+ if err != tt.readerr {
53
+ t.Errorf("%d. read = %v; want %v", i, err, tt.readerr)
54
+ continue
55
+ }
56
+ got := string(buf[:n])
57
+ if got != tt.want {
58
+ t.Errorf("%d. got %q; want %q", i, got, tt.want)
59
+ }
60
+ }
61
+ }
62
+
63
+ func TestReadAfterBigSeek(t *testing.T) {
64
+ r := NewReader([]byte("0123456789"))
65
+ if _, err := r.Seek(1<<31+5, io.SeekStart); err != nil {
66
+ t.Fatal(err)
67
+ }
68
+ if n, err := r.Read(make([]byte, 10)); n != 0 || err != io.EOF {
69
+ t.Errorf("Read = %d, %v; want 0, EOF", n, err)
70
+ }
71
+ }
72
+
73
+ func TestReaderAt(t *testing.T) {
74
+ r := NewReader([]byte("0123456789"))
75
+ tests := []struct {
76
+ off int64
77
+ n int
78
+ want string
79
+ wanterr any
80
+ }{
81
+ {0, 10, "0123456789", nil},
82
+ {1, 10, "123456789", io.EOF},
83
+ {1, 9, "123456789", nil},
84
+ {11, 10, "", io.EOF},
85
+ {0, 0, "", nil},
86
+ {-1, 0, "", "bytes.Reader.ReadAt: negative offset"},
87
+ }
88
+ for i, tt := range tests {
89
+ b := make([]byte, tt.n)
90
+ rn, err := r.ReadAt(b, tt.off)
91
+ got := string(b[:rn])
92
+ if got != tt.want {
93
+ t.Errorf("%d. got %q; want %q", i, got, tt.want)
94
+ }
95
+ if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", tt.wanterr) {
96
+ t.Errorf("%d. got error = %v; want %v", i, err, tt.wanterr)
97
+ }
98
+ }
99
+ }
100
+
101
+ func TestReaderAtConcurrent(t *testing.T) {
102
+ // Test for the race detector, to verify ReadAt doesn't mutate
103
+ // any state.
104
+ r := NewReader([]byte("0123456789"))
105
+ var wg sync.WaitGroup
106
+ for i := 0; i < 5; i++ {
107
+ wg.Add(1)
108
+ go func(i int) {
109
+ defer wg.Done()
110
+ var buf [1]byte
111
+ r.ReadAt(buf[:], int64(i))
112
+ }(i)
113
+ }
114
+ wg.Wait()
115
+ }
116
+
117
+ func TestEmptyReaderConcurrent(t *testing.T) {
118
+ // Test for the race detector, to verify a Read that doesn't yield any bytes
119
+ // is okay to use from multiple goroutines. This was our historic behavior.
120
+ // See golang.org/issue/7856
121
+ r := NewReader([]byte{})
122
+ var wg sync.WaitGroup
123
+ for i := 0; i < 5; i++ {
124
+ wg.Add(2)
125
+ go func() {
126
+ defer wg.Done()
127
+ var buf [1]byte
128
+ r.Read(buf[:])
129
+ }()
130
+ go func() {
131
+ defer wg.Done()
132
+ r.Read(nil)
133
+ }()
134
+ }
135
+ wg.Wait()
136
+ }
137
+
138
+ func TestReaderWriteTo(t *testing.T) {
139
+ for i := 0; i < 30; i += 3 {
140
+ var l int
141
+ if i > 0 {
142
+ l = len(testString) / i
143
+ }
144
+ s := testString[:l]
145
+ r := NewReader(testBytes[:l])
146
+ var b Buffer
147
+ n, err := r.WriteTo(&b)
148
+ if expect := int64(len(s)); n != expect {
149
+ t.Errorf("got %v; want %v", n, expect)
150
+ }
151
+ if err != nil {
152
+ t.Errorf("for length %d: got error = %v; want nil", l, err)
153
+ }
154
+ if b.String() != s {
155
+ t.Errorf("got string %q; want %q", b.String(), s)
156
+ }
157
+ if r.Len() != 0 {
158
+ t.Errorf("reader contains %v bytes; want 0", r.Len())
159
+ }
160
+ }
161
+ }
162
+
163
+ func TestReaderLen(t *testing.T) {
164
+ const data = "hello world"
165
+ r := NewReader([]byte(data))
166
+ if got, want := r.Len(), 11; got != want {
167
+ t.Errorf("r.Len(): got %d, want %d", got, want)
168
+ }
169
+ if n, err := r.Read(make([]byte, 10)); err != nil || n != 10 {
170
+ t.Errorf("Read failed: read %d %v", n, err)
171
+ }
172
+ if got, want := r.Len(), 1; got != want {
173
+ t.Errorf("r.Len(): got %d, want %d", got, want)
174
+ }
175
+ if n, err := r.Read(make([]byte, 1)); err != nil || n != 1 {
176
+ t.Errorf("Read failed: read %d %v; want 1, nil", n, err)
177
+ }
178
+ if got, want := r.Len(), 0; got != want {
179
+ t.Errorf("r.Len(): got %d, want %d", got, want)
180
+ }
181
+ }
182
+
183
+ var UnreadRuneErrorTests = []struct {
184
+ name string
185
+ f func(*Reader)
186
+ }{
187
+ {"Read", func(r *Reader) { r.Read([]byte{0}) }},
188
+ {"ReadByte", func(r *Reader) { r.ReadByte() }},
189
+ {"UnreadRune", func(r *Reader) { r.UnreadRune() }},
190
+ {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }},
191
+ {"WriteTo", func(r *Reader) { r.WriteTo(&Buffer{}) }},
192
+ }
193
+
194
+ func TestUnreadRuneError(t *testing.T) {
195
+ for _, tt := range UnreadRuneErrorTests {
196
+ reader := NewReader([]byte("0123456789"))
197
+ if _, _, err := reader.ReadRune(); err != nil {
198
+ // should not happen
199
+ t.Fatal(err)
200
+ }
201
+ tt.f(reader)
202
+ err := reader.UnreadRune()
203
+ if err == nil {
204
+ t.Errorf("Unreading after %s: expected error", tt.name)
205
+ }
206
+ }
207
+ }
208
+
209
+ func TestReaderDoubleUnreadRune(t *testing.T) {
210
+ buf := NewBuffer([]byte("groucho"))
211
+ if _, _, err := buf.ReadRune(); err != nil {
212
+ // should not happen
213
+ t.Fatal(err)
214
+ }
215
+ if err := buf.UnreadByte(); err != nil {
216
+ // should not happen
217
+ t.Fatal(err)
218
+ }
219
+ if err := buf.UnreadByte(); err == nil {
220
+ t.Fatal("UnreadByte: expected error, got nil")
221
+ }
222
+ }
223
+
224
+ // verify that copying from an empty reader always has the same results,
225
+ // regardless of the presence of a WriteTo method.
226
+ func TestReaderCopyNothing(t *testing.T) {
227
+ type nErr struct {
228
+ n int64
229
+ err error
230
+ }
231
+ type justReader struct {
232
+ io.Reader
233
+ }
234
+ type justWriter struct {
235
+ io.Writer
236
+ }
237
+ discard := justWriter{io.Discard} // hide ReadFrom
238
+
239
+ var with, withOut nErr
240
+ with.n, with.err = io.Copy(discard, NewReader(nil))
241
+ withOut.n, withOut.err = io.Copy(discard, justReader{NewReader(nil)})
242
+ if with != withOut {
243
+ t.Errorf("behavior differs: with = %#v; without: %#v", with, withOut)
244
+ }
245
+ }
246
+
247
+ // tests that Len is affected by reads, but Size is not.
248
+ func TestReaderLenSize(t *testing.T) {
249
+ r := NewReader([]byte("abc"))
250
+ io.CopyN(io.Discard, r, 1)
251
+ if r.Len() != 2 {
252
+ t.Errorf("Len = %d; want 2", r.Len())
253
+ }
254
+ if r.Size() != 3 {
255
+ t.Errorf("Size = %d; want 3", r.Size())
256
+ }
257
+ }
258
+
259
+ func TestReaderReset(t *testing.T) {
260
+ r := NewReader([]byte("世界"))
261
+ if _, _, err := r.ReadRune(); err != nil {
262
+ t.Errorf("ReadRune: unexpected error: %v", err)
263
+ }
264
+
265
+ const want = "abcdef"
266
+ r.Reset([]byte(want))
267
+ if err := r.UnreadRune(); err == nil {
268
+ t.Errorf("UnreadRune: expected error, got nil")
269
+ }
270
+ buf, err := io.ReadAll(r)
271
+ if err != nil {
272
+ t.Errorf("ReadAll: unexpected error: %v", err)
273
+ }
274
+ if got := string(buf); got != want {
275
+ t.Errorf("ReadAll: got %q, want %q", got, want)
276
+ }
277
+ }
278
+
279
+ func TestReaderZero(t *testing.T) {
280
+ if l := (&Reader{}).Len(); l != 0 {
281
+ t.Errorf("Len: got %d, want 0", l)
282
+ }
283
+
284
+ if n, err := (&Reader{}).Read(nil); n != 0 || err != io.EOF {
285
+ t.Errorf("Read: got %d, %v; want 0, io.EOF", n, err)
286
+ }
287
+
288
+ if n, err := (&Reader{}).ReadAt(nil, 11); n != 0 || err != io.EOF {
289
+ t.Errorf("ReadAt: got %d, %v; want 0, io.EOF", n, err)
290
+ }
291
+
292
+ if b, err := (&Reader{}).ReadByte(); b != 0 || err != io.EOF {
293
+ t.Errorf("ReadByte: got %d, %v; want 0, io.EOF", b, err)
294
+ }
295
+
296
+ if ch, size, err := (&Reader{}).ReadRune(); ch != 0 || size != 0 || err != io.EOF {
297
+ t.Errorf("ReadRune: got %d, %d, %v; want 0, 0, io.EOF", ch, size, err)
298
+ }
299
+
300
+ if offset, err := (&Reader{}).Seek(11, io.SeekStart); offset != 11 || err != nil {
301
+ t.Errorf("Seek: got %d, %v; want 11, nil", offset, err)
302
+ }
303
+
304
+ if s := (&Reader{}).Size(); s != 0 {
305
+ t.Errorf("Size: got %d, want 0", s)
306
+ }
307
+
308
+ if (&Reader{}).UnreadByte() == nil {
309
+ t.Errorf("UnreadByte: got nil, want error")
310
+ }
311
+
312
+ if (&Reader{}).UnreadRune() == nil {
313
+ t.Errorf("UnreadRune: got nil, want error")
314
+ }
315
+
316
+ if n, err := (&Reader{}).WriteTo(io.Discard); n != 0 || err != nil {
317
+ t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err)
318
+ }
319
+ }
go/src/cmd/README.vendor ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ See src/README.vendor for information on loading vendored packages
2
+ and updating the vendor directory.
go/src/cmd/go.mod ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module cmd
2
+
3
+ go 1.26
4
+
5
+ require (
6
+ github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8
7
+ golang.org/x/arch v0.23.0
8
+ golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8
9
+ golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350
10
+ golang.org/x/sync v0.19.0
11
+ golang.org/x/sys v0.39.0
12
+ golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec
13
+ golang.org/x/term v0.38.0
14
+ golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d
15
+ )
16
+
17
+ require (
18
+ github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b // indirect
19
+ golang.org/x/text v0.32.0 // indirect
20
+ rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef // indirect
21
+ )
go/src/cmd/go.sum ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
2
+ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
3
+ github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8 h1:3DsUAV+VNEQa2CUVLxCY3f87278uWfIDhJnbdvDjvmE=
4
+ github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
5
+ github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b h1:ogbOPx86mIhFy764gGkqnkFC8m5PJA7sPzlk9ppLVQA=
6
+ github.com/ianlancetaylor/demangle v0.0.0-20250417193237-f615e6bd150b/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
7
+ github.com/yuin/goldmark v1.6.0 h1:boZcn2GTjpsynOsC0iJHnBWa4Bi0qzfJjthwauItG68=
8
+ github.com/yuin/goldmark v1.6.0/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
9
+ golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
10
+ golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
11
+ golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8 h1:Mp+uRtHbKFW85lGBTOkOOfkPBz7AUKmZGcflkavmGRM=
12
+ golang.org/x/build v0.0.0-20251128064159-b9bfd88b30e8/go.mod h1:Jx2RBBeTWGRSCwfSZ+w2Hg1f7LjWycsSkx+EciLAmPE=
13
+ golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350 h1:JGDMsCp8NahDR9HSvwrF6V8tzEf87m7Bo4oZ07vRxdU=
14
+ golang.org/x/mod v0.30.1-0.20251115032019-269c237cf350/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
15
+ golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
16
+ golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
17
+ golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
18
+ golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
19
+ golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec h1:dRVkWZl6bUOp+oxnOe4BuyhWSIPmt29N4ooHarm7Ic8=
20
+ golang.org/x/telemetry v0.0.0-20251128220624-abf20d0e57ec/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
21
+ golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
22
+ golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
23
+ golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
24
+ golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
25
+ golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d h1:d9RYG/Z8xQk+tFy5IyhSwUrt4HhSsqHw/uhwmn1KaJg=
26
+ golang.org/x/tools v0.39.1-0.20260323181443-4f499ecaa91d/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
27
+ rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef h1:mqLYrXCXYEZOop9/Dbo6RPX11539nwiCNBb1icVPmw8=
28
+ rsc.io/markdown v0.0.0-20240306144322-0bf8f97ee8ef/go.mod h1:8xcPgWmwlZONN1D9bjxtHEjrUtSEa3fakVF8iaewYKQ=
go/src/cmp/cmp.go ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package cmp provides types and functions related to comparing
6
+ // ordered values.
7
+ package cmp
8
+
9
+ // Ordered is a constraint that permits any ordered type: any type
10
+ // that supports the operators < <= >= >.
11
+ // If future releases of Go add new ordered types,
12
+ // this constraint will be modified to include them.
13
+ //
14
+ // Note that floating-point types may contain NaN ("not-a-number") values.
15
+ // An operator such as == or < will always report false when
16
+ // comparing a NaN value with any other value, NaN or not.
17
+ // See the [Compare] function for a consistent way to compare NaN values.
18
+ type Ordered interface {
19
+ ~int | ~int8 | ~int16 | ~int32 | ~int64 |
20
+ ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
21
+ ~float32 | ~float64 |
22
+ ~string
23
+ }
24
+
25
+ // Less reports whether x is less than y.
26
+ // For floating-point types, a NaN is considered less than any non-NaN,
27
+ // and -0.0 is not less than (is equal to) 0.0.
28
+ func Less[T Ordered](x, y T) bool {
29
+ return (isNaN(x) && !isNaN(y)) || x < y
30
+ }
31
+
32
+ // Compare returns
33
+ //
34
+ // -1 if x is less than y,
35
+ // 0 if x equals y,
36
+ // +1 if x is greater than y.
37
+ //
38
+ // For floating-point types, a NaN is considered less than any non-NaN,
39
+ // a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
40
+ func Compare[T Ordered](x, y T) int {
41
+ xNaN := isNaN(x)
42
+ yNaN := isNaN(y)
43
+ if xNaN {
44
+ if yNaN {
45
+ return 0
46
+ }
47
+ return -1
48
+ }
49
+ if yNaN {
50
+ return +1
51
+ }
52
+ if x < y {
53
+ return -1
54
+ }
55
+ if x > y {
56
+ return +1
57
+ }
58
+ return 0
59
+ }
60
+
61
+ // isNaN reports whether x is a NaN without requiring the math package.
62
+ // This will always return false if T is not floating-point.
63
+ func isNaN[T Ordered](x T) bool {
64
+ return x != x
65
+ }
66
+
67
+ // Or returns the first of its arguments that is not equal to the zero value.
68
+ // If no argument is non-zero, it returns the zero value.
69
+ func Or[T comparable](vals ...T) T {
70
+ var zero T
71
+ for _, val := range vals {
72
+ if val != zero {
73
+ return val
74
+ }
75
+ }
76
+ return zero
77
+ }
go/src/cmp/cmp_test.go ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package cmp_test
6
+
7
+ import (
8
+ "cmp"
9
+ "fmt"
10
+ "math"
11
+ "slices"
12
+ "sort"
13
+ "strings"
14
+ "testing"
15
+ "unsafe"
16
+ )
17
+
18
+ var negzero = math.Copysign(0, -1)
19
+ var nonnilptr uintptr = uintptr(unsafe.Pointer(&negzero))
20
+ var nilptr uintptr = uintptr(unsafe.Pointer(nil))
21
+
22
+ var tests = []struct {
23
+ x, y any
24
+ compare int
25
+ }{
26
+ {1, 2, -1},
27
+ {1, 1, 0},
28
+ {2, 1, +1},
29
+ {"a", "aa", -1},
30
+ {"a", "a", 0},
31
+ {"aa", "a", +1},
32
+ {1.0, 1.1, -1},
33
+ {1.1, 1.1, 0},
34
+ {1.1, 1.0, +1},
35
+ {math.Inf(1), math.Inf(1), 0},
36
+ {math.Inf(-1), math.Inf(-1), 0},
37
+ {math.Inf(-1), 1.0, -1},
38
+ {1.0, math.Inf(-1), +1},
39
+ {math.Inf(1), 1.0, +1},
40
+ {1.0, math.Inf(1), -1},
41
+ {math.NaN(), math.NaN(), 0},
42
+ {0.0, math.NaN(), +1},
43
+ {math.NaN(), 0.0, -1},
44
+ {math.NaN(), math.Inf(-1), -1},
45
+ {math.Inf(-1), math.NaN(), +1},
46
+ {0.0, 0.0, 0},
47
+ {negzero, negzero, 0},
48
+ {negzero, 0.0, 0},
49
+ {0.0, negzero, 0},
50
+ {negzero, 1.0, -1},
51
+ {negzero, -1.0, +1},
52
+ {nilptr, nonnilptr, -1},
53
+ {nonnilptr, nilptr, 1},
54
+ {nonnilptr, nonnilptr, 0},
55
+ }
56
+
57
+ func TestLess(t *testing.T) {
58
+ for _, test := range tests {
59
+ var b bool
60
+ switch test.x.(type) {
61
+ case int:
62
+ b = cmp.Less(test.x.(int), test.y.(int))
63
+ case string:
64
+ b = cmp.Less(test.x.(string), test.y.(string))
65
+ case float64:
66
+ b = cmp.Less(test.x.(float64), test.y.(float64))
67
+ case uintptr:
68
+ b = cmp.Less(test.x.(uintptr), test.y.(uintptr))
69
+ }
70
+ if b != (test.compare < 0) {
71
+ t.Errorf("Less(%v, %v) == %t, want %t", test.x, test.y, b, test.compare < 0)
72
+ }
73
+ }
74
+ }
75
+
76
+ func TestCompare(t *testing.T) {
77
+ for _, test := range tests {
78
+ var c int
79
+ switch test.x.(type) {
80
+ case int:
81
+ c = cmp.Compare(test.x.(int), test.y.(int))
82
+ case string:
83
+ c = cmp.Compare(test.x.(string), test.y.(string))
84
+ case float64:
85
+ c = cmp.Compare(test.x.(float64), test.y.(float64))
86
+ case uintptr:
87
+ c = cmp.Compare(test.x.(uintptr), test.y.(uintptr))
88
+ }
89
+ if c != test.compare {
90
+ t.Errorf("Compare(%v, %v) == %d, want %d", test.x, test.y, c, test.compare)
91
+ }
92
+ }
93
+ }
94
+
95
+ func TestSort(t *testing.T) {
96
+ // Test that our comparison function is consistent with
97
+ // sort.Float64s.
98
+ input := []float64{1.0, 0.0, negzero, math.Inf(1), math.Inf(-1), math.NaN()}
99
+ sort.Float64s(input)
100
+ for i := 0; i < len(input)-1; i++ {
101
+ if cmp.Less(input[i+1], input[i]) {
102
+ t.Errorf("Less sort mismatch at %d in %v", i, input)
103
+ }
104
+ if cmp.Compare(input[i], input[i+1]) > 0 {
105
+ t.Errorf("Compare sort mismatch at %d in %v", i, input)
106
+ }
107
+ }
108
+ }
109
+
110
+ func TestOr(t *testing.T) {
111
+ cases := []struct {
112
+ in []int
113
+ want int
114
+ }{
115
+ {nil, 0},
116
+ {[]int{0}, 0},
117
+ {[]int{1}, 1},
118
+ {[]int{0, 2}, 2},
119
+ {[]int{3, 0}, 3},
120
+ {[]int{4, 5}, 4},
121
+ {[]int{0, 6, 7}, 6},
122
+ }
123
+ for _, tc := range cases {
124
+ if got := cmp.Or(tc.in...); got != tc.want {
125
+ t.Errorf("cmp.Or(%v) = %v; want %v", tc.in, got, tc.want)
126
+ }
127
+ }
128
+ }
129
+
130
+ func ExampleOr() {
131
+ // Suppose we have some user input
132
+ // that may or may not be an empty string
133
+ userInput1 := ""
134
+ userInput2 := "some text"
135
+
136
+ fmt.Println(cmp.Or(userInput1, "default"))
137
+ fmt.Println(cmp.Or(userInput2, "default"))
138
+ fmt.Println(cmp.Or(userInput1, userInput2, "default"))
139
+ // Output:
140
+ // default
141
+ // some text
142
+ // some text
143
+ }
144
+
145
+ func ExampleOr_sort() {
146
+ type Order struct {
147
+ Product string
148
+ Customer string
149
+ Price float64
150
+ }
151
+ orders := []Order{
152
+ {"foo", "alice", 1.00},
153
+ {"bar", "bob", 3.00},
154
+ {"baz", "carol", 4.00},
155
+ {"foo", "alice", 2.00},
156
+ {"bar", "carol", 1.00},
157
+ {"foo", "bob", 4.00},
158
+ }
159
+ // Sort by customer first, product second, and last by higher price
160
+ slices.SortFunc(orders, func(a, b Order) int {
161
+ return cmp.Or(
162
+ strings.Compare(a.Customer, b.Customer),
163
+ strings.Compare(a.Product, b.Product),
164
+ cmp.Compare(b.Price, a.Price),
165
+ )
166
+ })
167
+ for _, order := range orders {
168
+ fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price)
169
+ }
170
+
171
+ // Output:
172
+ // foo alice 2.00
173
+ // foo alice 1.00
174
+ // bar bob 3.00
175
+ // foo bob 4.00
176
+ // bar carol 1.00
177
+ // baz carol 4.00
178
+ }
179
+
180
+ func ExampleLess() {
181
+ fmt.Println(cmp.Less(1, 2))
182
+ fmt.Println(cmp.Less("a", "aa"))
183
+ fmt.Println(cmp.Less(1.0, math.NaN()))
184
+ fmt.Println(cmp.Less(math.NaN(), 1.0))
185
+ // Output:
186
+ // true
187
+ // true
188
+ // false
189
+ // true
190
+ }
191
+
192
+ func ExampleCompare() {
193
+ fmt.Println(cmp.Compare(1, 2))
194
+ fmt.Println(cmp.Compare("a", "aa"))
195
+ fmt.Println(cmp.Compare(1.5, 1.5))
196
+ fmt.Println(cmp.Compare(math.NaN(), 1.0))
197
+ // Output:
198
+ // -1
199
+ // -1
200
+ // 0
201
+ // -1
202
+ }
go/src/context/afterfunc_test.go ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context_test
6
+
7
+ import (
8
+ "context"
9
+ "sync"
10
+ "testing"
11
+ "time"
12
+ )
13
+
14
+ // afterFuncContext is a context that's not one of the types
15
+ // defined in context.go, that supports registering AfterFuncs.
16
+ type afterFuncContext struct {
17
+ mu sync.Mutex
18
+ afterFuncs map[*byte]func()
19
+ done chan struct{}
20
+ err error
21
+ }
22
+
23
+ var _ context.Context = (*afterFuncContext)(nil)
24
+
25
+ func (c *afterFuncContext) Deadline() (time.Time, bool) {
26
+ return time.Time{}, false
27
+ }
28
+
29
+ func (c *afterFuncContext) Done() <-chan struct{} {
30
+ c.mu.Lock()
31
+ defer c.mu.Unlock()
32
+ if c.done == nil {
33
+ c.done = make(chan struct{})
34
+ }
35
+ return c.done
36
+ }
37
+
38
+ func (c *afterFuncContext) Err() error {
39
+ c.mu.Lock()
40
+ defer c.mu.Unlock()
41
+ return c.err
42
+ }
43
+
44
+ func (c *afterFuncContext) Value(key any) any {
45
+ return nil
46
+ }
47
+
48
+ func (c *afterFuncContext) AfterFunc(f func()) func() bool {
49
+ c.mu.Lock()
50
+ defer c.mu.Unlock()
51
+ k := new(byte)
52
+ if c.afterFuncs == nil {
53
+ c.afterFuncs = make(map[*byte]func())
54
+ }
55
+ c.afterFuncs[k] = f
56
+ return func() bool {
57
+ c.mu.Lock()
58
+ defer c.mu.Unlock()
59
+ _, ok := c.afterFuncs[k]
60
+ delete(c.afterFuncs, k)
61
+ return ok
62
+ }
63
+ }
64
+
65
+ func (c *afterFuncContext) cancel(err error) {
66
+ c.mu.Lock()
67
+ defer c.mu.Unlock()
68
+ if c.err != nil {
69
+ return
70
+ }
71
+ c.err = err
72
+ for _, f := range c.afterFuncs {
73
+ go f()
74
+ }
75
+ c.afterFuncs = nil
76
+ }
77
+
78
+ func TestCustomContextAfterFuncCancel(t *testing.T) {
79
+ ctx0 := &afterFuncContext{}
80
+ ctx1, cancel := context.WithCancel(ctx0)
81
+ defer cancel()
82
+ ctx0.cancel(context.Canceled)
83
+ <-ctx1.Done()
84
+ }
85
+
86
+ func TestCustomContextAfterFuncTimeout(t *testing.T) {
87
+ ctx0 := &afterFuncContext{}
88
+ ctx1, cancel := context.WithTimeout(ctx0, veryLongDuration)
89
+ defer cancel()
90
+ ctx0.cancel(context.Canceled)
91
+ <-ctx1.Done()
92
+ }
93
+
94
+ func TestCustomContextAfterFuncAfterFunc(t *testing.T) {
95
+ ctx0 := &afterFuncContext{}
96
+ donec := make(chan struct{})
97
+ stop := context.AfterFunc(ctx0, func() {
98
+ close(donec)
99
+ })
100
+ defer stop()
101
+ ctx0.cancel(context.Canceled)
102
+ <-donec
103
+ }
104
+
105
+ func TestCustomContextAfterFuncUnregisterCancel(t *testing.T) {
106
+ ctx0 := &afterFuncContext{}
107
+ _, cancel1 := context.WithCancel(ctx0)
108
+ _, cancel2 := context.WithCancel(ctx0)
109
+ if got, want := len(ctx0.afterFuncs), 2; got != want {
110
+ t.Errorf("after WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want)
111
+ }
112
+ cancel1()
113
+ cancel2()
114
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
115
+ t.Errorf("after canceling WithCancel(ctx0): ctx0 has %v afterFuncs, want %v", got, want)
116
+ }
117
+ }
118
+
119
+ func TestCustomContextAfterFuncUnregisterTimeout(t *testing.T) {
120
+ ctx0 := &afterFuncContext{}
121
+ _, cancel := context.WithTimeout(ctx0, veryLongDuration)
122
+ if got, want := len(ctx0.afterFuncs), 1; got != want {
123
+ t.Errorf("after WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want)
124
+ }
125
+ cancel()
126
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
127
+ t.Errorf("after canceling WithTimeout(ctx0, d): ctx0 has %v afterFuncs, want %v", got, want)
128
+ }
129
+ }
130
+
131
+ func TestCustomContextAfterFuncUnregisterAfterFunc(t *testing.T) {
132
+ ctx0 := &afterFuncContext{}
133
+ stop := context.AfterFunc(ctx0, func() {})
134
+ if got, want := len(ctx0.afterFuncs), 1; got != want {
135
+ t.Errorf("after AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want)
136
+ }
137
+ stop()
138
+ if got, want := len(ctx0.afterFuncs), 0; got != want {
139
+ t.Errorf("after stopping AfterFunc(ctx0, f): ctx0 has %v afterFuncs, want %v", got, want)
140
+ }
141
+ }
go/src/context/benchmark_test.go ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context_test
6
+
7
+ import (
8
+ . "context"
9
+ "fmt"
10
+ "runtime"
11
+ "sync"
12
+ "testing"
13
+ "time"
14
+ )
15
+
16
+ func BenchmarkCommonParentCancel(b *testing.B) {
17
+ root := WithValue(Background(), "key", "value")
18
+ shared, sharedcancel := WithCancel(root)
19
+ defer sharedcancel()
20
+
21
+ b.ResetTimer()
22
+ b.RunParallel(func(pb *testing.PB) {
23
+ x := 0
24
+ for pb.Next() {
25
+ ctx, cancel := WithCancel(shared)
26
+ if ctx.Value("key").(string) != "value" {
27
+ b.Fatal("should not be reached")
28
+ }
29
+ for i := 0; i < 100; i++ {
30
+ x /= x + 1
31
+ }
32
+ cancel()
33
+ for i := 0; i < 100; i++ {
34
+ x /= x + 1
35
+ }
36
+ }
37
+ })
38
+ }
39
+
40
+ func BenchmarkWithTimeout(b *testing.B) {
41
+ for concurrency := 40; concurrency <= 4e5; concurrency *= 100 {
42
+ name := fmt.Sprintf("concurrency=%d", concurrency)
43
+ b.Run(name, func(b *testing.B) {
44
+ benchmarkWithTimeout(b, concurrency)
45
+ })
46
+ }
47
+ }
48
+
49
+ func benchmarkWithTimeout(b *testing.B, concurrentContexts int) {
50
+ gomaxprocs := runtime.GOMAXPROCS(0)
51
+ perPContexts := concurrentContexts / gomaxprocs
52
+ root := Background()
53
+
54
+ // Generate concurrent contexts.
55
+ var wg sync.WaitGroup
56
+ ccf := make([][]CancelFunc, gomaxprocs)
57
+ for i := range ccf {
58
+ wg.Add(1)
59
+ go func(i int) {
60
+ defer wg.Done()
61
+ cf := make([]CancelFunc, perPContexts)
62
+ for j := range cf {
63
+ _, cf[j] = WithTimeout(root, time.Hour)
64
+ }
65
+ ccf[i] = cf
66
+ }(i)
67
+ }
68
+ wg.Wait()
69
+
70
+ b.ResetTimer()
71
+ b.RunParallel(func(pb *testing.PB) {
72
+ wcf := make([]CancelFunc, 10)
73
+ for pb.Next() {
74
+ for i := range wcf {
75
+ _, wcf[i] = WithTimeout(root, time.Hour)
76
+ }
77
+ for _, f := range wcf {
78
+ f()
79
+ }
80
+ }
81
+ })
82
+ b.StopTimer()
83
+
84
+ for _, cf := range ccf {
85
+ for _, f := range cf {
86
+ f()
87
+ }
88
+ }
89
+ }
90
+
91
+ func BenchmarkCancelTree(b *testing.B) {
92
+ depths := []int{1, 10, 100, 1000}
93
+ for _, d := range depths {
94
+ b.Run(fmt.Sprintf("depth=%d", d), func(b *testing.B) {
95
+ b.Run("Root=Background", func(b *testing.B) {
96
+ for i := 0; i < b.N; i++ {
97
+ buildContextTree(Background(), d)
98
+ }
99
+ })
100
+ b.Run("Root=OpenCanceler", func(b *testing.B) {
101
+ for i := 0; i < b.N; i++ {
102
+ ctx, cancel := WithCancel(Background())
103
+ buildContextTree(ctx, d)
104
+ cancel()
105
+ }
106
+ })
107
+ b.Run("Root=ClosedCanceler", func(b *testing.B) {
108
+ for i := 0; i < b.N; i++ {
109
+ ctx, cancel := WithCancel(Background())
110
+ cancel()
111
+ buildContextTree(ctx, d)
112
+ }
113
+ })
114
+ })
115
+ }
116
+ }
117
+
118
+ func buildContextTree(root Context, depth int) {
119
+ for d := 0; d < depth; d++ {
120
+ root, _ = WithCancel(root)
121
+ }
122
+ }
123
+
124
+ func BenchmarkCheckCanceled(b *testing.B) {
125
+ ctx, cancel := WithCancel(Background())
126
+ cancel()
127
+ b.Run("Err", func(b *testing.B) {
128
+ for i := 0; i < b.N; i++ {
129
+ ctx.Err()
130
+ }
131
+ })
132
+ b.Run("Done", func(b *testing.B) {
133
+ for i := 0; i < b.N; i++ {
134
+ select {
135
+ case <-ctx.Done():
136
+ default:
137
+ }
138
+ }
139
+ })
140
+ }
141
+
142
+ func BenchmarkContextCancelDone(b *testing.B) {
143
+ ctx, cancel := WithCancel(Background())
144
+ defer cancel()
145
+
146
+ b.RunParallel(func(pb *testing.PB) {
147
+ for pb.Next() {
148
+ select {
149
+ case <-ctx.Done():
150
+ default:
151
+ }
152
+ }
153
+ })
154
+ }
155
+
156
+ func BenchmarkDeepValueNewGoRoutine(b *testing.B) {
157
+ for _, depth := range []int{10, 20, 30, 50, 100} {
158
+ ctx := Background()
159
+ for i := 0; i < depth; i++ {
160
+ ctx = WithValue(ctx, i, i)
161
+ }
162
+
163
+ b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) {
164
+ for i := 0; i < b.N; i++ {
165
+ var wg sync.WaitGroup
166
+ wg.Add(1)
167
+ go func() {
168
+ defer wg.Done()
169
+ ctx.Value(-1)
170
+ }()
171
+ wg.Wait()
172
+ }
173
+ })
174
+ }
175
+ }
176
+
177
+ func BenchmarkDeepValueSameGoRoutine(b *testing.B) {
178
+ for _, depth := range []int{10, 20, 30, 50, 100} {
179
+ ctx := Background()
180
+ for i := 0; i < depth; i++ {
181
+ ctx = WithValue(ctx, i, i)
182
+ }
183
+
184
+ b.Run(fmt.Sprintf("depth=%d", depth), func(b *testing.B) {
185
+ for i := 0; i < b.N; i++ {
186
+ ctx.Value(-1)
187
+ }
188
+ })
189
+ }
190
+ }
191
+
192
+ func BenchmarkErrOK(b *testing.B) {
193
+ ctx, cancel := WithCancel(Background())
194
+ defer cancel()
195
+ for b.Loop() {
196
+ if err := ctx.Err(); err != nil {
197
+ b.Fatalf("ctx.Err() = %v", err)
198
+ }
199
+ }
200
+ }
201
+
202
+ func BenchmarkErrCanceled(b *testing.B) {
203
+ ctx, cancel := WithCancel(Background())
204
+ cancel()
205
+ for b.Loop() {
206
+ if err := ctx.Err(); err == nil {
207
+ b.Fatalf("ctx.Err() = %v", err)
208
+ }
209
+ }
210
+ }
go/src/context/context.go ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package context defines the Context type, which carries deadlines,
6
+ // cancellation signals, and other request-scoped values across API boundaries
7
+ // and between processes.
8
+ //
9
+ // Incoming requests to a server should create a [Context], and outgoing
10
+ // calls to servers should accept a Context. The chain of function
11
+ // calls between them must propagate the Context, optionally replacing
12
+ // it with a derived Context created using [WithCancel], [WithDeadline],
13
+ // [WithTimeout], or [WithValue].
14
+ //
15
+ // A Context may be canceled to indicate that work done on its behalf should stop.
16
+ // A Context with a deadline is canceled after the deadline passes.
17
+ // When a Context is canceled, all Contexts derived from it are also canceled.
18
+ //
19
+ // The [WithCancel], [WithDeadline], and [WithTimeout] functions take a
20
+ // Context (the parent) and return a derived Context (the child) and a
21
+ // [CancelFunc]. Calling the CancelFunc directly cancels the child and its
22
+ // children, removes the parent's reference to the child, and stops
23
+ // any associated timers. Failing to call the CancelFunc leaks the
24
+ // child and its children until the parent is canceled. The go vet tool
25
+ // checks that CancelFuncs are used on all control-flow paths.
26
+ //
27
+ // The [WithCancelCause], [WithDeadlineCause], and [WithTimeoutCause] functions
28
+ // return a [CancelCauseFunc], which takes an error and records it as
29
+ // the cancellation cause. Calling [Cause] on the canceled context
30
+ // or any of its children retrieves the cause. If no cause is specified,
31
+ // Cause(ctx) returns the same value as ctx.Err().
32
+ //
33
+ // Programs that use Contexts should follow these rules to keep interfaces
34
+ // consistent across packages and enable static analysis tools to check context
35
+ // propagation:
36
+ //
37
+ // Do not store Contexts inside a struct type; instead, pass a Context
38
+ // explicitly to each function that needs it. This is discussed further in
39
+ // https://go.dev/blog/context-and-structs. The Context should be the first
40
+ // parameter, typically named ctx:
41
+ //
42
+ // func DoSomething(ctx context.Context, arg Arg) error {
43
+ // // ... use ctx ...
44
+ // }
45
+ //
46
+ // Do not pass a nil [Context], even if a function permits it. Pass [context.TODO]
47
+ // if you are unsure about which Context to use.
48
+ //
49
+ // Use context Values only for request-scoped data that transits processes and
50
+ // APIs, not for passing optional parameters to functions.
51
+ //
52
+ // The same Context may be passed to functions running in different goroutines;
53
+ // Contexts are safe for simultaneous use by multiple goroutines.
54
+ //
55
+ // See https://go.dev/blog/context for example code for a server that uses
56
+ // Contexts.
57
+ package context
58
+
59
+ import (
60
+ "errors"
61
+ "internal/reflectlite"
62
+ "sync"
63
+ "sync/atomic"
64
+ "time"
65
+ )
66
+
67
+ // A Context carries a deadline, a cancellation signal, and other values across
68
+ // API boundaries.
69
+ //
70
+ // Context's methods may be called by multiple goroutines simultaneously.
71
+ type Context interface {
72
+ // Deadline returns the time when work done on behalf of this context
73
+ // should be canceled. Deadline returns ok==false when no deadline is
74
+ // set. Successive calls to Deadline return the same results.
75
+ Deadline() (deadline time.Time, ok bool)
76
+
77
+ // Done returns a channel that's closed when work done on behalf of this
78
+ // context should be canceled. Done may return nil if this context can
79
+ // never be canceled. Successive calls to Done return the same value.
80
+ // The close of the Done channel may happen asynchronously,
81
+ // after the cancel function returns.
82
+ //
83
+ // WithCancel arranges for Done to be closed when cancel is called;
84
+ // WithDeadline arranges for Done to be closed when the deadline
85
+ // expires; WithTimeout arranges for Done to be closed when the timeout
86
+ // elapses.
87
+ //
88
+ // Done is provided for use in select statements:
89
+ //
90
+ // // Stream generates values with DoSomething and sends them to out
91
+ // // until DoSomething returns an error or ctx.Done is closed.
92
+ // func Stream(ctx context.Context, out chan<- Value) error {
93
+ // for {
94
+ // v, err := DoSomething(ctx)
95
+ // if err != nil {
96
+ // return err
97
+ // }
98
+ // select {
99
+ // case <-ctx.Done():
100
+ // return ctx.Err()
101
+ // case out <- v:
102
+ // }
103
+ // }
104
+ // }
105
+ //
106
+ // See https://go.dev/blog/pipelines for more examples of how to use
107
+ // a Done channel for cancellation.
108
+ Done() <-chan struct{}
109
+
110
+ // If Done is not yet closed, Err returns nil.
111
+ // If Done is closed, Err returns a non-nil error explaining why:
112
+ // DeadlineExceeded if the context's deadline passed,
113
+ // or Canceled if the context was canceled for some other reason.
114
+ // After Err returns a non-nil error, successive calls to Err return the same error.
115
+ Err() error
116
+
117
+ // Value returns the value associated with this context for key, or nil
118
+ // if no value is associated with key. Successive calls to Value with
119
+ // the same key returns the same result.
120
+ //
121
+ // Use context values only for request-scoped data that transits
122
+ // processes and API boundaries, not for passing optional parameters to
123
+ // functions.
124
+ //
125
+ // A key identifies a specific value in a Context. Functions that wish
126
+ // to store values in Context typically allocate a key in a global
127
+ // variable then use that key as the argument to context.WithValue and
128
+ // Context.Value. A key can be any type that supports equality;
129
+ // packages should define keys as an unexported type to avoid
130
+ // collisions.
131
+ //
132
+ // Packages that define a Context key should provide type-safe accessors
133
+ // for the values stored using that key:
134
+ //
135
+ // // Package user defines a User type that's stored in Contexts.
136
+ // package user
137
+ //
138
+ // import "context"
139
+ //
140
+ // // User is the type of value stored in the Contexts.
141
+ // type User struct {...}
142
+ //
143
+ // // key is an unexported type for keys defined in this package.
144
+ // // This prevents collisions with keys defined in other packages.
145
+ // type key int
146
+ //
147
+ // // userKey is the key for user.User values in Contexts. It is
148
+ // // unexported; clients use user.NewContext and user.FromContext
149
+ // // instead of using this key directly.
150
+ // var userKey key
151
+ //
152
+ // // NewContext returns a new Context that carries value u.
153
+ // func NewContext(ctx context.Context, u *User) context.Context {
154
+ // return context.WithValue(ctx, userKey, u)
155
+ // }
156
+ //
157
+ // // FromContext returns the User value stored in ctx, if any.
158
+ // func FromContext(ctx context.Context) (*User, bool) {
159
+ // u, ok := ctx.Value(userKey).(*User)
160
+ // return u, ok
161
+ // }
162
+ Value(key any) any
163
+ }
164
+
165
+ // Canceled is the error returned by [Context.Err] when the context is canceled
166
+ // for some reason other than its deadline passing.
167
+ var Canceled = errors.New("context canceled")
168
+
169
+ // DeadlineExceeded is the error returned by [Context.Err] when the context is canceled
170
+ // due to its deadline passing.
171
+ var DeadlineExceeded error = deadlineExceededError{}
172
+
173
+ type deadlineExceededError struct{}
174
+
175
+ func (deadlineExceededError) Error() string { return "context deadline exceeded" }
176
+ func (deadlineExceededError) Timeout() bool { return true }
177
+ func (deadlineExceededError) Temporary() bool { return true }
178
+
179
+ // An emptyCtx is never canceled, has no values, and has no deadline.
180
+ // It is the common base of backgroundCtx and todoCtx.
181
+ type emptyCtx struct{}
182
+
183
+ func (emptyCtx) Deadline() (deadline time.Time, ok bool) {
184
+ return
185
+ }
186
+
187
+ func (emptyCtx) Done() <-chan struct{} {
188
+ return nil
189
+ }
190
+
191
+ func (emptyCtx) Err() error {
192
+ return nil
193
+ }
194
+
195
+ func (emptyCtx) Value(key any) any {
196
+ return nil
197
+ }
198
+
199
+ type backgroundCtx struct{ emptyCtx }
200
+
201
+ func (backgroundCtx) String() string {
202
+ return "context.Background"
203
+ }
204
+
205
+ type todoCtx struct{ emptyCtx }
206
+
207
+ func (todoCtx) String() string {
208
+ return "context.TODO"
209
+ }
210
+
211
+ // Background returns a non-nil, empty [Context]. It is never canceled, has no
212
+ // values, and has no deadline. It is typically used by the main function,
213
+ // initialization, and tests, and as the top-level Context for incoming
214
+ // requests.
215
+ func Background() Context {
216
+ return backgroundCtx{}
217
+ }
218
+
219
+ // TODO returns a non-nil, empty [Context]. Code should use context.TODO when
220
+ // it's unclear which Context to use or it is not yet available (because the
221
+ // surrounding function has not yet been extended to accept a Context
222
+ // parameter).
223
+ func TODO() Context {
224
+ return todoCtx{}
225
+ }
226
+
227
+ // A CancelFunc tells an operation to abandon its work.
228
+ // A CancelFunc does not wait for the work to stop.
229
+ // A CancelFunc may be called by multiple goroutines simultaneously.
230
+ // After the first call, subsequent calls to a CancelFunc do nothing.
231
+ type CancelFunc func()
232
+
233
+ // WithCancel returns a derived context that points to the parent context
234
+ // but has a new Done channel. The returned context's Done channel is closed
235
+ // when the returned cancel function is called or when the parent context's
236
+ // Done channel is closed, whichever happens first.
237
+ //
238
+ // Canceling this context releases resources associated with it, so code should
239
+ // call cancel as soon as the operations running in this [Context] complete.
240
+ func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
241
+ c := withCancel(parent)
242
+ return c, func() { c.cancel(true, Canceled, nil) }
243
+ }
244
+
245
+ // A CancelCauseFunc behaves like a [CancelFunc] but additionally sets the cancellation cause.
246
+ // This cause can be retrieved by calling [Cause] on the canceled Context or on
247
+ // any of its derived Contexts.
248
+ //
249
+ // If the context has already been canceled, CancelCauseFunc does not set the cause.
250
+ // For example, if childContext is derived from parentContext:
251
+ // - if parentContext is canceled with cause1 before childContext is canceled with cause2,
252
+ // then Cause(parentContext) == Cause(childContext) == cause1
253
+ // - if childContext is canceled with cause2 before parentContext is canceled with cause1,
254
+ // then Cause(parentContext) == cause1 and Cause(childContext) == cause2
255
+ type CancelCauseFunc func(cause error)
256
+
257
+ // WithCancelCause behaves like [WithCancel] but returns a [CancelCauseFunc] instead of a [CancelFunc].
258
+ // Calling cancel with a non-nil error (the "cause") records that error in ctx;
259
+ // it can then be retrieved using Cause(ctx).
260
+ // Calling cancel with nil sets the cause to Canceled.
261
+ //
262
+ // Example use:
263
+ //
264
+ // ctx, cancel := context.WithCancelCause(parent)
265
+ // cancel(myError)
266
+ // ctx.Err() // returns context.Canceled
267
+ // context.Cause(ctx) // returns myError
268
+ func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc) {
269
+ c := withCancel(parent)
270
+ return c, func(cause error) { c.cancel(true, Canceled, cause) }
271
+ }
272
+
273
+ func withCancel(parent Context) *cancelCtx {
274
+ if parent == nil {
275
+ panic("cannot create context from nil parent")
276
+ }
277
+ c := &cancelCtx{}
278
+ c.propagateCancel(parent, c)
279
+ return c
280
+ }
281
+
282
+ // Cause returns a non-nil error explaining why c was canceled.
283
+ // The first cancellation of c or one of its parents sets the cause.
284
+ // If that cancellation happened via a call to CancelCauseFunc(err),
285
+ // then [Cause] returns err.
286
+ // Otherwise Cause(c) returns the same value as c.Err().
287
+ // Cause returns nil if c has not been canceled yet.
288
+ func Cause(c Context) error {
289
+ err := c.Err()
290
+ if err == nil {
291
+ return nil
292
+ }
293
+ if cc, ok := c.Value(&cancelCtxKey).(*cancelCtx); ok {
294
+ cc.mu.Lock()
295
+ cause := cc.cause
296
+ cc.mu.Unlock()
297
+ if cause != nil {
298
+ return cause
299
+ }
300
+ // The parent cancelCtx doesn't have a cause,
301
+ // so c must have been canceled in some custom context implementation.
302
+ }
303
+ // We don't have a cause to return from a parent cancelCtx,
304
+ // so return the context's error.
305
+ return err
306
+ }
307
+
308
+ // AfterFunc arranges to call f in its own goroutine after ctx is canceled.
309
+ // If ctx is already canceled, AfterFunc calls f immediately in its own goroutine.
310
+ //
311
+ // Multiple calls to AfterFunc on a context operate independently;
312
+ // one does not replace another.
313
+ //
314
+ // Calling the returned stop function stops the association of ctx with f.
315
+ // It returns true if the call stopped f from being run.
316
+ // If stop returns false,
317
+ // either the context is canceled and f has been started in its own goroutine;
318
+ // or f was already stopped.
319
+ // The stop function does not wait for f to complete before returning.
320
+ // If the caller needs to know whether f is completed,
321
+ // it must coordinate with f explicitly.
322
+ //
323
+ // If ctx has a "AfterFunc(func()) func() bool" method,
324
+ // AfterFunc will use it to schedule the call.
325
+ func AfterFunc(ctx Context, f func()) (stop func() bool) {
326
+ a := &afterFuncCtx{
327
+ f: f,
328
+ }
329
+ a.cancelCtx.propagateCancel(ctx, a)
330
+ return func() bool {
331
+ stopped := false
332
+ a.once.Do(func() {
333
+ stopped = true
334
+ })
335
+ if stopped {
336
+ a.cancel(true, Canceled, nil)
337
+ }
338
+ return stopped
339
+ }
340
+ }
341
+
342
+ type afterFuncer interface {
343
+ AfterFunc(func()) func() bool
344
+ }
345
+
346
+ type afterFuncCtx struct {
347
+ cancelCtx
348
+ once sync.Once // either starts running f or stops f from running
349
+ f func()
350
+ }
351
+
352
+ func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error) {
353
+ a.cancelCtx.cancel(false, err, cause)
354
+ if removeFromParent {
355
+ removeChild(a.Context, a)
356
+ }
357
+ a.once.Do(func() {
358
+ go a.f()
359
+ })
360
+ }
361
+
362
+ // A stopCtx is used as the parent context of a cancelCtx when
363
+ // an AfterFunc has been registered with the parent.
364
+ // It holds the stop function used to unregister the AfterFunc.
365
+ type stopCtx struct {
366
+ Context
367
+ stop func() bool
368
+ }
369
+
370
+ // goroutines counts the number of goroutines ever created; for testing.
371
+ var goroutines atomic.Int32
372
+
373
+ // &cancelCtxKey is the key that a cancelCtx returns itself for.
374
+ var cancelCtxKey int
375
+
376
+ // parentCancelCtx returns the underlying *cancelCtx for parent.
377
+ // It does this by looking up parent.Value(&cancelCtxKey) to find
378
+ // the innermost enclosing *cancelCtx and then checking whether
379
+ // parent.Done() matches that *cancelCtx. (If not, the *cancelCtx
380
+ // has been wrapped in a custom implementation providing a
381
+ // different done channel, in which case we should not bypass it.)
382
+ func parentCancelCtx(parent Context) (*cancelCtx, bool) {
383
+ done := parent.Done()
384
+ if done == closedchan || done == nil {
385
+ return nil, false
386
+ }
387
+ p, ok := parent.Value(&cancelCtxKey).(*cancelCtx)
388
+ if !ok {
389
+ return nil, false
390
+ }
391
+ pdone, _ := p.done.Load().(chan struct{})
392
+ if pdone != done {
393
+ return nil, false
394
+ }
395
+ return p, true
396
+ }
397
+
398
+ // removeChild removes a context from its parent.
399
+ func removeChild(parent Context, child canceler) {
400
+ if s, ok := parent.(stopCtx); ok {
401
+ s.stop()
402
+ return
403
+ }
404
+ p, ok := parentCancelCtx(parent)
405
+ if !ok {
406
+ return
407
+ }
408
+ p.mu.Lock()
409
+ if p.children != nil {
410
+ delete(p.children, child)
411
+ }
412
+ p.mu.Unlock()
413
+ }
414
+
415
+ // A canceler is a context type that can be canceled directly. The
416
+ // implementations are *cancelCtx and *timerCtx.
417
+ type canceler interface {
418
+ cancel(removeFromParent bool, err, cause error)
419
+ Done() <-chan struct{}
420
+ }
421
+
422
+ // closedchan is a reusable closed channel.
423
+ var closedchan = make(chan struct{})
424
+
425
+ func init() {
426
+ close(closedchan)
427
+ }
428
+
429
+ // A cancelCtx can be canceled. When canceled, it also cancels any children
430
+ // that implement canceler.
431
+ type cancelCtx struct {
432
+ Context
433
+
434
+ mu sync.Mutex // protects following fields
435
+ done atomic.Value // of chan struct{}, created lazily, closed by first cancel call
436
+ children map[canceler]struct{} // set to nil by the first cancel call
437
+ err atomic.Value // set to non-nil by the first cancel call
438
+ cause error // set to non-nil by the first cancel call
439
+ }
440
+
441
+ func (c *cancelCtx) Value(key any) any {
442
+ if key == &cancelCtxKey {
443
+ return c
444
+ }
445
+ return value(c.Context, key)
446
+ }
447
+
448
+ func (c *cancelCtx) Done() <-chan struct{} {
449
+ d := c.done.Load()
450
+ if d != nil {
451
+ return d.(chan struct{})
452
+ }
453
+ c.mu.Lock()
454
+ defer c.mu.Unlock()
455
+ d = c.done.Load()
456
+ if d == nil {
457
+ d = make(chan struct{})
458
+ c.done.Store(d)
459
+ }
460
+ return d.(chan struct{})
461
+ }
462
+
463
+ func (c *cancelCtx) Err() error {
464
+ // An atomic load is ~5x faster than a mutex, which can matter in tight loops.
465
+ if err := c.err.Load(); err != nil {
466
+ // Ensure the done channel has been closed before returning a non-nil error.
467
+ <-c.Done()
468
+ return err.(error)
469
+ }
470
+ return nil
471
+ }
472
+
473
+ // propagateCancel arranges for child to be canceled when parent is.
474
+ // It sets the parent context of cancelCtx.
475
+ func (c *cancelCtx) propagateCancel(parent Context, child canceler) {
476
+ c.Context = parent
477
+
478
+ done := parent.Done()
479
+ if done == nil {
480
+ return // parent is never canceled
481
+ }
482
+
483
+ select {
484
+ case <-done:
485
+ // parent is already canceled
486
+ child.cancel(false, parent.Err(), Cause(parent))
487
+ return
488
+ default:
489
+ }
490
+
491
+ if p, ok := parentCancelCtx(parent); ok {
492
+ // parent is a *cancelCtx, or derives from one.
493
+ p.mu.Lock()
494
+ if err := p.err.Load(); err != nil {
495
+ // parent has already been canceled
496
+ child.cancel(false, err.(error), p.cause)
497
+ } else {
498
+ if p.children == nil {
499
+ p.children = make(map[canceler]struct{})
500
+ }
501
+ p.children[child] = struct{}{}
502
+ }
503
+ p.mu.Unlock()
504
+ return
505
+ }
506
+
507
+ if a, ok := parent.(afterFuncer); ok {
508
+ // parent implements an AfterFunc method.
509
+ c.mu.Lock()
510
+ stop := a.AfterFunc(func() {
511
+ child.cancel(false, parent.Err(), Cause(parent))
512
+ })
513
+ c.Context = stopCtx{
514
+ Context: parent,
515
+ stop: stop,
516
+ }
517
+ c.mu.Unlock()
518
+ return
519
+ }
520
+
521
+ goroutines.Add(1)
522
+ go func() {
523
+ select {
524
+ case <-parent.Done():
525
+ child.cancel(false, parent.Err(), Cause(parent))
526
+ case <-child.Done():
527
+ }
528
+ }()
529
+ }
530
+
531
+ type stringer interface {
532
+ String() string
533
+ }
534
+
535
+ func contextName(c Context) string {
536
+ if s, ok := c.(stringer); ok {
537
+ return s.String()
538
+ }
539
+ return reflectlite.TypeOf(c).String()
540
+ }
541
+
542
+ func (c *cancelCtx) String() string {
543
+ return contextName(c.Context) + ".WithCancel"
544
+ }
545
+
546
+ // cancel closes c.done, cancels each of c's children, and, if
547
+ // removeFromParent is true, removes c from its parent's children.
548
+ // cancel sets c.cause to cause if this is the first time c is canceled.
549
+ func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {
550
+ if err == nil {
551
+ panic("context: internal error: missing cancel error")
552
+ }
553
+ if cause == nil {
554
+ cause = err
555
+ }
556
+ c.mu.Lock()
557
+ if c.err.Load() != nil {
558
+ c.mu.Unlock()
559
+ return // already canceled
560
+ }
561
+ c.err.Store(err)
562
+ c.cause = cause
563
+ d, _ := c.done.Load().(chan struct{})
564
+ if d == nil {
565
+ c.done.Store(closedchan)
566
+ } else {
567
+ close(d)
568
+ }
569
+ for child := range c.children {
570
+ // NOTE: acquiring the child's lock while holding parent's lock.
571
+ child.cancel(false, err, cause)
572
+ }
573
+ c.children = nil
574
+ c.mu.Unlock()
575
+
576
+ if removeFromParent {
577
+ removeChild(c.Context, c)
578
+ }
579
+ }
580
+
581
+ // WithoutCancel returns a derived context that points to the parent context
582
+ // and is not canceled when parent is canceled.
583
+ // The returned context returns no Deadline or Err, and its Done channel is nil.
584
+ // Calling [Cause] on the returned context returns nil.
585
+ func WithoutCancel(parent Context) Context {
586
+ if parent == nil {
587
+ panic("cannot create context from nil parent")
588
+ }
589
+ return withoutCancelCtx{parent}
590
+ }
591
+
592
+ type withoutCancelCtx struct {
593
+ c Context
594
+ }
595
+
596
+ func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) {
597
+ return
598
+ }
599
+
600
+ func (withoutCancelCtx) Done() <-chan struct{} {
601
+ return nil
602
+ }
603
+
604
+ func (withoutCancelCtx) Err() error {
605
+ return nil
606
+ }
607
+
608
+ func (c withoutCancelCtx) Value(key any) any {
609
+ return value(c, key)
610
+ }
611
+
612
+ func (c withoutCancelCtx) String() string {
613
+ return contextName(c.c) + ".WithoutCancel"
614
+ }
615
+
616
+ // WithDeadline returns a derived context that points to the parent context
617
+ // but has the deadline adjusted to be no later than d. If the parent's
618
+ // deadline is already earlier than d, WithDeadline(parent, d) is semantically
619
+ // equivalent to parent. The returned [Context.Done] channel is closed when
620
+ // the deadline expires, when the returned cancel function is called,
621
+ // or when the parent context's Done channel is closed, whichever happens first.
622
+ //
623
+ // Canceling this context releases resources associated with it, so code should
624
+ // call cancel as soon as the operations running in this [Context] complete.
625
+ func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
626
+ return WithDeadlineCause(parent, d, nil)
627
+ }
628
+
629
+ // WithDeadlineCause behaves like [WithDeadline] but also sets the cause of the
630
+ // returned Context when the deadline is exceeded. The returned [CancelFunc] does
631
+ // not set the cause.
632
+ func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc) {
633
+ if parent == nil {
634
+ panic("cannot create context from nil parent")
635
+ }
636
+ if cur, ok := parent.Deadline(); ok && cur.Before(d) {
637
+ // The current deadline is already sooner than the new one.
638
+ return WithCancel(parent)
639
+ }
640
+ c := &timerCtx{
641
+ deadline: d,
642
+ }
643
+ c.cancelCtx.propagateCancel(parent, c)
644
+ dur := time.Until(d)
645
+ if dur <= 0 {
646
+ c.cancel(true, DeadlineExceeded, cause) // deadline has already passed
647
+ return c, func() { c.cancel(false, Canceled, nil) }
648
+ }
649
+ c.mu.Lock()
650
+ defer c.mu.Unlock()
651
+ if c.err.Load() == nil {
652
+ c.timer = time.AfterFunc(dur, func() {
653
+ c.cancel(true, DeadlineExceeded, cause)
654
+ })
655
+ }
656
+ return c, func() { c.cancel(true, Canceled, nil) }
657
+ }
658
+
659
+ // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
660
+ // implement Done and Err. It implements cancel by stopping its timer then
661
+ // delegating to cancelCtx.cancel.
662
+ type timerCtx struct {
663
+ cancelCtx
664
+ timer *time.Timer // Under cancelCtx.mu.
665
+
666
+ deadline time.Time
667
+ }
668
+
669
+ func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
670
+ return c.deadline, true
671
+ }
672
+
673
+ func (c *timerCtx) String() string {
674
+ return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
675
+ c.deadline.String() + " [" +
676
+ time.Until(c.deadline).String() + "])"
677
+ }
678
+
679
+ func (c *timerCtx) cancel(removeFromParent bool, err, cause error) {
680
+ c.cancelCtx.cancel(false, err, cause)
681
+ if removeFromParent {
682
+ // Remove this timerCtx from its parent cancelCtx's children.
683
+ removeChild(c.cancelCtx.Context, c)
684
+ }
685
+ c.mu.Lock()
686
+ if c.timer != nil {
687
+ c.timer.Stop()
688
+ c.timer = nil
689
+ }
690
+ c.mu.Unlock()
691
+ }
692
+
693
+ // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
694
+ //
695
+ // Canceling this context releases resources associated with it, so code should
696
+ // call cancel as soon as the operations running in this [Context] complete:
697
+ //
698
+ // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
699
+ // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
700
+ // defer cancel() // releases resources if slowOperation completes before timeout elapses
701
+ // return slowOperation(ctx)
702
+ // }
703
+ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
704
+ return WithDeadline(parent, time.Now().Add(timeout))
705
+ }
706
+
707
+ // WithTimeoutCause behaves like [WithTimeout] but also sets the cause of the
708
+ // returned Context when the timeout expires. The returned [CancelFunc] does
709
+ // not set the cause.
710
+ func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) {
711
+ return WithDeadlineCause(parent, time.Now().Add(timeout), cause)
712
+ }
713
+
714
+ // WithValue returns a derived context that points to the parent Context.
715
+ // In the derived context, the value associated with key is val.
716
+ //
717
+ // Use context Values only for request-scoped data that transits processes and
718
+ // APIs, not for passing optional parameters to functions.
719
+ //
720
+ // The provided key must be comparable and should not be of type
721
+ // string or any other built-in type to avoid collisions between
722
+ // packages using context. Users of WithValue should define their own
723
+ // types for keys. To avoid allocating when assigning to an
724
+ // interface{}, context keys often have concrete type
725
+ // struct{}. Alternatively, exported context key variables' static
726
+ // type should be a pointer or interface.
727
+ func WithValue(parent Context, key, val any) Context {
728
+ if parent == nil {
729
+ panic("cannot create context from nil parent")
730
+ }
731
+ if key == nil {
732
+ panic("nil key")
733
+ }
734
+ if !reflectlite.TypeOf(key).Comparable() {
735
+ panic("key is not comparable")
736
+ }
737
+ return &valueCtx{parent, key, val}
738
+ }
739
+
740
+ // A valueCtx carries a key-value pair. It implements Value for that key and
741
+ // delegates all other calls to the embedded Context.
742
+ type valueCtx struct {
743
+ Context
744
+ key, val any
745
+ }
746
+
747
+ // stringify tries a bit to stringify v, without using fmt, since we don't
748
+ // want context depending on the unicode tables. This is only used by
749
+ // *valueCtx.String().
750
+ func stringify(v any) string {
751
+ switch s := v.(type) {
752
+ case stringer:
753
+ return s.String()
754
+ case string:
755
+ return s
756
+ case nil:
757
+ return "<nil>"
758
+ }
759
+ return reflectlite.TypeOf(v).String()
760
+ }
761
+
762
+ func (c *valueCtx) String() string {
763
+ return contextName(c.Context) + ".WithValue(" +
764
+ stringify(c.key) + ", " +
765
+ stringify(c.val) + ")"
766
+ }
767
+
768
+ func (c *valueCtx) Value(key any) any {
769
+ if c.key == key {
770
+ return c.val
771
+ }
772
+ return value(c.Context, key)
773
+ }
774
+
775
+ func value(c Context, key any) any {
776
+ for {
777
+ switch ctx := c.(type) {
778
+ case *valueCtx:
779
+ if key == ctx.key {
780
+ return ctx.val
781
+ }
782
+ c = ctx.Context
783
+ case *cancelCtx:
784
+ if key == &cancelCtxKey {
785
+ return c
786
+ }
787
+ c = ctx.Context
788
+ case withoutCancelCtx:
789
+ if key == &cancelCtxKey {
790
+ // This implements Cause(ctx) == nil
791
+ // when ctx is created using WithoutCancel.
792
+ return nil
793
+ }
794
+ c = ctx.c
795
+ case *timerCtx:
796
+ if key == &cancelCtxKey {
797
+ return &ctx.cancelCtx
798
+ }
799
+ c = ctx.Context
800
+ case backgroundCtx, todoCtx:
801
+ return nil
802
+ default:
803
+ return c.Value(key)
804
+ }
805
+ }
806
+ }
go/src/context/context_test.go ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context
6
+
7
+ // Tests in package context cannot depend directly on package testing due to an import cycle.
8
+ // If your test requires access to unexported members of the context package,
9
+ // add your test below as `func XTestFoo(t testingT)` and add a `TestFoo` to x_test.go
10
+ // that calls it. Otherwise, write a regular test in a test.go file in package context_test.
11
+
12
+ import (
13
+ "time"
14
+ )
15
+
16
+ type testingT interface {
17
+ Deadline() (time.Time, bool)
18
+ Error(args ...any)
19
+ Errorf(format string, args ...any)
20
+ Fail()
21
+ FailNow()
22
+ Failed() bool
23
+ Fatal(args ...any)
24
+ Fatalf(format string, args ...any)
25
+ Helper()
26
+ Log(args ...any)
27
+ Logf(format string, args ...any)
28
+ Name() string
29
+ Parallel()
30
+ Skip(args ...any)
31
+ SkipNow()
32
+ Skipf(format string, args ...any)
33
+ Skipped() bool
34
+ }
35
+
36
+ const veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time
37
+
38
+ func contains(m map[canceler]struct{}, key canceler) bool {
39
+ _, ret := m[key]
40
+ return ret
41
+ }
42
+
43
+ func XTestParentFinishesChild(t testingT) {
44
+ // Context tree:
45
+ // parent -> cancelChild
46
+ // parent -> valueChild -> timerChild
47
+ // parent -> afterChild
48
+ parent, cancel := WithCancel(Background())
49
+ cancelChild, stop := WithCancel(parent)
50
+ defer stop()
51
+ valueChild := WithValue(parent, "key", "value")
52
+ timerChild, stop := WithTimeout(valueChild, veryLongDuration)
53
+ defer stop()
54
+ afterStop := AfterFunc(parent, func() {})
55
+ defer afterStop()
56
+
57
+ select {
58
+ case x := <-parent.Done():
59
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
60
+ case x := <-cancelChild.Done():
61
+ t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x)
62
+ case x := <-timerChild.Done():
63
+ t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x)
64
+ case x := <-valueChild.Done():
65
+ t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x)
66
+ default:
67
+ }
68
+
69
+ // The parent's children should contain the three cancelable children.
70
+ pc := parent.(*cancelCtx)
71
+ cc := cancelChild.(*cancelCtx)
72
+ tc := timerChild.(*timerCtx)
73
+ pc.mu.Lock()
74
+ var ac *afterFuncCtx
75
+ for c := range pc.children {
76
+ if a, ok := c.(*afterFuncCtx); ok {
77
+ ac = a
78
+ break
79
+ }
80
+ }
81
+ if len(pc.children) != 3 || !contains(pc.children, cc) || !contains(pc.children, tc) || ac == nil {
82
+ t.Errorf("bad linkage: pc.children = %v, want %v, %v, and an afterFunc",
83
+ pc.children, cc, tc)
84
+ }
85
+ pc.mu.Unlock()
86
+
87
+ if p, ok := parentCancelCtx(cc.Context); !ok || p != pc {
88
+ t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc)
89
+ }
90
+ if p, ok := parentCancelCtx(tc.Context); !ok || p != pc {
91
+ t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc)
92
+ }
93
+ if p, ok := parentCancelCtx(ac.Context); !ok || p != pc {
94
+ t.Errorf("bad linkage: parentCancelCtx(afterChild.Context) = %v, %v want %v, true", p, ok, pc)
95
+ }
96
+
97
+ cancel()
98
+
99
+ pc.mu.Lock()
100
+ if len(pc.children) != 0 {
101
+ t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children)
102
+ }
103
+ pc.mu.Unlock()
104
+
105
+ // parent and children should all be finished.
106
+ check := func(ctx Context, name string) {
107
+ select {
108
+ case <-ctx.Done():
109
+ default:
110
+ t.Errorf("<-%s.Done() blocked, but shouldn't have", name)
111
+ }
112
+ if e := ctx.Err(); e != Canceled {
113
+ t.Errorf("%s.Err() == %v want %v", name, e, Canceled)
114
+ }
115
+ }
116
+ check(parent, "parent")
117
+ check(cancelChild, "cancelChild")
118
+ check(valueChild, "valueChild")
119
+ check(timerChild, "timerChild")
120
+
121
+ // WithCancel should return a canceled context on a canceled parent.
122
+ precanceledChild := WithValue(parent, "key", "value")
123
+ select {
124
+ case <-precanceledChild.Done():
125
+ default:
126
+ t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have")
127
+ }
128
+ if e := precanceledChild.Err(); e != Canceled {
129
+ t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled)
130
+ }
131
+ }
132
+
133
+ func XTestChildFinishesFirst(t testingT) {
134
+ cancelable, stop := WithCancel(Background())
135
+ defer stop()
136
+ for _, parent := range []Context{Background(), cancelable} {
137
+ child, cancel := WithCancel(parent)
138
+
139
+ select {
140
+ case x := <-parent.Done():
141
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
142
+ case x := <-child.Done():
143
+ t.Errorf("<-child.Done() == %v want nothing (it should block)", x)
144
+ default:
145
+ }
146
+
147
+ cc := child.(*cancelCtx)
148
+ pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background()
149
+ if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) {
150
+ t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok)
151
+ }
152
+
153
+ if pcok {
154
+ pc.mu.Lock()
155
+ if len(pc.children) != 1 || !contains(pc.children, cc) {
156
+ t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc)
157
+ }
158
+ pc.mu.Unlock()
159
+ }
160
+
161
+ cancel()
162
+
163
+ if pcok {
164
+ pc.mu.Lock()
165
+ if len(pc.children) != 0 {
166
+ t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children)
167
+ }
168
+ pc.mu.Unlock()
169
+ }
170
+
171
+ // child should be finished.
172
+ select {
173
+ case <-child.Done():
174
+ default:
175
+ t.Errorf("<-child.Done() blocked, but shouldn't have")
176
+ }
177
+ if e := child.Err(); e != Canceled {
178
+ t.Errorf("child.Err() == %v want %v", e, Canceled)
179
+ }
180
+
181
+ // parent should not be finished.
182
+ select {
183
+ case x := <-parent.Done():
184
+ t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
185
+ default:
186
+ }
187
+ if e := parent.Err(); e != nil {
188
+ t.Errorf("parent.Err() == %v want nil", e)
189
+ }
190
+ }
191
+ }
192
+
193
+ func XTestCancelRemoves(t testingT) {
194
+ checkChildren := func(when string, ctx Context, want int) {
195
+ if got := len(ctx.(*cancelCtx).children); got != want {
196
+ t.Errorf("%s: context has %d children, want %d", when, got, want)
197
+ }
198
+ }
199
+
200
+ ctx, _ := WithCancel(Background())
201
+ checkChildren("after creation", ctx, 0)
202
+ _, cancel := WithCancel(ctx)
203
+ checkChildren("with WithCancel child ", ctx, 1)
204
+ cancel()
205
+ checkChildren("after canceling WithCancel child", ctx, 0)
206
+
207
+ ctx, _ = WithCancel(Background())
208
+ checkChildren("after creation", ctx, 0)
209
+ _, cancel = WithTimeout(ctx, 60*time.Minute)
210
+ checkChildren("with WithTimeout child ", ctx, 1)
211
+ cancel()
212
+ checkChildren("after canceling WithTimeout child", ctx, 0)
213
+
214
+ ctx, _ = WithCancel(Background())
215
+ checkChildren("after creation", ctx, 0)
216
+ stop := AfterFunc(ctx, func() {})
217
+ checkChildren("with AfterFunc child ", ctx, 1)
218
+ stop()
219
+ checkChildren("after stopping AfterFunc child ", ctx, 0)
220
+ }
221
+
222
+ type myCtx struct {
223
+ Context
224
+ }
225
+
226
+ type myDoneCtx struct {
227
+ Context
228
+ }
229
+
230
+ func (d *myDoneCtx) Done() <-chan struct{} {
231
+ c := make(chan struct{})
232
+ return c
233
+ }
234
+ func XTestCustomContextGoroutines(t testingT) {
235
+ g := goroutines.Load()
236
+ checkNoGoroutine := func() {
237
+ t.Helper()
238
+ now := goroutines.Load()
239
+ if now != g {
240
+ t.Fatalf("%d goroutines created", now-g)
241
+ }
242
+ }
243
+ checkCreatedGoroutine := func() {
244
+ t.Helper()
245
+ now := goroutines.Load()
246
+ if now != g+1 {
247
+ t.Fatalf("%d goroutines created, want 1", now-g)
248
+ }
249
+ g = now
250
+ }
251
+
252
+ _, cancel0 := WithCancel(&myDoneCtx{Background()})
253
+ cancel0()
254
+ checkCreatedGoroutine()
255
+
256
+ _, cancel0 = WithTimeout(&myDoneCtx{Background()}, veryLongDuration)
257
+ cancel0()
258
+ checkCreatedGoroutine()
259
+
260
+ checkNoGoroutine()
261
+ defer checkNoGoroutine()
262
+
263
+ ctx1, cancel1 := WithCancel(Background())
264
+ defer cancel1()
265
+ checkNoGoroutine()
266
+
267
+ ctx2 := &myCtx{ctx1}
268
+ ctx3, cancel3 := WithCancel(ctx2)
269
+ defer cancel3()
270
+ checkNoGoroutine()
271
+
272
+ _, cancel3b := WithCancel(&myDoneCtx{ctx2})
273
+ defer cancel3b()
274
+ checkCreatedGoroutine() // ctx1 is not providing Done, must not be used
275
+
276
+ ctx4, cancel4 := WithTimeout(ctx3, veryLongDuration)
277
+ defer cancel4()
278
+ checkNoGoroutine()
279
+
280
+ ctx5, cancel5 := WithCancel(ctx4)
281
+ defer cancel5()
282
+ checkNoGoroutine()
283
+
284
+ cancel5()
285
+ checkNoGoroutine()
286
+
287
+ _, cancel6 := WithTimeout(ctx5, veryLongDuration)
288
+ defer cancel6()
289
+ checkNoGoroutine()
290
+
291
+ // Check applied to canceled context.
292
+ cancel6()
293
+ cancel1()
294
+ _, cancel7 := WithCancel(ctx5)
295
+ defer cancel7()
296
+ checkNoGoroutine()
297
+ }
go/src/context/example_test.go ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context_test
6
+
7
+ import (
8
+ "context"
9
+ "errors"
10
+ "fmt"
11
+ "net"
12
+ "sync"
13
+ "time"
14
+ )
15
+
16
+ var neverReady = make(chan struct{}) // never closed
17
+
18
+ // This example demonstrates the use of a cancelable context to prevent a
19
+ // goroutine leak. By the end of the example function, the goroutine started
20
+ // by gen will return without leaking.
21
+ func ExampleWithCancel() {
22
+ // gen generates integers in a separate goroutine and
23
+ // sends them to the returned channel.
24
+ // The callers of gen need to cancel the context once
25
+ // they are done consuming generated integers not to leak
26
+ // the internal goroutine started by gen.
27
+ gen := func(ctx context.Context) <-chan int {
28
+ dst := make(chan int)
29
+ n := 1
30
+ go func() {
31
+ for {
32
+ select {
33
+ case <-ctx.Done():
34
+ return // returning not to leak the goroutine
35
+ case dst <- n:
36
+ n++
37
+ }
38
+ }
39
+ }()
40
+ return dst
41
+ }
42
+
43
+ ctx, cancel := context.WithCancel(context.Background())
44
+ defer cancel() // cancel when we are finished consuming integers
45
+
46
+ for n := range gen(ctx) {
47
+ fmt.Println(n)
48
+ if n == 5 {
49
+ break
50
+ }
51
+ }
52
+ // Output:
53
+ // 1
54
+ // 2
55
+ // 3
56
+ // 4
57
+ // 5
58
+ }
59
+
60
+ // This example passes a context with an arbitrary deadline to tell a blocking
61
+ // function that it should abandon its work as soon as it gets to it.
62
+ func ExampleWithDeadline() {
63
+ d := time.Now().Add(shortDuration)
64
+ ctx, cancel := context.WithDeadline(context.Background(), d)
65
+
66
+ // Even though ctx will be expired, it is good practice to call its
67
+ // cancellation function in any case. Failure to do so may keep the
68
+ // context and its parent alive longer than necessary.
69
+ defer cancel()
70
+
71
+ select {
72
+ case <-neverReady:
73
+ fmt.Println("ready")
74
+ case <-ctx.Done():
75
+ fmt.Println(ctx.Err())
76
+ }
77
+
78
+ // Output:
79
+ // context deadline exceeded
80
+ }
81
+
82
+ // This example passes a context with a timeout to tell a blocking function that
83
+ // it should abandon its work after the timeout elapses.
84
+ func ExampleWithTimeout() {
85
+ // Pass a context with a timeout to tell a blocking function that it
86
+ // should abandon its work after the timeout elapses.
87
+ ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
88
+ defer cancel()
89
+
90
+ select {
91
+ case <-neverReady:
92
+ fmt.Println("ready")
93
+ case <-ctx.Done():
94
+ fmt.Println(ctx.Err()) // prints "context deadline exceeded"
95
+ }
96
+
97
+ // Output:
98
+ // context deadline exceeded
99
+ }
100
+
101
+ // This example demonstrates how a value can be passed to the context
102
+ // and also how to retrieve it if it exists.
103
+ func ExampleWithValue() {
104
+ type favContextKey string
105
+
106
+ f := func(ctx context.Context, k favContextKey) {
107
+ if v := ctx.Value(k); v != nil {
108
+ fmt.Println("found value:", v)
109
+ return
110
+ }
111
+ fmt.Println("key not found:", k)
112
+ }
113
+
114
+ k := favContextKey("language")
115
+ ctx := context.WithValue(context.Background(), k, "Go")
116
+
117
+ f(ctx, k)
118
+ f(ctx, favContextKey("color"))
119
+
120
+ // Output:
121
+ // found value: Go
122
+ // key not found: color
123
+ }
124
+
125
+ // This example uses AfterFunc to define a function which waits on a sync.Cond,
126
+ // stopping the wait when a context is canceled.
127
+ func ExampleAfterFunc_cond() {
128
+ waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error {
129
+ stopf := context.AfterFunc(ctx, func() {
130
+ // We need to acquire cond.L here to be sure that the Broadcast
131
+ // below won't occur before the call to Wait, which would result
132
+ // in a missed signal (and deadlock).
133
+ cond.L.Lock()
134
+ defer cond.L.Unlock()
135
+
136
+ // If multiple goroutines are waiting on cond simultaneously,
137
+ // we need to make sure we wake up exactly this one.
138
+ // That means that we need to Broadcast to all of the goroutines,
139
+ // which will wake them all up.
140
+ //
141
+ // If there are N concurrent calls to waitOnCond, each of the goroutines
142
+ // will spuriously wake up O(N) other goroutines that aren't ready yet,
143
+ // so this will cause the overall CPU cost to be O(N²).
144
+ cond.Broadcast()
145
+ })
146
+ defer stopf()
147
+
148
+ // Since the wakeups are using Broadcast instead of Signal, this call to
149
+ // Wait may unblock due to some other goroutine's context being canceled,
150
+ // so to be sure that ctx is actually canceled we need to check it in a loop.
151
+ for !conditionMet() {
152
+ cond.Wait()
153
+ if ctx.Err() != nil {
154
+ return ctx.Err()
155
+ }
156
+ }
157
+
158
+ return nil
159
+ }
160
+
161
+ cond := sync.NewCond(new(sync.Mutex))
162
+
163
+ var wg sync.WaitGroup
164
+ for i := 0; i < 4; i++ {
165
+ wg.Add(1)
166
+ go func() {
167
+ defer wg.Done()
168
+
169
+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
170
+ defer cancel()
171
+
172
+ cond.L.Lock()
173
+ defer cond.L.Unlock()
174
+
175
+ err := waitOnCond(ctx, cond, func() bool { return false })
176
+ fmt.Println(err)
177
+ }()
178
+ }
179
+ wg.Wait()
180
+
181
+ // Output:
182
+ // context deadline exceeded
183
+ // context deadline exceeded
184
+ // context deadline exceeded
185
+ // context deadline exceeded
186
+ }
187
+
188
+ // This example uses AfterFunc to define a function which reads from a net.Conn,
189
+ // stopping the read when a context is canceled.
190
+ func ExampleAfterFunc_connection() {
191
+ readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) {
192
+ stopc := make(chan struct{})
193
+ stop := context.AfterFunc(ctx, func() {
194
+ conn.SetReadDeadline(time.Now())
195
+ close(stopc)
196
+ })
197
+ n, err = conn.Read(b)
198
+ if !stop() {
199
+ // The AfterFunc was started.
200
+ // Wait for it to complete, and reset the Conn's deadline.
201
+ <-stopc
202
+ conn.SetReadDeadline(time.Time{})
203
+ return n, ctx.Err()
204
+ }
205
+ return n, err
206
+ }
207
+
208
+ listener, err := net.Listen("tcp", "localhost:0")
209
+ if err != nil {
210
+ fmt.Println(err)
211
+ return
212
+ }
213
+ defer listener.Close()
214
+
215
+ conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String())
216
+ if err != nil {
217
+ fmt.Println(err)
218
+ return
219
+ }
220
+ defer conn.Close()
221
+
222
+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
223
+ defer cancel()
224
+
225
+ b := make([]byte, 1024)
226
+ _, err = readFromConn(ctx, conn, b)
227
+ fmt.Println(err)
228
+
229
+ // Output:
230
+ // context deadline exceeded
231
+ }
232
+
233
+ // This example uses AfterFunc to define a function which combines
234
+ // the cancellation signals of two Contexts.
235
+ func ExampleAfterFunc_merge() {
236
+ // mergeCancel returns a context that contains the values of ctx,
237
+ // and which is canceled when either ctx or cancelCtx is canceled.
238
+ mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
239
+ ctx, cancel := context.WithCancelCause(ctx)
240
+ stop := context.AfterFunc(cancelCtx, func() {
241
+ cancel(context.Cause(cancelCtx))
242
+ })
243
+ return ctx, func() {
244
+ stop()
245
+ cancel(context.Canceled)
246
+ }
247
+ }
248
+
249
+ ctx1, cancel1 := context.WithCancelCause(context.Background())
250
+ defer cancel1(errors.New("ctx1 canceled"))
251
+
252
+ ctx2, cancel2 := context.WithCancelCause(context.Background())
253
+
254
+ mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2)
255
+ defer mergedCancel()
256
+
257
+ cancel2(errors.New("ctx2 canceled"))
258
+ <-mergedCtx.Done()
259
+ fmt.Println(context.Cause(mergedCtx))
260
+
261
+ // Output:
262
+ // ctx2 canceled
263
+ }
go/src/context/net_test.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context_test
6
+
7
+ import (
8
+ "context"
9
+ "net"
10
+ "testing"
11
+ )
12
+
13
+ func TestDeadlineExceededIsNetError(t *testing.T) {
14
+ err, ok := context.DeadlineExceeded.(net.Error)
15
+ if !ok {
16
+ t.Fatal("DeadlineExceeded does not implement net.Error")
17
+ }
18
+ if !err.Timeout() || !err.Temporary() {
19
+ t.Fatalf("Timeout() = %v, Temporary() = %v, want true, true", err.Timeout(), err.Temporary())
20
+ }
21
+ }
go/src/context/x_test.go ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package context_test
6
+
7
+ import (
8
+ . "context"
9
+ "errors"
10
+ "fmt"
11
+ "internal/asan"
12
+ "math/rand"
13
+ "runtime"
14
+ "strings"
15
+ "sync"
16
+ "testing"
17
+ "time"
18
+ )
19
+
20
+ // Each XTestFoo in context_test.go must be called from a TestFoo here to run.
21
+ func TestParentFinishesChild(t *testing.T) {
22
+ XTestParentFinishesChild(t) // uses unexported context types
23
+ }
24
+ func TestChildFinishesFirst(t *testing.T) {
25
+ XTestChildFinishesFirst(t) // uses unexported context types
26
+ }
27
+ func TestCancelRemoves(t *testing.T) {
28
+ XTestCancelRemoves(t) // uses unexported context types
29
+ }
30
+ func TestCustomContextGoroutines(t *testing.T) {
31
+ XTestCustomContextGoroutines(t) // reads the context.goroutines counter
32
+ }
33
+
34
+ // The following are regular tests in package context_test.
35
+
36
+ // otherContext is a Context that's not one of the types defined in context.go.
37
+ // This lets us test code paths that differ based on the underlying type of the
38
+ // Context.
39
+ type otherContext struct {
40
+ Context
41
+ }
42
+
43
+ const (
44
+ shortDuration = 1 * time.Millisecond // a reasonable duration to block in a test
45
+ veryLongDuration = 1000 * time.Hour // an arbitrary upper bound on the test's running time
46
+ )
47
+
48
+ // quiescent returns an arbitrary duration by which the program should have
49
+ // completed any remaining work and reached a steady (idle) state.
50
+ func quiescent(t *testing.T) time.Duration {
51
+ deadline, ok := t.Deadline()
52
+ if !ok {
53
+ return 5 * time.Second
54
+ }
55
+
56
+ const arbitraryCleanupMargin = 1 * time.Second
57
+ return time.Until(deadline) - arbitraryCleanupMargin
58
+ }
59
+ func TestBackground(t *testing.T) {
60
+ c := Background()
61
+ if c == nil {
62
+ t.Fatalf("Background returned nil")
63
+ }
64
+ select {
65
+ case x := <-c.Done():
66
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
67
+ default:
68
+ }
69
+ if got, want := fmt.Sprint(c), "context.Background"; got != want {
70
+ t.Errorf("Background().String() = %q want %q", got, want)
71
+ }
72
+ }
73
+
74
+ func TestTODO(t *testing.T) {
75
+ c := TODO()
76
+ if c == nil {
77
+ t.Fatalf("TODO returned nil")
78
+ }
79
+ select {
80
+ case x := <-c.Done():
81
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
82
+ default:
83
+ }
84
+ if got, want := fmt.Sprint(c), "context.TODO"; got != want {
85
+ t.Errorf("TODO().String() = %q want %q", got, want)
86
+ }
87
+ }
88
+
89
+ func TestWithCancel(t *testing.T) {
90
+ c1, cancel := WithCancel(Background())
91
+
92
+ if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want {
93
+ t.Errorf("c1.String() = %q want %q", got, want)
94
+ }
95
+
96
+ o := otherContext{c1}
97
+ c2, _ := WithCancel(o)
98
+ contexts := []Context{c1, o, c2}
99
+
100
+ for i, c := range contexts {
101
+ if d := c.Done(); d == nil {
102
+ t.Errorf("c[%d].Done() == %v want non-nil", i, d)
103
+ }
104
+ if e := c.Err(); e != nil {
105
+ t.Errorf("c[%d].Err() == %v want nil", i, e)
106
+ }
107
+
108
+ select {
109
+ case x := <-c.Done():
110
+ t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
111
+ default:
112
+ }
113
+ }
114
+
115
+ cancel() // Should propagate synchronously.
116
+ for i, c := range contexts {
117
+ select {
118
+ case <-c.Done():
119
+ default:
120
+ t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i)
121
+ }
122
+ if e := c.Err(); e != Canceled {
123
+ t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled)
124
+ }
125
+ }
126
+ }
127
+
128
+ func testDeadline(c Context, name string, t *testing.T) {
129
+ t.Helper()
130
+ d := quiescent(t)
131
+ timer := time.NewTimer(d)
132
+ defer timer.Stop()
133
+ select {
134
+ case <-timer.C:
135
+ t.Fatalf("%s: context not timed out after %v", name, d)
136
+ case <-c.Done():
137
+ }
138
+ if e := c.Err(); e != DeadlineExceeded {
139
+ t.Errorf("%s: c.Err() == %v; want %v", name, e, DeadlineExceeded)
140
+ }
141
+ }
142
+
143
+ func TestDeadline(t *testing.T) {
144
+ t.Parallel()
145
+
146
+ c, _ := WithDeadline(Background(), time.Now().Add(shortDuration))
147
+ if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
148
+ t.Errorf("c.String() = %q want prefix %q", got, prefix)
149
+ }
150
+ testDeadline(c, "WithDeadline", t)
151
+
152
+ c, _ = WithDeadline(Background(), time.Now().Add(shortDuration))
153
+ o := otherContext{c}
154
+ testDeadline(o, "WithDeadline+otherContext", t)
155
+
156
+ c, _ = WithDeadline(Background(), time.Now().Add(shortDuration))
157
+ o = otherContext{c}
158
+ c, _ = WithDeadline(o, time.Now().Add(veryLongDuration))
159
+ testDeadline(c, "WithDeadline+otherContext+WithDeadline", t)
160
+
161
+ c, _ = WithDeadline(Background(), time.Now().Add(-shortDuration))
162
+ testDeadline(c, "WithDeadline+inthepast", t)
163
+
164
+ c, _ = WithDeadline(Background(), time.Now())
165
+ testDeadline(c, "WithDeadline+now", t)
166
+ }
167
+
168
+ func TestTimeout(t *testing.T) {
169
+ t.Parallel()
170
+
171
+ c, _ := WithTimeout(Background(), shortDuration)
172
+ if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
173
+ t.Errorf("c.String() = %q want prefix %q", got, prefix)
174
+ }
175
+ testDeadline(c, "WithTimeout", t)
176
+
177
+ c, _ = WithTimeout(Background(), shortDuration)
178
+ o := otherContext{c}
179
+ testDeadline(o, "WithTimeout+otherContext", t)
180
+
181
+ c, _ = WithTimeout(Background(), shortDuration)
182
+ o = otherContext{c}
183
+ c, _ = WithTimeout(o, veryLongDuration)
184
+ testDeadline(c, "WithTimeout+otherContext+WithTimeout", t)
185
+ }
186
+
187
+ func TestCanceledTimeout(t *testing.T) {
188
+ c, _ := WithTimeout(Background(), time.Second)
189
+ o := otherContext{c}
190
+ c, cancel := WithTimeout(o, veryLongDuration)
191
+ cancel() // Should propagate synchronously.
192
+ select {
193
+ case <-c.Done():
194
+ default:
195
+ t.Errorf("<-c.Done() blocked, but shouldn't have")
196
+ }
197
+ if e := c.Err(); e != Canceled {
198
+ t.Errorf("c.Err() == %v want %v", e, Canceled)
199
+ }
200
+ }
201
+
202
+ type key1 int
203
+ type key2 int
204
+
205
+ func (k key2) String() string { return fmt.Sprintf("%[1]T(%[1]d)", k) }
206
+
207
+ var k1 = key1(1)
208
+ var k2 = key2(1) // same int as k1, different type
209
+ var k3 = key2(3) // same type as k2, different int
210
+
211
+ func TestValues(t *testing.T) {
212
+ check := func(c Context, nm, v1, v2, v3 string) {
213
+ if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 {
214
+ t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0)
215
+ }
216
+ if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 {
217
+ t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0)
218
+ }
219
+ if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 {
220
+ t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0)
221
+ }
222
+ }
223
+
224
+ c0 := Background()
225
+ check(c0, "c0", "", "", "")
226
+
227
+ c1 := WithValue(Background(), k1, "c1k1")
228
+ check(c1, "c1", "c1k1", "", "")
229
+
230
+ if got, want := fmt.Sprint(c1), `context.Background.WithValue(context_test.key1, c1k1)`; got != want {
231
+ t.Errorf("c.String() = %q want %q", got, want)
232
+ }
233
+
234
+ c2 := WithValue(c1, k2, "c2k2")
235
+ check(c2, "c2", "c1k1", "c2k2", "")
236
+
237
+ if got, want := fmt.Sprint(c2), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2)`; got != want {
238
+ t.Errorf("c.String() = %q want %q", got, want)
239
+ }
240
+
241
+ c3 := WithValue(c2, k3, "c3k3")
242
+ check(c3, "c2", "c1k1", "c2k2", "c3k3")
243
+
244
+ c4 := WithValue(c3, k1, nil)
245
+ check(c4, "c4", "", "c2k2", "c3k3")
246
+
247
+ if got, want := fmt.Sprint(c4), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2).WithValue(context_test.key2(3), c3k3).WithValue(context_test.key1, <nil>)`; got != want {
248
+ t.Errorf("c.String() = %q want %q", got, want)
249
+ }
250
+
251
+ o0 := otherContext{Background()}
252
+ check(o0, "o0", "", "", "")
253
+
254
+ o1 := otherContext{WithValue(Background(), k1, "c1k1")}
255
+ check(o1, "o1", "c1k1", "", "")
256
+
257
+ o2 := WithValue(o1, k2, "o2k2")
258
+ check(o2, "o2", "c1k1", "o2k2", "")
259
+
260
+ o3 := otherContext{c4}
261
+ check(o3, "o3", "", "c2k2", "c3k3")
262
+
263
+ o4 := WithValue(o3, k3, nil)
264
+ check(o4, "o4", "", "c2k2", "")
265
+ }
266
+
267
+ func TestAllocs(t *testing.T) {
268
+ if asan.Enabled {
269
+ t.Skip("test allocates more with -asan")
270
+ }
271
+ bg := Background()
272
+ for _, test := range []struct {
273
+ desc string
274
+ f func()
275
+ limit float64
276
+ gccgoLimit float64
277
+ }{
278
+ {
279
+ desc: "Background()",
280
+ f: func() { Background() },
281
+ limit: 0,
282
+ gccgoLimit: 0,
283
+ },
284
+ {
285
+ desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1),
286
+ f: func() {
287
+ c := WithValue(bg, k1, nil)
288
+ c.Value(k1)
289
+ },
290
+ limit: 3,
291
+ gccgoLimit: 3,
292
+ },
293
+ {
294
+ desc: "WithTimeout(bg, 1*time.Nanosecond)",
295
+ f: func() {
296
+ c, _ := WithTimeout(bg, 1*time.Nanosecond)
297
+ <-c.Done()
298
+ },
299
+ limit: 12,
300
+ gccgoLimit: 15,
301
+ },
302
+ {
303
+ desc: "WithCancel(bg)",
304
+ f: func() {
305
+ c, cancel := WithCancel(bg)
306
+ cancel()
307
+ <-c.Done()
308
+ },
309
+ limit: 5,
310
+ gccgoLimit: 8,
311
+ },
312
+ {
313
+ desc: "WithTimeout(bg, 5*time.Millisecond)",
314
+ f: func() {
315
+ c, cancel := WithTimeout(bg, 5*time.Millisecond)
316
+ cancel()
317
+ <-c.Done()
318
+ },
319
+ limit: 8,
320
+ gccgoLimit: 25,
321
+ },
322
+ } {
323
+ limit := test.limit
324
+ if runtime.Compiler == "gccgo" {
325
+ // gccgo does not yet do escape analysis.
326
+ // TODO(iant): Remove this when gccgo does do escape analysis.
327
+ limit = test.gccgoLimit
328
+ }
329
+ numRuns := 100
330
+ if testing.Short() {
331
+ numRuns = 10
332
+ }
333
+ if n := testing.AllocsPerRun(numRuns, test.f); n > limit {
334
+ t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit))
335
+ }
336
+ }
337
+ }
338
+
339
+ func TestSimultaneousCancels(t *testing.T) {
340
+ root, cancel := WithCancel(Background())
341
+ m := map[Context]CancelFunc{root: cancel}
342
+ q := []Context{root}
343
+ // Create a tree of contexts.
344
+ for len(q) != 0 && len(m) < 100 {
345
+ parent := q[0]
346
+ q = q[1:]
347
+ for i := 0; i < 4; i++ {
348
+ ctx, cancel := WithCancel(parent)
349
+ m[ctx] = cancel
350
+ q = append(q, ctx)
351
+ }
352
+ }
353
+ // Start all the cancels in a random order.
354
+ var wg sync.WaitGroup
355
+ wg.Add(len(m))
356
+ for _, cancel := range m {
357
+ go func(cancel CancelFunc) {
358
+ cancel()
359
+ wg.Done()
360
+ }(cancel)
361
+ }
362
+
363
+ d := quiescent(t)
364
+ stuck := make(chan struct{})
365
+ timer := time.AfterFunc(d, func() { close(stuck) })
366
+ defer timer.Stop()
367
+
368
+ // Wait on all the contexts in a random order.
369
+ for ctx := range m {
370
+ select {
371
+ case <-ctx.Done():
372
+ case <-stuck:
373
+ buf := make([]byte, 10<<10)
374
+ n := runtime.Stack(buf, true)
375
+ t.Fatalf("timed out after %v waiting for <-ctx.Done(); stacks:\n%s", d, buf[:n])
376
+ }
377
+ }
378
+ // Wait for all the cancel functions to return.
379
+ done := make(chan struct{})
380
+ go func() {
381
+ wg.Wait()
382
+ close(done)
383
+ }()
384
+ select {
385
+ case <-done:
386
+ case <-stuck:
387
+ buf := make([]byte, 10<<10)
388
+ n := runtime.Stack(buf, true)
389
+ t.Fatalf("timed out after %v waiting for cancel functions; stacks:\n%s", d, buf[:n])
390
+ }
391
+ }
392
+
393
+ func TestInterlockedCancels(t *testing.T) {
394
+ parent, cancelParent := WithCancel(Background())
395
+ child, cancelChild := WithCancel(parent)
396
+ go func() {
397
+ <-parent.Done()
398
+ cancelChild()
399
+ }()
400
+ cancelParent()
401
+ d := quiescent(t)
402
+ timer := time.NewTimer(d)
403
+ defer timer.Stop()
404
+ select {
405
+ case <-child.Done():
406
+ case <-timer.C:
407
+ buf := make([]byte, 10<<10)
408
+ n := runtime.Stack(buf, true)
409
+ t.Fatalf("timed out after %v waiting for child.Done(); stacks:\n%s", d, buf[:n])
410
+ }
411
+ }
412
+
413
+ func TestLayersCancel(t *testing.T) {
414
+ testLayers(t, time.Now().UnixNano(), false)
415
+ }
416
+
417
+ func TestLayersTimeout(t *testing.T) {
418
+ testLayers(t, time.Now().UnixNano(), true)
419
+ }
420
+
421
+ func testLayers(t *testing.T, seed int64, testTimeout bool) {
422
+ t.Parallel()
423
+
424
+ r := rand.New(rand.NewSource(seed))
425
+ prefix := fmt.Sprintf("seed=%d", seed)
426
+ errorf := func(format string, a ...any) {
427
+ t.Errorf(prefix+format, a...)
428
+ }
429
+ const (
430
+ minLayers = 30
431
+ )
432
+ type value int
433
+ var (
434
+ vals []*value
435
+ cancels []CancelFunc
436
+ numTimers int
437
+ ctx = Background()
438
+ )
439
+ for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ {
440
+ switch r.Intn(3) {
441
+ case 0:
442
+ v := new(value)
443
+ ctx = WithValue(ctx, v, v)
444
+ vals = append(vals, v)
445
+ case 1:
446
+ var cancel CancelFunc
447
+ ctx, cancel = WithCancel(ctx)
448
+ cancels = append(cancels, cancel)
449
+ case 2:
450
+ var cancel CancelFunc
451
+ d := veryLongDuration
452
+ if testTimeout {
453
+ d = shortDuration
454
+ }
455
+ ctx, cancel = WithTimeout(ctx, d)
456
+ cancels = append(cancels, cancel)
457
+ numTimers++
458
+ }
459
+ }
460
+ checkValues := func(when string) {
461
+ for _, key := range vals {
462
+ if val := ctx.Value(key).(*value); key != val {
463
+ errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key)
464
+ }
465
+ }
466
+ }
467
+ if !testTimeout {
468
+ select {
469
+ case <-ctx.Done():
470
+ errorf("ctx should not be canceled yet")
471
+ default:
472
+ }
473
+ }
474
+ if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) {
475
+ t.Errorf("ctx.String() = %q want prefix %q", s, prefix)
476
+ }
477
+ t.Log(ctx)
478
+ checkValues("before cancel")
479
+ if testTimeout {
480
+ d := quiescent(t)
481
+ timer := time.NewTimer(d)
482
+ defer timer.Stop()
483
+ select {
484
+ case <-ctx.Done():
485
+ case <-timer.C:
486
+ errorf("ctx should have timed out after %v", d)
487
+ }
488
+ checkValues("after timeout")
489
+ } else {
490
+ cancel := cancels[r.Intn(len(cancels))]
491
+ cancel()
492
+ select {
493
+ case <-ctx.Done():
494
+ default:
495
+ errorf("ctx should be canceled")
496
+ }
497
+ checkValues("after cancel")
498
+ }
499
+ }
500
+
501
+ func TestWithCancelCanceledParent(t *testing.T) {
502
+ parent, pcancel := WithCancelCause(Background())
503
+ cause := fmt.Errorf("Because!")
504
+ pcancel(cause)
505
+
506
+ c, _ := WithCancel(parent)
507
+ select {
508
+ case <-c.Done():
509
+ default:
510
+ t.Errorf("child not done immediately upon construction")
511
+ }
512
+ if got, want := c.Err(), Canceled; got != want {
513
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
514
+ }
515
+ if got, want := Cause(c), cause; got != want {
516
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
517
+ }
518
+ }
519
+
520
+ func TestWithCancelSimultaneouslyCanceledParent(t *testing.T) {
521
+ // Cancel the parent goroutine concurrently with creating a child.
522
+ for i := 0; i < 100; i++ {
523
+ parent, pcancel := WithCancelCause(Background())
524
+ cause := fmt.Errorf("Because!")
525
+ go pcancel(cause)
526
+
527
+ c, _ := WithCancel(parent)
528
+ <-c.Done()
529
+ if got, want := c.Err(), Canceled; got != want {
530
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
531
+ }
532
+ if got, want := Cause(c), cause; got != want {
533
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
534
+ }
535
+ }
536
+ }
537
+
538
+ func TestWithValueChecksKey(t *testing.T) {
539
+ panicVal := recoveredValue(func() { _ = WithValue(Background(), []byte("foo"), "bar") })
540
+ if panicVal == nil {
541
+ t.Error("expected panic")
542
+ }
543
+ panicVal = recoveredValue(func() { _ = WithValue(Background(), nil, "bar") })
544
+ if got, want := fmt.Sprint(panicVal), "nil key"; got != want {
545
+ t.Errorf("panic = %q; want %q", got, want)
546
+ }
547
+ }
548
+
549
+ func TestInvalidDerivedFail(t *testing.T) {
550
+ panicVal := recoveredValue(func() { _, _ = WithCancel(nil) })
551
+ if panicVal == nil {
552
+ t.Error("expected panic")
553
+ }
554
+ panicVal = recoveredValue(func() { _, _ = WithDeadline(nil, time.Now().Add(shortDuration)) })
555
+ if panicVal == nil {
556
+ t.Error("expected panic")
557
+ }
558
+ panicVal = recoveredValue(func() { _ = WithValue(nil, "foo", "bar") })
559
+ if panicVal == nil {
560
+ t.Error("expected panic")
561
+ }
562
+ }
563
+
564
+ func recoveredValue(fn func()) (v any) {
565
+ defer func() { v = recover() }()
566
+ fn()
567
+ return
568
+ }
569
+
570
+ func TestDeadlineExceededSupportsTimeout(t *testing.T) {
571
+ i, ok := DeadlineExceeded.(interface {
572
+ Timeout() bool
573
+ })
574
+ if !ok {
575
+ t.Fatal("DeadlineExceeded does not support Timeout interface")
576
+ }
577
+ if !i.Timeout() {
578
+ t.Fatal("wrong value for timeout")
579
+ }
580
+ }
581
+ func TestCause(t *testing.T) {
582
+ var (
583
+ forever = 1e6 * time.Second
584
+ parentCause = fmt.Errorf("parentCause")
585
+ childCause = fmt.Errorf("childCause")
586
+ tooSlow = fmt.Errorf("tooSlow")
587
+ finishedEarly = fmt.Errorf("finishedEarly")
588
+ )
589
+ for _, test := range []struct {
590
+ name string
591
+ ctx func() Context
592
+ err error
593
+ cause error
594
+ }{
595
+ {
596
+ name: "Background",
597
+ ctx: Background,
598
+ err: nil,
599
+ cause: nil,
600
+ },
601
+ {
602
+ name: "TODO",
603
+ ctx: TODO,
604
+ err: nil,
605
+ cause: nil,
606
+ },
607
+ {
608
+ name: "WithCancel",
609
+ ctx: func() Context {
610
+ ctx, cancel := WithCancel(Background())
611
+ cancel()
612
+ return ctx
613
+ },
614
+ err: Canceled,
615
+ cause: Canceled,
616
+ },
617
+ {
618
+ name: "WithCancelCause",
619
+ ctx: func() Context {
620
+ ctx, cancel := WithCancelCause(Background())
621
+ cancel(parentCause)
622
+ return ctx
623
+ },
624
+ err: Canceled,
625
+ cause: parentCause,
626
+ },
627
+ {
628
+ name: "WithCancelCause nil",
629
+ ctx: func() Context {
630
+ ctx, cancel := WithCancelCause(Background())
631
+ cancel(nil)
632
+ return ctx
633
+ },
634
+ err: Canceled,
635
+ cause: Canceled,
636
+ },
637
+ {
638
+ name: "WithCancelCause: parent cause before child",
639
+ ctx: func() Context {
640
+ ctx, cancelParent := WithCancelCause(Background())
641
+ ctx, cancelChild := WithCancelCause(ctx)
642
+ cancelParent(parentCause)
643
+ cancelChild(childCause)
644
+ return ctx
645
+ },
646
+ err: Canceled,
647
+ cause: parentCause,
648
+ },
649
+ {
650
+ name: "WithCancelCause: parent cause after child",
651
+ ctx: func() Context {
652
+ ctx, cancelParent := WithCancelCause(Background())
653
+ ctx, cancelChild := WithCancelCause(ctx)
654
+ cancelChild(childCause)
655
+ cancelParent(parentCause)
656
+ return ctx
657
+ },
658
+ err: Canceled,
659
+ cause: childCause,
660
+ },
661
+ {
662
+ name: "WithCancelCause: parent cause before nil",
663
+ ctx: func() Context {
664
+ ctx, cancelParent := WithCancelCause(Background())
665
+ ctx, cancelChild := WithCancel(ctx)
666
+ cancelParent(parentCause)
667
+ cancelChild()
668
+ return ctx
669
+ },
670
+ err: Canceled,
671
+ cause: parentCause,
672
+ },
673
+ {
674
+ name: "WithCancelCause: parent cause after nil",
675
+ ctx: func() Context {
676
+ ctx, cancelParent := WithCancelCause(Background())
677
+ ctx, cancelChild := WithCancel(ctx)
678
+ cancelChild()
679
+ cancelParent(parentCause)
680
+ return ctx
681
+ },
682
+ err: Canceled,
683
+ cause: Canceled,
684
+ },
685
+ {
686
+ name: "WithCancelCause: child cause after nil",
687
+ ctx: func() Context {
688
+ ctx, cancelParent := WithCancel(Background())
689
+ ctx, cancelChild := WithCancelCause(ctx)
690
+ cancelParent()
691
+ cancelChild(childCause)
692
+ return ctx
693
+ },
694
+ err: Canceled,
695
+ cause: Canceled,
696
+ },
697
+ {
698
+ name: "WithCancelCause: child cause before nil",
699
+ ctx: func() Context {
700
+ ctx, cancelParent := WithCancel(Background())
701
+ ctx, cancelChild := WithCancelCause(ctx)
702
+ cancelChild(childCause)
703
+ cancelParent()
704
+ return ctx
705
+ },
706
+ err: Canceled,
707
+ cause: childCause,
708
+ },
709
+ {
710
+ name: "WithTimeout",
711
+ ctx: func() Context {
712
+ ctx, cancel := WithTimeout(Background(), 0)
713
+ cancel()
714
+ return ctx
715
+ },
716
+ err: DeadlineExceeded,
717
+ cause: DeadlineExceeded,
718
+ },
719
+ {
720
+ name: "WithTimeout canceled",
721
+ ctx: func() Context {
722
+ ctx, cancel := WithTimeout(Background(), forever)
723
+ cancel()
724
+ return ctx
725
+ },
726
+ err: Canceled,
727
+ cause: Canceled,
728
+ },
729
+ {
730
+ name: "WithTimeoutCause",
731
+ ctx: func() Context {
732
+ ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow)
733
+ cancel()
734
+ return ctx
735
+ },
736
+ err: DeadlineExceeded,
737
+ cause: tooSlow,
738
+ },
739
+ {
740
+ name: "WithTimeoutCause canceled",
741
+ ctx: func() Context {
742
+ ctx, cancel := WithTimeoutCause(Background(), forever, tooSlow)
743
+ cancel()
744
+ return ctx
745
+ },
746
+ err: Canceled,
747
+ cause: Canceled,
748
+ },
749
+ {
750
+ name: "WithTimeoutCause stacked",
751
+ ctx: func() Context {
752
+ ctx, cancel := WithCancelCause(Background())
753
+ ctx, _ = WithTimeoutCause(ctx, 0, tooSlow)
754
+ cancel(finishedEarly)
755
+ return ctx
756
+ },
757
+ err: DeadlineExceeded,
758
+ cause: tooSlow,
759
+ },
760
+ {
761
+ name: "WithTimeoutCause stacked canceled",
762
+ ctx: func() Context {
763
+ ctx, cancel := WithCancelCause(Background())
764
+ ctx, _ = WithTimeoutCause(ctx, forever, tooSlow)
765
+ cancel(finishedEarly)
766
+ return ctx
767
+ },
768
+ err: Canceled,
769
+ cause: finishedEarly,
770
+ },
771
+ {
772
+ name: "WithoutCancel",
773
+ ctx: func() Context {
774
+ return WithoutCancel(Background())
775
+ },
776
+ err: nil,
777
+ cause: nil,
778
+ },
779
+ {
780
+ name: "WithoutCancel canceled",
781
+ ctx: func() Context {
782
+ ctx, cancel := WithCancelCause(Background())
783
+ ctx = WithoutCancel(ctx)
784
+ cancel(finishedEarly)
785
+ return ctx
786
+ },
787
+ err: nil,
788
+ cause: nil,
789
+ },
790
+ {
791
+ name: "WithoutCancel timeout",
792
+ ctx: func() Context {
793
+ ctx, cancel := WithTimeoutCause(Background(), 0, tooSlow)
794
+ ctx = WithoutCancel(ctx)
795
+ cancel()
796
+ return ctx
797
+ },
798
+ err: nil,
799
+ cause: nil,
800
+ },
801
+ {
802
+ name: "parent of custom context not canceled",
803
+ ctx: func() Context {
804
+ ctx, _ := WithCancelCause(Background())
805
+ ctx, cancel2 := newCustomContext(ctx)
806
+ cancel2()
807
+ return ctx
808
+ },
809
+ err: Canceled,
810
+ cause: Canceled,
811
+ },
812
+ {
813
+ name: "parent of custom context is canceled before",
814
+ ctx: func() Context {
815
+ ctx, cancel1 := WithCancelCause(Background())
816
+ ctx, cancel2 := newCustomContext(ctx)
817
+ cancel1(parentCause)
818
+ cancel2()
819
+ return ctx
820
+ },
821
+ err: Canceled,
822
+ cause: parentCause,
823
+ },
824
+ {
825
+ name: "parent of custom context is canceled after",
826
+ ctx: func() Context {
827
+ ctx, cancel1 := WithCancelCause(Background())
828
+ ctx, cancel2 := newCustomContext(ctx)
829
+ cancel2()
830
+ cancel1(parentCause)
831
+ return ctx
832
+ },
833
+ err: Canceled,
834
+ // This isn't really right: the child context was canceled before
835
+ // the parent context, and shouldn't inherit the parent's cause.
836
+ // However, since the child is a custom context, Cause has no way
837
+ // to tell which was canceled first and returns the parent's cause.
838
+ cause: parentCause,
839
+ },
840
+ } {
841
+ t.Run(test.name, func(t *testing.T) {
842
+ t.Parallel()
843
+ ctx := test.ctx()
844
+ if got, want := ctx.Err(), test.err; want != got {
845
+ t.Errorf("ctx.Err() = %v want %v", got, want)
846
+ }
847
+ if got, want := Cause(ctx), test.cause; want != got {
848
+ t.Errorf("Cause(ctx) = %v want %v", got, want)
849
+ }
850
+ })
851
+ }
852
+ }
853
+
854
+ func TestCauseRace(t *testing.T) {
855
+ cause := errors.New("TestCauseRace")
856
+ ctx, cancel := WithCancelCause(Background())
857
+ go func() {
858
+ cancel(cause)
859
+ }()
860
+ for {
861
+ // Poll Cause, rather than waiting for Done, to test that
862
+ // access to the underlying cause is synchronized properly.
863
+ if err := Cause(ctx); err != nil {
864
+ if err != cause {
865
+ t.Errorf("Cause returned %v, want %v", err, cause)
866
+ }
867
+ break
868
+ }
869
+ runtime.Gosched()
870
+ }
871
+ }
872
+
873
+ func TestWithoutCancel(t *testing.T) {
874
+ key, value := "key", "value"
875
+ ctx := WithValue(Background(), key, value)
876
+ ctx = WithoutCancel(ctx)
877
+ if d, ok := ctx.Deadline(); !d.IsZero() || ok != false {
878
+ t.Errorf("ctx.Deadline() = %v, %v want zero, false", d, ok)
879
+ }
880
+ if done := ctx.Done(); done != nil {
881
+ t.Errorf("ctx.Deadline() = %v want nil", done)
882
+ }
883
+ if err := ctx.Err(); err != nil {
884
+ t.Errorf("ctx.Err() = %v want nil", err)
885
+ }
886
+ if v := ctx.Value(key); v != value {
887
+ t.Errorf("ctx.Value(%q) = %q want %q", key, v, value)
888
+ }
889
+ }
890
+
891
+ type customDoneContext struct {
892
+ Context
893
+ donec chan struct{}
894
+ }
895
+
896
+ func (c *customDoneContext) Done() <-chan struct{} {
897
+ return c.donec
898
+ }
899
+
900
+ func TestCustomContextPropagation(t *testing.T) {
901
+ cause := errors.New("TestCustomContextPropagation")
902
+ donec := make(chan struct{})
903
+ ctx1, cancel1 := WithCancelCause(Background())
904
+ ctx2 := &customDoneContext{
905
+ Context: ctx1,
906
+ donec: donec,
907
+ }
908
+ ctx3, cancel3 := WithCancel(ctx2)
909
+ defer cancel3()
910
+
911
+ cancel1(cause)
912
+ close(donec)
913
+
914
+ <-ctx3.Done()
915
+ if got, want := ctx3.Err(), Canceled; got != want {
916
+ t.Errorf("child not canceled; got = %v, want = %v", got, want)
917
+ }
918
+ if got, want := Cause(ctx3), cause; got != want {
919
+ t.Errorf("child has wrong cause; got = %v, want = %v", got, want)
920
+ }
921
+ }
922
+
923
+ // customCauseContext is a custom Context used to test context.Cause.
924
+ type customCauseContext struct {
925
+ mu sync.Mutex
926
+ done chan struct{}
927
+ err error
928
+
929
+ cancelChild CancelFunc
930
+ }
931
+
932
+ func (ccc *customCauseContext) Deadline() (deadline time.Time, ok bool) {
933
+ return
934
+ }
935
+
936
+ func (ccc *customCauseContext) Done() <-chan struct{} {
937
+ ccc.mu.Lock()
938
+ defer ccc.mu.Unlock()
939
+ return ccc.done
940
+ }
941
+
942
+ func (ccc *customCauseContext) Err() error {
943
+ ccc.mu.Lock()
944
+ defer ccc.mu.Unlock()
945
+ return ccc.err
946
+ }
947
+
948
+ func (ccc *customCauseContext) Value(key any) any {
949
+ return nil
950
+ }
951
+
952
+ func (ccc *customCauseContext) cancel() {
953
+ ccc.mu.Lock()
954
+ ccc.err = Canceled
955
+ close(ccc.done)
956
+ cancelChild := ccc.cancelChild
957
+ ccc.mu.Unlock()
958
+
959
+ if cancelChild != nil {
960
+ cancelChild()
961
+ }
962
+ }
963
+
964
+ func (ccc *customCauseContext) setCancelChild(cancelChild CancelFunc) {
965
+ ccc.cancelChild = cancelChild
966
+ }
967
+
968
+ func TestCustomContextCause(t *testing.T) {
969
+ // Test if we cancel a custom context, Err and Cause return Canceled.
970
+ ccc := &customCauseContext{
971
+ done: make(chan struct{}),
972
+ }
973
+ ccc.cancel()
974
+ if got := ccc.Err(); got != Canceled {
975
+ t.Errorf("ccc.Err() = %v, want %v", got, Canceled)
976
+ }
977
+ if got := Cause(ccc); got != Canceled {
978
+ t.Errorf("Cause(ccc) = %v, want %v", got, Canceled)
979
+ }
980
+
981
+ // Test that if we pass a custom context to WithCancelCause,
982
+ // and then cancel that child context with a cause,
983
+ // that the cause of the child canceled context is correct
984
+ // but that the parent custom context is not canceled.
985
+ ccc = &customCauseContext{
986
+ done: make(chan struct{}),
987
+ }
988
+ ctx, causeFunc := WithCancelCause(ccc)
989
+ cause := errors.New("TestCustomContextCause")
990
+ causeFunc(cause)
991
+ if got := ctx.Err(); got != Canceled {
992
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
993
+ }
994
+ if got := Cause(ctx); got != cause {
995
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause)
996
+ }
997
+ if got := ccc.Err(); got != nil {
998
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, nil)
999
+ }
1000
+ if got := Cause(ccc); got != nil {
1001
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, nil)
1002
+ }
1003
+
1004
+ // Test that if we now cancel the parent custom context,
1005
+ // the cause of the child canceled context is still correct,
1006
+ // and the parent custom context is canceled without a cause.
1007
+ ccc.cancel()
1008
+ if got := ctx.Err(); got != Canceled {
1009
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
1010
+ }
1011
+ if got := Cause(ctx); got != cause {
1012
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, cause)
1013
+ }
1014
+ if got := ccc.Err(); got != Canceled {
1015
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled)
1016
+ }
1017
+ if got := Cause(ccc); got != Canceled {
1018
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled)
1019
+ }
1020
+
1021
+ // Test that if we associate a custom context with a child,
1022
+ // then canceling the custom context cancels the child.
1023
+ ccc = &customCauseContext{
1024
+ done: make(chan struct{}),
1025
+ }
1026
+ ctx, cancelFunc := WithCancel(ccc)
1027
+ ccc.setCancelChild(cancelFunc)
1028
+ ccc.cancel()
1029
+ if got := ctx.Err(); got != Canceled {
1030
+ t.Errorf("after CancelCauseFunc ctx.Err() = %v, want %v", got, Canceled)
1031
+ }
1032
+ if got := Cause(ctx); got != Canceled {
1033
+ t.Errorf("after CancelCauseFunc Cause(ctx) = %v, want %v", got, Canceled)
1034
+ }
1035
+ if got := ccc.Err(); got != Canceled {
1036
+ t.Errorf("after CancelCauseFunc ccc.Err() = %v, want %v", got, Canceled)
1037
+ }
1038
+ if got := Cause(ccc); got != Canceled {
1039
+ t.Errorf("after CancelCauseFunc Cause(ccc) = %v, want %v", got, Canceled)
1040
+ }
1041
+ }
1042
+
1043
+ func TestAfterFuncCalledAfterCancel(t *testing.T) {
1044
+ ctx, cancel := WithCancel(Background())
1045
+ donec := make(chan struct{})
1046
+ stop := AfterFunc(ctx, func() {
1047
+ close(donec)
1048
+ })
1049
+ select {
1050
+ case <-donec:
1051
+ t.Fatalf("AfterFunc called before context is done")
1052
+ case <-time.After(shortDuration):
1053
+ }
1054
+ cancel()
1055
+ select {
1056
+ case <-donec:
1057
+ case <-time.After(veryLongDuration):
1058
+ t.Fatalf("AfterFunc not called after context is canceled")
1059
+ }
1060
+ if stop() {
1061
+ t.Fatalf("stop() = true, want false")
1062
+ }
1063
+ }
1064
+
1065
+ func TestAfterFuncCalledAfterTimeout(t *testing.T) {
1066
+ ctx, cancel := WithTimeout(Background(), shortDuration)
1067
+ defer cancel()
1068
+ donec := make(chan struct{})
1069
+ AfterFunc(ctx, func() {
1070
+ close(donec)
1071
+ })
1072
+ select {
1073
+ case <-donec:
1074
+ case <-time.After(veryLongDuration):
1075
+ t.Fatalf("AfterFunc not called after context is canceled")
1076
+ }
1077
+ }
1078
+
1079
+ func TestAfterFuncCalledImmediately(t *testing.T) {
1080
+ ctx, cancel := WithCancel(Background())
1081
+ cancel()
1082
+ donec := make(chan struct{})
1083
+ AfterFunc(ctx, func() {
1084
+ close(donec)
1085
+ })
1086
+ select {
1087
+ case <-donec:
1088
+ case <-time.After(veryLongDuration):
1089
+ t.Fatalf("AfterFunc not called for already-canceled context")
1090
+ }
1091
+ }
1092
+
1093
+ func TestAfterFuncNotCalledAfterStop(t *testing.T) {
1094
+ ctx, cancel := WithCancel(Background())
1095
+ donec := make(chan struct{})
1096
+ stop := AfterFunc(ctx, func() {
1097
+ close(donec)
1098
+ })
1099
+ if !stop() {
1100
+ t.Fatalf("stop() = false, want true")
1101
+ }
1102
+ cancel()
1103
+ select {
1104
+ case <-donec:
1105
+ t.Fatalf("AfterFunc called for already-canceled context")
1106
+ case <-time.After(shortDuration):
1107
+ }
1108
+ if stop() {
1109
+ t.Fatalf("stop() = true, want false")
1110
+ }
1111
+ }
1112
+
1113
+ // This test verifies that canceling a context does not block waiting for AfterFuncs to finish.
1114
+ func TestAfterFuncCalledAsynchronously(t *testing.T) {
1115
+ ctx, cancel := WithCancel(Background())
1116
+ donec := make(chan struct{})
1117
+ stop := AfterFunc(ctx, func() {
1118
+ // The channel send blocks until donec is read from.
1119
+ donec <- struct{}{}
1120
+ })
1121
+ defer stop()
1122
+ cancel()
1123
+ // After cancel returns, read from donec and unblock the AfterFunc.
1124
+ select {
1125
+ case <-donec:
1126
+ case <-time.After(veryLongDuration):
1127
+ t.Fatalf("AfterFunc not called after context is canceled")
1128
+ }
1129
+ }
1130
+
1131
+ // customContext is a custom Context implementation.
1132
+ type customContext struct {
1133
+ parent Context
1134
+
1135
+ doneOnce sync.Once
1136
+ donec chan struct{}
1137
+ err error
1138
+ }
1139
+
1140
+ func newCustomContext(parent Context) (Context, CancelFunc) {
1141
+ c := &customContext{
1142
+ parent: parent,
1143
+ donec: make(chan struct{}),
1144
+ }
1145
+ AfterFunc(parent, func() {
1146
+ c.doneOnce.Do(func() {
1147
+ c.err = parent.Err()
1148
+ close(c.donec)
1149
+ })
1150
+ })
1151
+ return c, func() {
1152
+ c.doneOnce.Do(func() {
1153
+ c.err = Canceled
1154
+ close(c.donec)
1155
+ })
1156
+ }
1157
+ }
1158
+
1159
+ func (c *customContext) Deadline() (time.Time, bool) {
1160
+ return c.parent.Deadline()
1161
+ }
1162
+
1163
+ func (c *customContext) Done() <-chan struct{} {
1164
+ return c.donec
1165
+ }
1166
+
1167
+ func (c *customContext) Err() error {
1168
+ select {
1169
+ case <-c.donec:
1170
+ return c.err
1171
+ default:
1172
+ return nil
1173
+ }
1174
+ }
1175
+
1176
+ func (c *customContext) Value(key any) any {
1177
+ return c.parent.Value(key)
1178
+ }
1179
+
1180
+ // Issue #75533.
1181
+ func TestContextErrDoneRace(t *testing.T) {
1182
+ // 4 iterations reliably reproduced #75533.
1183
+ for range 10 {
1184
+ ctx, cancel := WithCancel(Background())
1185
+ donec := ctx.Done()
1186
+ go cancel()
1187
+ for ctx.Err() == nil {
1188
+ if runtime.GOARCH == "wasm" {
1189
+ runtime.Gosched() // need to explicitly yield
1190
+ }
1191
+ }
1192
+ select {
1193
+ case <-donec:
1194
+ default:
1195
+ t.Fatalf("ctx.Err is non-nil, but ctx.Done is not closed")
1196
+ }
1197
+ }
1198
+ }
go/src/crypto/crypto.go ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package crypto collects common cryptographic constants.
6
+ package crypto
7
+
8
+ import (
9
+ "hash"
10
+ "io"
11
+ "strconv"
12
+ )
13
+
14
+ // Hash identifies a cryptographic hash function that is implemented in another
15
+ // package.
16
+ type Hash uint
17
+
18
+ // HashFunc simply returns the value of h so that [Hash] implements [SignerOpts].
19
+ func (h Hash) HashFunc() Hash {
20
+ return h
21
+ }
22
+
23
+ func (h Hash) String() string {
24
+ switch h {
25
+ case MD4:
26
+ return "MD4"
27
+ case MD5:
28
+ return "MD5"
29
+ case SHA1:
30
+ return "SHA-1"
31
+ case SHA224:
32
+ return "SHA-224"
33
+ case SHA256:
34
+ return "SHA-256"
35
+ case SHA384:
36
+ return "SHA-384"
37
+ case SHA512:
38
+ return "SHA-512"
39
+ case MD5SHA1:
40
+ return "MD5+SHA1"
41
+ case RIPEMD160:
42
+ return "RIPEMD-160"
43
+ case SHA3_224:
44
+ return "SHA3-224"
45
+ case SHA3_256:
46
+ return "SHA3-256"
47
+ case SHA3_384:
48
+ return "SHA3-384"
49
+ case SHA3_512:
50
+ return "SHA3-512"
51
+ case SHA512_224:
52
+ return "SHA-512/224"
53
+ case SHA512_256:
54
+ return "SHA-512/256"
55
+ case BLAKE2s_256:
56
+ return "BLAKE2s-256"
57
+ case BLAKE2b_256:
58
+ return "BLAKE2b-256"
59
+ case BLAKE2b_384:
60
+ return "BLAKE2b-384"
61
+ case BLAKE2b_512:
62
+ return "BLAKE2b-512"
63
+ default:
64
+ return "unknown hash value " + strconv.Itoa(int(h))
65
+ }
66
+ }
67
+
68
+ const (
69
+ MD4 Hash = 1 + iota // import golang.org/x/crypto/md4
70
+ MD5 // import crypto/md5
71
+ SHA1 // import crypto/sha1
72
+ SHA224 // import crypto/sha256
73
+ SHA256 // import crypto/sha256
74
+ SHA384 // import crypto/sha512
75
+ SHA512 // import crypto/sha512
76
+ MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA
77
+ RIPEMD160 // import golang.org/x/crypto/ripemd160
78
+ SHA3_224 // import crypto/sha3
79
+ SHA3_256 // import crypto/sha3
80
+ SHA3_384 // import crypto/sha3
81
+ SHA3_512 // import crypto/sha3
82
+ SHA512_224 // import crypto/sha512
83
+ SHA512_256 // import crypto/sha512
84
+ BLAKE2s_256 // import golang.org/x/crypto/blake2s
85
+ BLAKE2b_256 // import golang.org/x/crypto/blake2b
86
+ BLAKE2b_384 // import golang.org/x/crypto/blake2b
87
+ BLAKE2b_512 // import golang.org/x/crypto/blake2b
88
+ maxHash
89
+ )
90
+
91
+ var digestSizes = []uint8{
92
+ MD4: 16,
93
+ MD5: 16,
94
+ SHA1: 20,
95
+ SHA224: 28,
96
+ SHA256: 32,
97
+ SHA384: 48,
98
+ SHA512: 64,
99
+ SHA512_224: 28,
100
+ SHA512_256: 32,
101
+ SHA3_224: 28,
102
+ SHA3_256: 32,
103
+ SHA3_384: 48,
104
+ SHA3_512: 64,
105
+ MD5SHA1: 36,
106
+ RIPEMD160: 20,
107
+ BLAKE2s_256: 32,
108
+ BLAKE2b_256: 32,
109
+ BLAKE2b_384: 48,
110
+ BLAKE2b_512: 64,
111
+ }
112
+
113
+ // Size returns the length, in bytes, of a digest resulting from the given hash
114
+ // function. It doesn't require that the hash function in question be linked
115
+ // into the program.
116
+ func (h Hash) Size() int {
117
+ if h > 0 && h < maxHash {
118
+ return int(digestSizes[h])
119
+ }
120
+ panic("crypto: Size of unknown hash function")
121
+ }
122
+
123
+ var hashes = make([]func() hash.Hash, maxHash)
124
+
125
+ // New returns a new hash.Hash calculating the given hash function. New panics
126
+ // if the hash function is not linked into the binary.
127
+ func (h Hash) New() hash.Hash {
128
+ if h > 0 && h < maxHash {
129
+ f := hashes[h]
130
+ if f != nil {
131
+ return f()
132
+ }
133
+ }
134
+ panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable")
135
+ }
136
+
137
+ // Available reports whether the given hash function is linked into the binary.
138
+ func (h Hash) Available() bool {
139
+ return h < maxHash && hashes[h] != nil
140
+ }
141
+
142
+ // RegisterHash registers a function that returns a new instance of the given
143
+ // hash function. This is intended to be called from the init function in
144
+ // packages that implement hash functions.
145
+ func RegisterHash(h Hash, f func() hash.Hash) {
146
+ if h >= maxHash {
147
+ panic("crypto: RegisterHash of unknown hash function")
148
+ }
149
+ hashes[h] = f
150
+ }
151
+
152
+ // PublicKey represents a public key using an unspecified algorithm.
153
+ //
154
+ // Although this type is an empty interface for backwards compatibility reasons,
155
+ // all public key types in the standard library implement the following interface
156
+ //
157
+ // interface{
158
+ // Equal(x crypto.PublicKey) bool
159
+ // }
160
+ //
161
+ // which can be used for increased type safety within applications.
162
+ type PublicKey any
163
+
164
+ // PrivateKey represents a private key using an unspecified algorithm.
165
+ //
166
+ // Although this type is an empty interface for backwards compatibility reasons,
167
+ // all private key types in the standard library implement the following interface
168
+ //
169
+ // interface{
170
+ // Public() crypto.PublicKey
171
+ // Equal(x crypto.PrivateKey) bool
172
+ // }
173
+ //
174
+ // as well as purpose-specific interfaces such as [Signer] and [Decrypter], which
175
+ // can be used for increased type safety within applications.
176
+ type PrivateKey any
177
+
178
+ // Signer is an interface for an opaque private key that can be used for
179
+ // signing operations. For example, an RSA key kept in a hardware module.
180
+ type Signer interface {
181
+ // Public returns the public key corresponding to the opaque,
182
+ // private key.
183
+ Public() PublicKey
184
+
185
+ // Sign signs digest with the private key, possibly using entropy from
186
+ // rand. For an RSA key, the resulting signature should be either a
187
+ // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
188
+ // key, it should be a DER-serialised, ASN.1 signature structure.
189
+ //
190
+ // Hash implements the SignerOpts interface and, in most cases, one can
191
+ // simply pass in the hash function used as opts. Sign may also attempt
192
+ // to type assert opts to other types in order to obtain algorithm
193
+ // specific values. See the documentation in each package for details.
194
+ //
195
+ // Note that when a signature of a hash of a larger message is needed,
196
+ // the caller is responsible for hashing the larger message and passing
197
+ // the hash (as digest) and the hash function (as opts) to Sign.
198
+ Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
199
+ }
200
+
201
+ // MessageSigner is an interface for an opaque private key that can be used for
202
+ // signing operations where the message is not pre-hashed by the caller.
203
+ // It is a superset of the Signer interface so that it can be passed to APIs
204
+ // which accept Signer, which may try to do an interface upgrade.
205
+ //
206
+ // MessageSigner.SignMessage and MessageSigner.Sign should produce the same
207
+ // result given the same opts. In particular, MessageSigner.SignMessage should
208
+ // only accept a zero opts.HashFunc if the Signer would also accept messages
209
+ // which are not pre-hashed.
210
+ //
211
+ // Implementations which do not provide the pre-hashed Sign API should implement
212
+ // Signer.Sign by always returning an error.
213
+ type MessageSigner interface {
214
+ Signer
215
+ SignMessage(rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error)
216
+ }
217
+
218
+ // SignerOpts contains options for signing with a [Signer].
219
+ type SignerOpts interface {
220
+ // HashFunc returns an identifier for the hash function used to produce
221
+ // the message passed to Signer.Sign, or else zero to indicate that no
222
+ // hashing was done.
223
+ HashFunc() Hash
224
+ }
225
+
226
+ // Decrypter is an interface for an opaque private key that can be used for
227
+ // asymmetric decryption operations. An example would be an RSA key
228
+ // kept in a hardware module.
229
+ type Decrypter interface {
230
+ // Public returns the public key corresponding to the opaque,
231
+ // private key.
232
+ Public() PublicKey
233
+
234
+ // Decrypt decrypts msg. The opts argument should be appropriate for
235
+ // the primitive used. See the documentation in each implementation for
236
+ // details.
237
+ Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
238
+ }
239
+
240
+ type DecrypterOpts any
241
+
242
+ // SignMessage signs msg with signer. If signer implements [MessageSigner],
243
+ // [MessageSigner.SignMessage] is called directly. Otherwise, msg is hashed
244
+ // with opts.HashFunc() and signed with [Signer.Sign].
245
+ func SignMessage(signer Signer, rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error) {
246
+ if ms, ok := signer.(MessageSigner); ok {
247
+ return ms.SignMessage(rand, msg, opts)
248
+ }
249
+ if opts.HashFunc() != 0 {
250
+ h := opts.HashFunc().New()
251
+ h.Write(msg)
252
+ msg = h.Sum(nil)
253
+ }
254
+ return signer.Sign(rand, msg, opts)
255
+ }
256
+
257
+ // Decapsulator is an interface for an opaque private KEM key that can be used for
258
+ // decapsulation operations. For example, an ML-KEM key kept in a hardware module.
259
+ //
260
+ // It is implemented, for example, by [crypto/mlkem.DecapsulationKey768].
261
+ type Decapsulator interface {
262
+ Encapsulator() Encapsulator
263
+ Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
264
+ }
265
+
266
+ // Encapsulator is an interface for a public KEM key that can be used for
267
+ // encapsulation operations.
268
+ //
269
+ // It is implemented, for example, by [crypto/mlkem.EncapsulationKey768].
270
+ type Encapsulator interface {
271
+ Bytes() []byte
272
+ Encapsulate() (sharedKey, ciphertext []byte)
273
+ }
go/src/crypto/crypto_test.go ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package crypto_test
6
+
7
+ import (
8
+ "bytes"
9
+ "crypto"
10
+ "crypto/rand"
11
+ "crypto/rsa"
12
+ "crypto/x509"
13
+ "encoding/pem"
14
+ "errors"
15
+ "internal/testenv"
16
+ "io"
17
+ "io/fs"
18
+ "os"
19
+ "path/filepath"
20
+ "regexp"
21
+ "strings"
22
+ "testing"
23
+ )
24
+
25
+ type messageSignerOnly struct {
26
+ k *rsa.PrivateKey
27
+ }
28
+
29
+ func (s *messageSignerOnly) Public() crypto.PublicKey {
30
+ return s.k.Public()
31
+ }
32
+
33
+ func (s *messageSignerOnly) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) {
34
+ return nil, errors.New("unimplemented")
35
+ }
36
+
37
+ func (s *messageSignerOnly) SignMessage(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
38
+ h := opts.HashFunc().New()
39
+ h.Write(msg)
40
+ digest := h.Sum(nil)
41
+ return s.k.Sign(rand, digest, opts)
42
+ }
43
+
44
+ func TestSignMessage(t *testing.T) {
45
+ block, _ := pem.Decode([]byte(strings.ReplaceAll(
46
+ `-----BEGIN RSA TESTING KEY-----
47
+ MIIEowIBAAKCAQEAsPnoGUOnrpiSqt4XynxA+HRP7S+BSObI6qJ7fQAVSPtRkqso
48
+ tWxQYLEYzNEx5ZSHTGypibVsJylvCfuToDTfMul8b/CZjP2Ob0LdpYrNH6l5hvFE
49
+ 89FU1nZQF15oVLOpUgA7wGiHuEVawrGfey92UE68mOyUVXGweJIVDdxqdMoPvNNU
50
+ l86BU02vlBiESxOuox+dWmuVV7vfYZ79Toh/LUK43YvJh+rhv4nKuF7iHjVjBd9s
51
+ B6iDjj70HFldzOQ9r8SRI+9NirupPTkF5AKNe6kUhKJ1luB7S27ZkvB3tSTT3P59
52
+ 3VVJvnzOjaA1z6Cz+4+eRvcysqhrRgFlwI9TEwIDAQABAoIBAEEYiyDP29vCzx/+
53
+ dS3LqnI5BjUuJhXUnc6AWX/PCgVAO+8A+gZRgvct7PtZb0sM6P9ZcLrweomlGezI
54
+ FrL0/6xQaa8bBr/ve/a8155OgcjFo6fZEw3Dz7ra5fbSiPmu4/b/kvrg+Br1l77J
55
+ aun6uUAs1f5B9wW+vbR7tzbT/mxaUeDiBzKpe15GwcvbJtdIVMa2YErtRjc1/5B2
56
+ BGVXyvlJv0SIlcIEMsHgnAFOp1ZgQ08aDzvilLq8XVMOahAhP1O2A3X8hKdXPyrx
57
+ IVWE9bS9ptTo+eF6eNl+d7htpKGEZHUxinoQpWEBTv+iOoHsVunkEJ3vjLP3lyI/
58
+ fY0NQ1ECgYEA3RBXAjgvIys2gfU3keImF8e/TprLge1I2vbWmV2j6rZCg5r/AS0u
59
+ pii5CvJ5/T5vfJPNgPBy8B/yRDs+6PJO1GmnlhOkG9JAIPkv0RBZvR0PMBtbp6nT
60
+ Y3yo1lwamBVBfY6rc0sLTzosZh2aGoLzrHNMQFMGaauORzBFpY5lU50CgYEAzPHl
61
+ u5DI6Xgep1vr8QvCUuEesCOgJg8Yh1UqVoY/SmQh6MYAv1I9bLGwrb3WW/7kqIoD
62
+ fj0aQV5buVZI2loMomtU9KY5SFIsPV+JuUpy7/+VE01ZQM5FdY8wiYCQiVZYju9X
63
+ Wz5LxMNoz+gT7pwlLCsC4N+R8aoBk404aF1gum8CgYAJ7VTq7Zj4TFV7Soa/T1eE
64
+ k9y8a+kdoYk3BASpCHJ29M5R2KEA7YV9wrBklHTz8VzSTFTbKHEQ5W5csAhoL5Fo
65
+ qoHzFFi3Qx7MHESQb9qHyolHEMNx6QdsHUn7rlEnaTTyrXh3ifQtD6C0yTmFXUIS
66
+ CW9wKApOrnyKJ9nI0HcuZQKBgQCMtoV6e9VGX4AEfpuHvAAnMYQFgeBiYTkBKltQ
67
+ XwozhH63uMMomUmtSG87Sz1TmrXadjAhy8gsG6I0pWaN7QgBuFnzQ/HOkwTm+qKw
68
+ AsrZt4zeXNwsH7QXHEJCFnCmqw9QzEoZTrNtHJHpNboBuVnYcoueZEJrP8OnUG3r
69
+ UjmopwKBgAqB2KYYMUqAOvYcBnEfLDmyZv9BTVNHbR2lKkMYqv5LlvDaBxVfilE0
70
+ 2riO4p6BaAdvzXjKeRrGNEKoHNBpOSfYCOM16NjL8hIZB1CaV3WbT5oY+jp7Mzd5
71
+ 7d56RZOE+ERK2uz/7JX9VSsM/LbH9pJibd4e8mikDS9ntciqOH/3
72
+ -----END RSA TESTING KEY-----`, "TESTING KEY", "PRIVATE KEY")))
73
+ k, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
74
+
75
+ msg := []byte("hello :)")
76
+
77
+ h := crypto.SHA256.New()
78
+ h.Write(msg)
79
+ digest := h.Sum(nil)
80
+
81
+ sig, err := crypto.SignMessage(k, rand.Reader, msg, &rsa.PSSOptions{Hash: crypto.SHA256})
82
+ if err != nil {
83
+ t.Fatalf("SignMessage failed with Signer: %s", err)
84
+ }
85
+ if err := rsa.VerifyPSS(&k.PublicKey, crypto.SHA256, digest, sig, nil); err != nil {
86
+ t.Errorf("VerifyPSS failed for Signer signature: %s", err)
87
+ }
88
+
89
+ sig, err = crypto.SignMessage(&messageSignerOnly{k}, rand.Reader, msg, &rsa.PSSOptions{Hash: crypto.SHA256})
90
+ if err != nil {
91
+ t.Fatalf("SignMessage failed with MessageSigner: %s", err)
92
+ }
93
+ if err := rsa.VerifyPSS(&k.PublicKey, crypto.SHA256, digest, sig, nil); err != nil {
94
+ t.Errorf("VerifyPSS failed for MessageSigner signature: %s", err)
95
+ }
96
+ }
97
+
98
+ func TestDisallowedAssemblyInstructions(t *testing.T) {
99
+ // This test enforces the cryptography assembly policy rule that we do not
100
+ // use BYTE or WORD instructions, since these instructions can obscure what
101
+ // the assembly is actually doing. If we do not support specific
102
+ // instructions in the assembler, we should not be using them until we do.
103
+ //
104
+ // Instead of using the output of the 'go tool asm' tool, we take the simple
105
+ // approach and just search the text of .s files for usage of BYTE and WORD.
106
+ // We do this because the assembler itself will sometimes insert WORD
107
+ // instructions for things like function preambles etc.
108
+
109
+ boringSigPath := filepath.Join("internal", "boring", "sig")
110
+
111
+ matcher, err := regexp.Compile(`(^|;)\s(BYTE|WORD)\s`)
112
+ if err != nil {
113
+ t.Fatal(err)
114
+ }
115
+ if err := filepath.WalkDir(filepath.Join(testenv.GOROOT(t), "src/crypto"), func(path string, d fs.DirEntry, err error) error {
116
+ if err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ if d.IsDir() || !strings.HasSuffix(path, ".s") {
120
+ return nil
121
+ }
122
+ if strings.Contains(path, boringSigPath) {
123
+ return nil
124
+ }
125
+
126
+ f, err := os.ReadFile(path)
127
+ if err != nil {
128
+ t.Fatal(err)
129
+ }
130
+
131
+ i := 1
132
+ for line := range bytes.Lines(f) {
133
+ if matcher.Match(line) {
134
+ t.Errorf("%s:%d assembly contains BYTE or WORD instruction (%q)", path, i, string(line))
135
+ }
136
+ i++
137
+ }
138
+
139
+ return nil
140
+ }); err != nil {
141
+ t.Fatal(err)
142
+ }
143
+ }
go/src/crypto/issue21104_test.go ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package crypto_test
6
+
7
+ import (
8
+ "crypto/aes"
9
+ "crypto/cipher"
10
+ "crypto/rc4"
11
+ "testing"
12
+ )
13
+
14
+ func TestRC4OutOfBoundsWrite(t *testing.T) {
15
+ // This cipherText is encrypted "0123456789"
16
+ cipherText := []byte{238, 41, 187, 114, 151, 2, 107, 13, 178, 63}
17
+ cipher, err := rc4.NewCipher([]byte{0})
18
+ if err != nil {
19
+ panic(err)
20
+ }
21
+ test(t, "RC4", cipherText, cipher.XORKeyStream)
22
+ }
23
+ func TestCTROutOfBoundsWrite(t *testing.T) {
24
+ testBlock(t, "CTR", cipher.NewCTR)
25
+ }
26
+ func TestOFBOutOfBoundsWrite(t *testing.T) {
27
+ testBlock(t, "OFB", cipher.NewOFB)
28
+ }
29
+ func TestCFBEncryptOutOfBoundsWrite(t *testing.T) {
30
+ testBlock(t, "CFB Encrypt", cipher.NewCFBEncrypter)
31
+ }
32
+ func TestCFBDecryptOutOfBoundsWrite(t *testing.T) {
33
+ testBlock(t, "CFB Decrypt", cipher.NewCFBDecrypter)
34
+ }
35
+ func testBlock(t *testing.T, name string, newCipher func(cipher.Block, []byte) cipher.Stream) {
36
+ // This cipherText is encrypted "0123456789"
37
+ cipherText := []byte{86, 216, 121, 231, 219, 191, 26, 12, 176, 117}
38
+ var iv, key [16]byte
39
+ block, err := aes.NewCipher(key[:])
40
+ if err != nil {
41
+ panic(err)
42
+ }
43
+ stream := newCipher(block, iv[:])
44
+ test(t, name, cipherText, stream.XORKeyStream)
45
+ }
46
+ func test(t *testing.T, name string, cipherText []byte, xor func([]byte, []byte)) {
47
+ want := "abcdefghij"
48
+ plainText := []byte(want)
49
+ shorterLen := len(cipherText) / 2
50
+ defer func() {
51
+ err := recover()
52
+ if err == nil {
53
+ t.Errorf("%v XORKeyStream expected to panic on len(dst) < len(src), but didn't", name)
54
+ }
55
+ const plain = "0123456789"
56
+ if plainText[shorterLen] == plain[shorterLen] {
57
+ t.Errorf("%v XORKeyStream did out of bounds write, want %v, got %v", name, want, string(plainText))
58
+ }
59
+ }()
60
+ xor(plainText[:shorterLen], cipherText)
61
+ }
go/src/crypto/purego_test.go ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package crypto_test
6
+
7
+ import (
8
+ "go/build"
9
+ "internal/testenv"
10
+ "log"
11
+ "os"
12
+ "strings"
13
+ "testing"
14
+ )
15
+
16
+ // TestPureGoTag checks that when built with the purego build tag, crypto
17
+ // packages don't require any assembly. This is used by alternative compilers
18
+ // such as TinyGo. See also the "crypto/...:purego" test in cmd/dist, which
19
+ // ensures the packages build correctly.
20
+ func TestPureGoTag(t *testing.T) {
21
+ cmd := testenv.Command(t, testenv.GoToolPath(t), "list", "-e", "crypto/...", "math/big")
22
+ cmd = testenv.CleanCmdEnv(cmd)
23
+ cmd.Env = append(cmd.Environ(), "GOOS=linux", "GOFIPS140=off")
24
+ cmd.Stderr = os.Stderr
25
+ out, err := cmd.Output()
26
+ if err != nil {
27
+ log.Fatalf("loading package list: %v\n%s", err, out)
28
+ }
29
+ pkgs := strings.Split(strings.TrimSpace(string(out)), "\n")
30
+
31
+ cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "dist", "list")
32
+ cmd.Stderr = os.Stderr
33
+ out, err = testenv.CleanCmdEnv(cmd).Output()
34
+ if err != nil {
35
+ log.Fatalf("loading architecture list: %v\n%s", err, out)
36
+ }
37
+ allGOARCH := make(map[string]bool)
38
+ for _, pair := range strings.Split(strings.TrimSpace(string(out)), "\n") {
39
+ GOARCH := strings.Split(pair, "/")[1]
40
+ allGOARCH[GOARCH] = true
41
+ }
42
+
43
+ for _, pkgName := range pkgs {
44
+ if strings.Contains(pkgName, "/boring") {
45
+ continue
46
+ }
47
+
48
+ for GOARCH := range allGOARCH {
49
+ context := build.Context{
50
+ GOOS: "linux", // darwin has custom assembly
51
+ GOARCH: GOARCH,
52
+ GOROOT: testenv.GOROOT(t),
53
+ Compiler: build.Default.Compiler,
54
+ BuildTags: []string{"purego", "math_big_pure_go"},
55
+ }
56
+
57
+ pkg, err := context.Import(pkgName, "", 0)
58
+ if err != nil {
59
+ t.Fatal(err)
60
+ }
61
+ if len(pkg.SFiles) == 0 {
62
+ continue
63
+ }
64
+ t.Errorf("package %s has purego assembly files on %s: %v", pkgName, GOARCH, pkg.SFiles)
65
+ }
66
+ }
67
+ }
go/src/embed/embed.go ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package embed provides access to files embedded in the running Go program.
6
+ //
7
+ // Go source files that import "embed" can use the //go:embed directive
8
+ // to initialize a variable of type string, []byte, or [FS] with the contents of
9
+ // files read from the package directory or subdirectories at compile time.
10
+ //
11
+ // For example, here are three ways to embed a file named hello.txt
12
+ // and then print its contents at run time.
13
+ //
14
+ // Embedding one file into a string:
15
+ //
16
+ // import _ "embed"
17
+ //
18
+ // //go:embed hello.txt
19
+ // var s string
20
+ // print(s)
21
+ //
22
+ // Embedding one file into a slice of bytes:
23
+ //
24
+ // import _ "embed"
25
+ //
26
+ // //go:embed hello.txt
27
+ // var b []byte
28
+ // print(string(b))
29
+ //
30
+ // Embedded one or more files into a file system:
31
+ //
32
+ // import "embed"
33
+ //
34
+ // //go:embed hello.txt
35
+ // var f embed.FS
36
+ // data, _ := f.ReadFile("hello.txt")
37
+ // print(string(data))
38
+ //
39
+ // # Directives
40
+ //
41
+ // A //go:embed directive above a variable declaration specifies which files to embed,
42
+ // using one or more path.Match patterns.
43
+ //
44
+ // The directive must immediately precede a line containing the declaration of a single variable.
45
+ // Only blank lines and ‘//’ line comments are permitted between the directive and the declaration.
46
+ //
47
+ // The type of the variable must be a string type, or a slice of a byte type,
48
+ // or [FS] (or an alias of [FS]).
49
+ //
50
+ // For example:
51
+ //
52
+ // package server
53
+ //
54
+ // import "embed"
55
+ //
56
+ // // content holds our static web server content.
57
+ // //go:embed image/* template/*
58
+ // //go:embed html/index.html
59
+ // var content embed.FS
60
+ //
61
+ // The Go build system will recognize the directives and arrange for the declared variable
62
+ // (in the example above, content) to be populated with the matching files from the file system.
63
+ //
64
+ // The //go:embed directive accepts multiple space-separated patterns for
65
+ // brevity, but it can also be repeated, to avoid very long lines when there are
66
+ // many patterns. The patterns are interpreted relative to the package directory
67
+ // containing the source file. The path separator is a forward slash, even on
68
+ // Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements,
69
+ // nor may they begin or end with a slash. To match everything in the current
70
+ // directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in
71
+ // their names, patterns can be written as Go double-quoted or back-quoted
72
+ // string literals.
73
+ //
74
+ // If a pattern names a directory, all files in the subtree rooted at that directory are
75
+ // embedded (recursively), except that files with names beginning with ‘.’ or ‘_’
76
+ // are excluded. So the variable in the above example is almost equivalent to:
77
+ //
78
+ // // content is our static web server content.
79
+ // //go:embed image template html/index.html
80
+ // var content embed.FS
81
+ //
82
+ // The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not.
83
+ // Neither embeds ‘image/dir/.tempfile’.
84
+ //
85
+ // If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed
86
+ // to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds
87
+ // both ‘image/.tempfile’ and ‘image/dir/.tempfile’.
88
+ //
89
+ // The //go:embed directive can be used with both exported and unexported variables,
90
+ // depending on whether the package wants to make the data available to other packages.
91
+ // It can only be used with variables at package scope, not with local variables.
92
+ //
93
+ // Patterns must not match files outside the package's module, such as ‘.git/*’, symbolic links,
94
+ // 'vendor/', or any directories containing go.mod (these are separate modules).
95
+ // Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :.
96
+ // Matches for empty directories are ignored. After that, each pattern in a //go:embed line
97
+ // must match at least one file or non-empty directory.
98
+ //
99
+ // If any patterns are invalid or have invalid matches, the build will fail.
100
+ //
101
+ // # Strings and Bytes
102
+ //
103
+ // The //go:embed line for a variable of type string or []byte can have only a single pattern,
104
+ // and that pattern can match only a single file. The string or []byte is initialized with
105
+ // the contents of that file.
106
+ //
107
+ // The //go:embed directive requires importing "embed", even when using a string or []byte.
108
+ // In source files that don't refer to [embed.FS], use a blank import (import _ "embed").
109
+ //
110
+ // # File Systems
111
+ //
112
+ // For embedding a single file, a variable of type string or []byte is often best.
113
+ // The [FS] type enables embedding a tree of files, such as a directory of static
114
+ // web server content, as in the example above.
115
+ //
116
+ // FS implements the [io/fs] package's [FS] interface, so it can be used with any package that
117
+ // understands file systems, including [net/http], [text/template], and [html/template].
118
+ //
119
+ // For example, given the content variable in the example above, we can write:
120
+ //
121
+ // http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
122
+ //
123
+ // template.ParseFS(content, "*.tmpl")
124
+ //
125
+ // # Tools
126
+ //
127
+ // To support tools that analyze Go packages, the patterns found in //go:embed lines
128
+ // are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns,
129
+ // and XTestEmbedPatterns fields in the “go help list” output.
130
+ package embed
131
+
132
+ import (
133
+ "errors"
134
+ "internal/bytealg"
135
+ "internal/stringslite"
136
+ "io"
137
+ "io/fs"
138
+ "time"
139
+ )
140
+
141
+ // An FS is a read-only collection of files, usually initialized with a //go:embed directive.
142
+ // When declared without a //go:embed directive, an FS is an empty file system.
143
+ //
144
+ // An FS is a read-only value, so it is safe to use from multiple goroutines
145
+ // simultaneously and also safe to assign values of type FS to each other.
146
+ //
147
+ // FS implements fs.FS, so it can be used with any package that understands
148
+ // file system interfaces, including net/http, text/template, and html/template.
149
+ //
150
+ // See the package documentation for more details about initializing an FS.
151
+ type FS struct {
152
+ // The compiler knows the layout of this struct.
153
+ // See cmd/compile/internal/staticdata's WriteEmbed.
154
+ //
155
+ // The files list is sorted by name but not by simple string comparison.
156
+ // Instead, each file's name takes the form "dir/elem" or "dir/elem/".
157
+ // The optional trailing slash indicates that the file is itself a directory.
158
+ // The files list is sorted first by dir (if dir is missing, it is taken to be ".")
159
+ // and then by base, so this list of files:
160
+ //
161
+ // p
162
+ // q/
163
+ // q/r
164
+ // q/s/
165
+ // q/s/t
166
+ // q/s/u
167
+ // q/v
168
+ // w
169
+ //
170
+ // is actually sorted as:
171
+ //
172
+ // p # dir=. elem=p
173
+ // q/ # dir=. elem=q
174
+ // w # dir=. elem=w
175
+ // q/r # dir=q elem=r
176
+ // q/s/ # dir=q elem=s
177
+ // q/v # dir=q elem=v
178
+ // q/s/t # dir=q/s elem=t
179
+ // q/s/u # dir=q/s elem=u
180
+ //
181
+ // This order brings directory contents together in contiguous sections
182
+ // of the list, allowing a directory read to use binary search to find
183
+ // the relevant sequence of entries.
184
+ files *[]file
185
+ }
186
+
187
+ // split splits the name into dir and elem as described in the
188
+ // comment in the FS struct above. isDir reports whether the
189
+ // final trailing slash was present, indicating that name is a directory.
190
+ func split(name string) (dir, elem string, isDir bool) {
191
+ name, isDir = stringslite.CutSuffix(name, "/")
192
+ i := bytealg.LastIndexByteString(name, '/')
193
+ if i < 0 {
194
+ return ".", name, isDir
195
+ }
196
+ return name[:i], name[i+1:], isDir
197
+ }
198
+
199
+ var (
200
+ _ fs.ReadDirFS = FS{}
201
+ _ fs.ReadFileFS = FS{}
202
+ )
203
+
204
+ // A file is a single file in the FS.
205
+ // It implements fs.FileInfo and fs.DirEntry.
206
+ type file struct {
207
+ // The compiler knows the layout of this struct.
208
+ // See cmd/compile/internal/staticdata's WriteEmbed.
209
+ name string
210
+ data string
211
+ hash [16]byte // truncated SHA256 hash
212
+ }
213
+
214
+ var (
215
+ _ fs.FileInfo = (*file)(nil)
216
+ _ fs.DirEntry = (*file)(nil)
217
+ )
218
+
219
+ func (f *file) Name() string { _, elem, _ := split(f.name); return elem }
220
+ func (f *file) Size() int64 { return int64(len(f.data)) }
221
+ func (f *file) ModTime() time.Time { return time.Time{} }
222
+ func (f *file) IsDir() bool { _, _, isDir := split(f.name); return isDir }
223
+ func (f *file) Sys() any { return nil }
224
+ func (f *file) Type() fs.FileMode { return f.Mode().Type() }
225
+ func (f *file) Info() (fs.FileInfo, error) { return f, nil }
226
+
227
+ func (f *file) Mode() fs.FileMode {
228
+ if f.IsDir() {
229
+ return fs.ModeDir | 0555
230
+ }
231
+ return 0444
232
+ }
233
+
234
+ func (f *file) String() string {
235
+ return fs.FormatFileInfo(f)
236
+ }
237
+
238
+ // dotFile is a file for the root directory,
239
+ // which is omitted from the files list in a FS.
240
+ var dotFile = &file{name: "./"}
241
+
242
+ // lookup returns the named file, or nil if it is not present.
243
+ func (f FS) lookup(name string) *file {
244
+ if !fs.ValidPath(name) {
245
+ // The compiler should never emit a file with an invalid name,
246
+ // so this check is not strictly necessary (if name is invalid,
247
+ // we shouldn't find a match below), but it's a good backstop anyway.
248
+ return nil
249
+ }
250
+ if name == "." {
251
+ return dotFile
252
+ }
253
+ if f.files == nil {
254
+ return nil
255
+ }
256
+
257
+ // Binary search to find where name would be in the list,
258
+ // and then check if name is at that position.
259
+ dir, elem, _ := split(name)
260
+ files := *f.files
261
+ i := sortSearch(len(files), func(i int) bool {
262
+ idir, ielem, _ := split(files[i].name)
263
+ return idir > dir || idir == dir && ielem >= elem
264
+ })
265
+ if i < len(files) && stringslite.TrimSuffix(files[i].name, "/") == name {
266
+ return &files[i]
267
+ }
268
+ return nil
269
+ }
270
+
271
+ // readDir returns the list of files corresponding to the directory dir.
272
+ func (f FS) readDir(dir string) []file {
273
+ if f.files == nil {
274
+ return nil
275
+ }
276
+ // Binary search to find where dir starts and ends in the list
277
+ // and then return that slice of the list.
278
+ files := *f.files
279
+ i := sortSearch(len(files), func(i int) bool {
280
+ idir, _, _ := split(files[i].name)
281
+ return idir >= dir
282
+ })
283
+ j := sortSearch(len(files), func(j int) bool {
284
+ jdir, _, _ := split(files[j].name)
285
+ return jdir > dir
286
+ })
287
+ return files[i:j]
288
+ }
289
+
290
+ // Open opens the named file for reading and returns it as an [fs.File].
291
+ //
292
+ // The returned file implements [io.Seeker] and [io.ReaderAt] when the file is not a directory.
293
+ func (f FS) Open(name string) (fs.File, error) {
294
+ file := f.lookup(name)
295
+ if file == nil {
296
+ return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
297
+ }
298
+ if file.IsDir() {
299
+ return &openDir{file, f.readDir(name), 0}, nil
300
+ }
301
+ return &openFile{file, 0}, nil
302
+ }
303
+
304
+ // ReadDir reads and returns the entire named directory.
305
+ func (f FS) ReadDir(name string) ([]fs.DirEntry, error) {
306
+ file, err := f.Open(name)
307
+ if err != nil {
308
+ return nil, err
309
+ }
310
+ dir, ok := file.(*openDir)
311
+ if !ok {
312
+ return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("not a directory")}
313
+ }
314
+ list := make([]fs.DirEntry, len(dir.files))
315
+ for i := range list {
316
+ list[i] = &dir.files[i]
317
+ }
318
+ return list, nil
319
+ }
320
+
321
+ // ReadFile reads and returns the content of the named file.
322
+ func (f FS) ReadFile(name string) ([]byte, error) {
323
+ file, err := f.Open(name)
324
+ if err != nil {
325
+ return nil, err
326
+ }
327
+ ofile, ok := file.(*openFile)
328
+ if !ok {
329
+ return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("is a directory")}
330
+ }
331
+ return []byte(ofile.f.data), nil
332
+ }
333
+
334
+ // An openFile is a regular file open for reading.
335
+ type openFile struct {
336
+ f *file // the file itself
337
+ offset int64 // current read offset
338
+ }
339
+
340
+ var (
341
+ _ io.Seeker = (*openFile)(nil)
342
+ _ io.ReaderAt = (*openFile)(nil)
343
+ )
344
+
345
+ func (f *openFile) Close() error { return nil }
346
+ func (f *openFile) Stat() (fs.FileInfo, error) { return f.f, nil }
347
+
348
+ func (f *openFile) Read(b []byte) (int, error) {
349
+ if f.offset >= int64(len(f.f.data)) {
350
+ return 0, io.EOF
351
+ }
352
+ if f.offset < 0 {
353
+ return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid}
354
+ }
355
+ n := copy(b, f.f.data[f.offset:])
356
+ f.offset += int64(n)
357
+ return n, nil
358
+ }
359
+
360
+ func (f *openFile) Seek(offset int64, whence int) (int64, error) {
361
+ switch whence {
362
+ case 0:
363
+ // offset += 0
364
+ case 1:
365
+ offset += f.offset
366
+ case 2:
367
+ offset += int64(len(f.f.data))
368
+ }
369
+ if offset < 0 || offset > int64(len(f.f.data)) {
370
+ return 0, &fs.PathError{Op: "seek", Path: f.f.name, Err: fs.ErrInvalid}
371
+ }
372
+ f.offset = offset
373
+ return offset, nil
374
+ }
375
+
376
+ func (f *openFile) ReadAt(b []byte, offset int64) (int, error) {
377
+ if offset < 0 || offset > int64(len(f.f.data)) {
378
+ return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid}
379
+ }
380
+ n := copy(b, f.f.data[offset:])
381
+ if n < len(b) {
382
+ return n, io.EOF
383
+ }
384
+ return n, nil
385
+ }
386
+
387
+ // An openDir is a directory open for reading.
388
+ type openDir struct {
389
+ f *file // the directory file itself
390
+ files []file // the directory contents
391
+ offset int // the read offset, an index into the files slice
392
+ }
393
+
394
+ func (d *openDir) Close() error { return nil }
395
+ func (d *openDir) Stat() (fs.FileInfo, error) { return d.f, nil }
396
+
397
+ func (d *openDir) Read([]byte) (int, error) {
398
+ return 0, &fs.PathError{Op: "read", Path: d.f.name, Err: errors.New("is a directory")}
399
+ }
400
+
401
+ func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) {
402
+ n := len(d.files) - d.offset
403
+ if n == 0 {
404
+ if count <= 0 {
405
+ return nil, nil
406
+ }
407
+ return nil, io.EOF
408
+ }
409
+ if count > 0 && n > count {
410
+ n = count
411
+ }
412
+ list := make([]fs.DirEntry, n)
413
+ for i := range list {
414
+ list[i] = &d.files[d.offset+i]
415
+ }
416
+ d.offset += n
417
+ return list, nil
418
+ }
419
+
420
+ // sortSearch is like sort.Search, avoiding an import.
421
+ func sortSearch(n int, f func(int) bool) int {
422
+ // Define f(-1) == false and f(n) == true.
423
+ // Invariant: f(i-1) == false, f(j) == true.
424
+ i, j := 0, n
425
+ for i < j {
426
+ h := int(uint(i+j) >> 1) // avoid overflow when computing h
427
+ // i ≤ h < j
428
+ if !f(h) {
429
+ i = h + 1 // preserves f(i-1) == false
430
+ } else {
431
+ j = h // preserves f(j) == true
432
+ }
433
+ }
434
+ // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
435
+ return i
436
+ }
go/src/embed/example_test.go ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package embed_test
6
+
7
+ import (
8
+ "embed"
9
+ "log"
10
+ "net/http"
11
+ )
12
+
13
+ //go:embed internal/embedtest/testdata/*.txt
14
+ var content embed.FS
15
+
16
+ func Example() {
17
+ mux := http.NewServeMux()
18
+ mux.Handle("/", http.FileServer(http.FS(content)))
19
+ err := http.ListenAndServe(":8080", mux)
20
+ if err != nil {
21
+ log.Fatal(err)
22
+ }
23
+ }
go/src/encoding/encoding.go ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package encoding defines interfaces shared by other packages that
6
+ // convert data to and from byte-level and textual representations.
7
+ // Packages that check for these interfaces include encoding/gob,
8
+ // encoding/json, and encoding/xml. As a result, implementing an
9
+ // interface once can make a type useful in multiple encodings.
10
+ // Standard types that implement these interfaces include time.Time and net.IP.
11
+ // The interfaces come in pairs that produce and consume encoded data.
12
+ //
13
+ // Adding encoding/decoding methods to existing types may constitute a breaking change,
14
+ // as they can be used for serialization in communicating with programs
15
+ // written with different library versions.
16
+ // The policy for packages maintained by the Go project is to only allow
17
+ // the addition of marshaling functions if no existing, reasonable marshaling exists.
18
+ package encoding
19
+
20
+ // BinaryMarshaler is the interface implemented by an object that can
21
+ // marshal itself into a binary form.
22
+ //
23
+ // MarshalBinary encodes the receiver into a binary form and returns the result.
24
+ type BinaryMarshaler interface {
25
+ MarshalBinary() (data []byte, err error)
26
+ }
27
+
28
+ // BinaryUnmarshaler is the interface implemented by an object that can
29
+ // unmarshal a binary representation of itself.
30
+ //
31
+ // UnmarshalBinary must be able to decode the form generated by MarshalBinary.
32
+ // UnmarshalBinary must copy the data if it wishes to retain the data
33
+ // after returning.
34
+ type BinaryUnmarshaler interface {
35
+ UnmarshalBinary(data []byte) error
36
+ }
37
+
38
+ // BinaryAppender is the interface implemented by an object
39
+ // that can append the binary representation of itself.
40
+ // If a type implements both [BinaryAppender] and [BinaryMarshaler],
41
+ // then v.MarshalBinary() must be semantically identical to v.AppendBinary(nil).
42
+ type BinaryAppender interface {
43
+ // AppendBinary appends the binary representation of itself to the end of b
44
+ // (allocating a larger slice if necessary) and returns the updated slice.
45
+ //
46
+ // Implementations must not retain b, nor mutate any bytes within b[:len(b)].
47
+ AppendBinary(b []byte) ([]byte, error)
48
+ }
49
+
50
+ // TextMarshaler is the interface implemented by an object that can
51
+ // marshal itself into a textual form.
52
+ //
53
+ // MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
54
+ type TextMarshaler interface {
55
+ MarshalText() (text []byte, err error)
56
+ }
57
+
58
+ // TextUnmarshaler is the interface implemented by an object that can
59
+ // unmarshal a textual representation of itself.
60
+ //
61
+ // UnmarshalText must be able to decode the form generated by MarshalText.
62
+ // UnmarshalText must copy the text if it wishes to retain the text
63
+ // after returning.
64
+ type TextUnmarshaler interface {
65
+ UnmarshalText(text []byte) error
66
+ }
67
+
68
+ // TextAppender is the interface implemented by an object
69
+ // that can append the textual representation of itself.
70
+ // If a type implements both [TextAppender] and [TextMarshaler],
71
+ // then v.MarshalText() must be semantically identical to v.AppendText(nil).
72
+ type TextAppender interface {
73
+ // AppendText appends the textual representation of itself to the end of b
74
+ // (allocating a larger slice if necessary) and returns the updated slice.
75
+ //
76
+ // Implementations must not retain b, nor mutate any bytes within b[:len(b)].
77
+ AppendText(b []byte) ([]byte, error)
78
+ }
go/src/errors/errors.go ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package errors implements functions to manipulate errors.
6
+ //
7
+ // The [New] function creates errors whose only content is a text message.
8
+ //
9
+ // An error e wraps another error if e's type has one of the methods
10
+ //
11
+ // Unwrap() error
12
+ // Unwrap() []error
13
+ //
14
+ // If e.Unwrap() returns a non-nil error w or a slice containing w,
15
+ // then we say that e wraps w. A nil error returned from e.Unwrap()
16
+ // indicates that e does not wrap any error. It is invalid for an
17
+ // Unwrap method to return an []error containing a nil error value.
18
+ //
19
+ // An easy way to create wrapped errors is to call [fmt.Errorf] and apply
20
+ // the %w verb to the error argument:
21
+ //
22
+ // wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
23
+ //
24
+ // Successive unwrapping of an error creates a tree. The [Is] and [As]
25
+ // functions inspect an error's tree by examining first the error
26
+ // itself followed by the tree of each of its children in turn
27
+ // (pre-order, depth-first traversal).
28
+ //
29
+ // See https://go.dev/blog/go1.13-errors for a deeper discussion of the
30
+ // philosophy of wrapping and when to wrap.
31
+ //
32
+ // [Is] examines the tree of its first argument looking for an error that
33
+ // matches the second. It reports whether it finds a match. It should be
34
+ // used in preference to simple equality checks:
35
+ //
36
+ // if errors.Is(err, fs.ErrExist)
37
+ //
38
+ // is preferable to
39
+ //
40
+ // if err == fs.ErrExist
41
+ //
42
+ // because the former will succeed if err wraps [io/fs.ErrExist].
43
+ //
44
+ // [AsType] examines the tree of its argument looking for an error whose
45
+ // type matches its type argument. If it succeeds, it returns the
46
+ // corresponding value of that type and true. Otherwise, it returns the
47
+ // zero value of that type and false. The form
48
+ //
49
+ // if perr, ok := errors.AsType[*fs.PathError](err); ok {
50
+ // fmt.Println(perr.Path)
51
+ // }
52
+ //
53
+ // is preferable to
54
+ //
55
+ // if perr, ok := err.(*fs.PathError); ok {
56
+ // fmt.Println(perr.Path)
57
+ // }
58
+ //
59
+ // because the former will succeed if err wraps an [*io/fs.PathError].
60
+ package errors
61
+
62
+ // New returns an error that formats as the given text.
63
+ // Each call to New returns a distinct error value even if the text is identical.
64
+ func New(text string) error {
65
+ return &errorString{text}
66
+ }
67
+
68
+ // errorString is a trivial implementation of error.
69
+ type errorString struct {
70
+ s string
71
+ }
72
+
73
+ func (e *errorString) Error() string {
74
+ return e.s
75
+ }
76
+
77
+ // ErrUnsupported indicates that a requested operation cannot be performed,
78
+ // because it is unsupported. For example, a call to [os.Link] when using a
79
+ // file system that does not support hard links.
80
+ //
81
+ // Functions and methods should not return this error but should instead
82
+ // return an error including appropriate context that satisfies
83
+ //
84
+ // errors.Is(err, errors.ErrUnsupported)
85
+ //
86
+ // either by directly wrapping ErrUnsupported or by implementing an [Is] method.
87
+ //
88
+ // Functions and methods should document the cases in which an error
89
+ // wrapping this will be returned.
90
+ var ErrUnsupported = New("unsupported operation")
go/src/errors/errors_test.go ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors_test
6
+
7
+ import (
8
+ "errors"
9
+ "testing"
10
+ )
11
+
12
+ func TestNewEqual(t *testing.T) {
13
+ // Different allocations should not be equal.
14
+ if errors.New("abc") == errors.New("abc") {
15
+ t.Errorf(`New("abc") == New("abc")`)
16
+ }
17
+ if errors.New("abc") == errors.New("xyz") {
18
+ t.Errorf(`New("abc") == New("xyz")`)
19
+ }
20
+
21
+ // Same allocation should be equal to itself (not crash).
22
+ err := errors.New("jkl")
23
+ if err != err {
24
+ t.Errorf(`err != err`)
25
+ }
26
+ }
27
+
28
+ func TestErrorMethod(t *testing.T) {
29
+ err := errors.New("abc")
30
+ if err.Error() != "abc" {
31
+ t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
32
+ }
33
+ }
go/src/errors/example_test.go ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2012 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors_test
6
+
7
+ import (
8
+ "errors"
9
+ "fmt"
10
+ "io/fs"
11
+ "os"
12
+ "time"
13
+ )
14
+
15
+ // MyError is an error implementation that includes a time and message.
16
+ type MyError struct {
17
+ When time.Time
18
+ What string
19
+ }
20
+
21
+ func (e MyError) Error() string {
22
+ return fmt.Sprintf("%v: %v", e.When, e.What)
23
+ }
24
+
25
+ func oops() error {
26
+ return MyError{
27
+ time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
28
+ "the file system has gone away",
29
+ }
30
+ }
31
+
32
+ func Example() {
33
+ if err := oops(); err != nil {
34
+ fmt.Println(err)
35
+ }
36
+ // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
37
+ }
38
+
39
+ func ExampleNew() {
40
+ err := errors.New("emit macho dwarf: elf header corrupted")
41
+ if err != nil {
42
+ fmt.Print(err)
43
+ }
44
+ // Output: emit macho dwarf: elf header corrupted
45
+ }
46
+
47
+ func OopsNew() error {
48
+ return errors.New("an error")
49
+ }
50
+
51
+ var ErrSentinel = errors.New("an error")
52
+
53
+ func OopsSentinel() error {
54
+ return ErrSentinel
55
+ }
56
+
57
+ // Each call to [errors.New] returns an unique instance of the error,
58
+ // even if the arguments are the same. To match against errors
59
+ // created by [errors.New], declare a sentinel error and reuse it.
60
+ func ExampleNew_unique() {
61
+ err1 := OopsNew()
62
+ err2 := OopsNew()
63
+ fmt.Println("Errors using distinct errors.New calls:")
64
+ fmt.Printf("Is(%q, %q) = %v\n", err1, err2, errors.Is(err1, err2))
65
+
66
+ err3 := OopsSentinel()
67
+ err4 := OopsSentinel()
68
+ fmt.Println()
69
+ fmt.Println("Errors using a sentinel error:")
70
+ fmt.Printf("Is(%q, %q) = %v\n", err3, err4, errors.Is(err3, err4))
71
+
72
+ // Output:
73
+ // Errors using distinct errors.New calls:
74
+ // Is("an error", "an error") = false
75
+ //
76
+ // Errors using a sentinel error:
77
+ // Is("an error", "an error") = true
78
+ }
79
+
80
+ // The fmt package's Errorf function lets us use the package's formatting
81
+ // features to create descriptive error messages.
82
+ func ExampleNew_errorf() {
83
+ const name, id = "bimmler", 17
84
+ err := fmt.Errorf("user %q (id %d) not found", name, id)
85
+ if err != nil {
86
+ fmt.Print(err)
87
+ }
88
+ // Output: user "bimmler" (id 17) not found
89
+ }
90
+
91
+ func ExampleJoin() {
92
+ err1 := errors.New("err1")
93
+ err2 := errors.New("err2")
94
+ err := errors.Join(err1, err2)
95
+ fmt.Println(err)
96
+ if errors.Is(err, err1) {
97
+ fmt.Println("err is err1")
98
+ }
99
+ if errors.Is(err, err2) {
100
+ fmt.Println("err is err2")
101
+ }
102
+ fmt.Println(err.(interface{ Unwrap() []error }).Unwrap())
103
+ // Output:
104
+ // err1
105
+ // err2
106
+ // err is err1
107
+ // err is err2
108
+ // [err1 err2]
109
+ }
110
+
111
+ func ExampleIs() {
112
+ if _, err := os.Open("non-existing"); err != nil {
113
+ if errors.Is(err, fs.ErrNotExist) {
114
+ fmt.Println("file does not exist")
115
+ } else {
116
+ fmt.Println(err)
117
+ }
118
+ }
119
+
120
+ // Output:
121
+ // file does not exist
122
+ }
123
+
124
+ type MyIsError struct {
125
+ err string
126
+ }
127
+
128
+ func (e MyIsError) Error() string {
129
+ return e.err
130
+ }
131
+ func (e MyIsError) Is(err error) bool {
132
+ return err == fs.ErrPermission
133
+ }
134
+
135
+ // Custom errors can implement a method "Is(error) bool" to match other error values,
136
+ // overriding the default matching of [errors.Is].
137
+ func ExampleIs_custom_match() {
138
+ var err error = MyIsError{"an error"}
139
+ fmt.Println("Error equals fs.ErrPermission:", err == fs.ErrPermission)
140
+ fmt.Println("Error is fs.ErrPermission:", errors.Is(err, fs.ErrPermission))
141
+
142
+ // Output:
143
+ // Error equals fs.ErrPermission: false
144
+ // Error is fs.ErrPermission: true
145
+ }
146
+
147
+ func ExampleAs() {
148
+ if _, err := os.Open("non-existing"); err != nil {
149
+ var pathError *fs.PathError
150
+ if errors.As(err, &pathError) {
151
+ fmt.Println("Failed at path:", pathError.Path)
152
+ } else {
153
+ fmt.Println(err)
154
+ }
155
+ }
156
+
157
+ // Output:
158
+ // Failed at path: non-existing
159
+ }
160
+
161
+ func ExampleAsType() {
162
+ if _, err := os.Open("non-existing"); err != nil {
163
+ if pathError, ok := errors.AsType[*fs.PathError](err); ok {
164
+ fmt.Println("Failed at path:", pathError.Path)
165
+ } else {
166
+ fmt.Println(err)
167
+ }
168
+ }
169
+ // Output:
170
+ // Failed at path: non-existing
171
+ }
172
+
173
+ type MyAsError struct {
174
+ err string
175
+ }
176
+
177
+ func (e MyAsError) Error() string {
178
+ return e.err
179
+ }
180
+ func (e MyAsError) As(target any) bool {
181
+ pe, ok := target.(**fs.PathError)
182
+ if !ok {
183
+ return false
184
+ }
185
+ *pe = &fs.PathError{
186
+ Op: "custom",
187
+ Path: "/",
188
+ Err: errors.New(e.err),
189
+ }
190
+ return true
191
+ }
192
+
193
+ // Custom errors can implement a method "As(any) bool" to match against other error types,
194
+ // overriding the default matching of [errors.As].
195
+ func ExampleAs_custom_match() {
196
+ var err error = MyAsError{"an error"}
197
+ fmt.Println("Error:", err)
198
+ fmt.Printf("TypeOf err: %T\n", err)
199
+
200
+ var pathError *fs.PathError
201
+ ok := errors.As(err, &pathError)
202
+ fmt.Println("Error as fs.PathError:", ok)
203
+ fmt.Println("fs.PathError:", pathError)
204
+
205
+ // Output:
206
+ // Error: an error
207
+ // TypeOf err: errors_test.MyAsError
208
+ // Error as fs.PathError: true
209
+ // fs.PathError: custom /: an error
210
+ }
211
+
212
+ // Custom errors can implement a method "As(any) bool" to match against other error types,
213
+ // overriding the default matching of [errors.AsType].
214
+ func ExampleAsType_custom_match() {
215
+ var err error = MyAsError{"an error"}
216
+ fmt.Println("Error:", err)
217
+ fmt.Printf("TypeOf err: %T\n", err)
218
+
219
+ pathError, ok := errors.AsType[*fs.PathError](err)
220
+ fmt.Println("Error as fs.PathError:", ok)
221
+ fmt.Println("fs.PathError:", pathError)
222
+
223
+ // Output:
224
+ // Error: an error
225
+ // TypeOf err: errors_test.MyAsError
226
+ // Error as fs.PathError: true
227
+ // fs.PathError: custom /: an error
228
+ }
229
+
230
+ func ExampleUnwrap() {
231
+ err1 := errors.New("error1")
232
+ err2 := fmt.Errorf("error2: [%w]", err1)
233
+ fmt.Println(err2)
234
+ fmt.Println(errors.Unwrap(err2))
235
+ // Output:
236
+ // error2: [error1]
237
+ // error1
238
+ }
go/src/errors/join.go ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors
6
+
7
+ import (
8
+ "unsafe"
9
+ )
10
+
11
+ // Join returns an error that wraps the given errors.
12
+ // Any nil error values are discarded.
13
+ // Join returns nil if every value in errs is nil.
14
+ // The error formats as the concatenation of the strings obtained
15
+ // by calling the Error method of each element of errs, with a newline
16
+ // between each string.
17
+ //
18
+ // A non-nil error returned by Join implements the Unwrap() []error method.
19
+ // The errors may be inspected with [Is] and [As].
20
+ func Join(errs ...error) error {
21
+ n := 0
22
+ for _, err := range errs {
23
+ if err != nil {
24
+ n++
25
+ }
26
+ }
27
+ if n == 0 {
28
+ return nil
29
+ }
30
+ e := &joinError{
31
+ errs: make([]error, 0, n),
32
+ }
33
+ for _, err := range errs {
34
+ if err != nil {
35
+ e.errs = append(e.errs, err)
36
+ }
37
+ }
38
+ return e
39
+ }
40
+
41
+ type joinError struct {
42
+ errs []error
43
+ }
44
+
45
+ func (e *joinError) Error() string {
46
+ // Since Join returns nil if every value in errs is nil,
47
+ // e.errs cannot be empty.
48
+ if len(e.errs) == 1 {
49
+ return e.errs[0].Error()
50
+ }
51
+
52
+ b := []byte(e.errs[0].Error())
53
+ for _, err := range e.errs[1:] {
54
+ b = append(b, '\n')
55
+ b = append(b, err.Error()...)
56
+ }
57
+ // At this point, b has at least one byte '\n'.
58
+ return unsafe.String(&b[0], len(b))
59
+ }
60
+
61
+ func (e *joinError) Unwrap() []error {
62
+ return e.errs
63
+ }
go/src/errors/join_test.go ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors_test
6
+
7
+ import (
8
+ "errors"
9
+ "reflect"
10
+ "testing"
11
+ )
12
+
13
+ func TestJoinReturnsNil(t *testing.T) {
14
+ if err := errors.Join(); err != nil {
15
+ t.Errorf("errors.Join() = %v, want nil", err)
16
+ }
17
+ if err := errors.Join(nil); err != nil {
18
+ t.Errorf("errors.Join(nil) = %v, want nil", err)
19
+ }
20
+ if err := errors.Join(nil, nil); err != nil {
21
+ t.Errorf("errors.Join(nil, nil) = %v, want nil", err)
22
+ }
23
+ }
24
+
25
+ func TestJoin(t *testing.T) {
26
+ err1 := errors.New("err1")
27
+ err2 := errors.New("err2")
28
+ merr := multiErr{errors.New("err3")}
29
+ for _, test := range []struct {
30
+ errs []error
31
+ want []error
32
+ }{{
33
+ errs: []error{err1},
34
+ want: []error{err1},
35
+ }, {
36
+ errs: []error{err1, err2},
37
+ want: []error{err1, err2},
38
+ }, {
39
+ errs: []error{err1, nil, err2},
40
+ want: []error{err1, err2},
41
+ }, {
42
+ errs: []error{merr},
43
+ want: []error{merr},
44
+ }} {
45
+ got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap()
46
+ if !reflect.DeepEqual(got, test.want) {
47
+ t.Errorf("Join(%v) = %v; want %v", test.errs, got, test.want)
48
+ }
49
+ if len(got) != cap(got) {
50
+ t.Errorf("Join(%v) returns errors with len=%v, cap=%v; want len==cap", test.errs, len(got), cap(got))
51
+ }
52
+ }
53
+ }
54
+
55
+ func TestJoinErrorMethod(t *testing.T) {
56
+ err1 := errors.New("err1")
57
+ err2 := errors.New("err2")
58
+ for _, test := range []struct {
59
+ errs []error
60
+ want string
61
+ }{{
62
+ errs: []error{err1},
63
+ want: "err1",
64
+ }, {
65
+ errs: []error{err1, err2},
66
+ want: "err1\nerr2",
67
+ }, {
68
+ errs: []error{err1, nil, err2},
69
+ want: "err1\nerr2",
70
+ }} {
71
+ got := errors.Join(test.errs...).Error()
72
+ if got != test.want {
73
+ t.Errorf("Join(%v).Error() = %q; want %q", test.errs, got, test.want)
74
+ }
75
+ }
76
+ }
go/src/errors/wrap.go ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors
6
+
7
+ import (
8
+ "internal/reflectlite"
9
+ )
10
+
11
+ // Unwrap returns the result of calling the Unwrap method on err, if err's
12
+ // type contains an Unwrap method returning error.
13
+ // Otherwise, Unwrap returns nil.
14
+ //
15
+ // Unwrap only calls a method of the form "Unwrap() error".
16
+ // In particular Unwrap does not unwrap errors returned by [Join].
17
+ func Unwrap(err error) error {
18
+ u, ok := err.(interface {
19
+ Unwrap() error
20
+ })
21
+ if !ok {
22
+ return nil
23
+ }
24
+ return u.Unwrap()
25
+ }
26
+
27
+ // Is reports whether any error in err's tree matches target.
28
+ // The target must be comparable.
29
+ //
30
+ // The tree consists of err itself, followed by the errors obtained by repeatedly
31
+ // calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
32
+ // errors, Is examines err followed by a depth-first traversal of its children.
33
+ //
34
+ // An error is considered to match a target if it is equal to that target or if
35
+ // it implements a method Is(error) bool such that Is(target) returns true.
36
+ //
37
+ // An error type might provide an Is method so it can be treated as equivalent
38
+ // to an existing error. For example, if MyError defines
39
+ //
40
+ // func (m MyError) Is(target error) bool { return target == fs.ErrExist }
41
+ //
42
+ // then Is(MyError{}, fs.ErrExist) returns true. See [syscall.Errno.Is] for
43
+ // an example in the standard library. An Is method should only shallowly
44
+ // compare err and the target and not call [Unwrap] on either.
45
+ func Is(err, target error) bool {
46
+ if err == nil || target == nil {
47
+ return err == target
48
+ }
49
+
50
+ isComparable := reflectlite.TypeOf(target).Comparable()
51
+ return is(err, target, isComparable)
52
+ }
53
+
54
+ func is(err, target error, targetComparable bool) bool {
55
+ for {
56
+ if targetComparable && err == target {
57
+ return true
58
+ }
59
+ if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
60
+ return true
61
+ }
62
+ switch x := err.(type) {
63
+ case interface{ Unwrap() error }:
64
+ err = x.Unwrap()
65
+ if err == nil {
66
+ return false
67
+ }
68
+ case interface{ Unwrap() []error }:
69
+ for _, err := range x.Unwrap() {
70
+ if is(err, target, targetComparable) {
71
+ return true
72
+ }
73
+ }
74
+ return false
75
+ default:
76
+ return false
77
+ }
78
+ }
79
+ }
80
+
81
+ // As finds the first error in err's tree that matches target, and if one is found, sets
82
+ // target to that error value and returns true. Otherwise, it returns false.
83
+ //
84
+ // For most uses, prefer [AsType]. As is equivalent to [AsType] but sets its target
85
+ // argument rather than returning the matching error and doesn't require its target
86
+ // argument to implement error.
87
+ //
88
+ // The tree consists of err itself, followed by the errors obtained by repeatedly
89
+ // calling its Unwrap() error or Unwrap() []error method. When err wraps multiple
90
+ // errors, As examines err followed by a depth-first traversal of its children.
91
+ //
92
+ // An error matches target if the error's concrete value is assignable to the value
93
+ // pointed to by target, or if the error has a method As(any) bool such that
94
+ // As(target) returns true. In the latter case, the As method is responsible for
95
+ // setting target.
96
+ //
97
+ // An error type might provide an As method so it can be treated as if it were a
98
+ // different error type.
99
+ //
100
+ // As panics if target is not a non-nil pointer to either a type that implements
101
+ // error, or to any interface type.
102
+ func As(err error, target any) bool {
103
+ if err == nil {
104
+ return false
105
+ }
106
+ if target == nil {
107
+ panic("errors: target cannot be nil")
108
+ }
109
+ val := reflectlite.ValueOf(target)
110
+ typ := val.Type()
111
+ if typ.Kind() != reflectlite.Ptr || val.IsNil() {
112
+ panic("errors: target must be a non-nil pointer")
113
+ }
114
+ targetType := typ.Elem()
115
+ if targetType.Kind() != reflectlite.Interface && !targetType.Implements(errorType) {
116
+ panic("errors: *target must be interface or implement error")
117
+ }
118
+ return as(err, target, val, targetType)
119
+ }
120
+
121
+ func as(err error, target any, targetVal reflectlite.Value, targetType reflectlite.Type) bool {
122
+ for {
123
+ if reflectlite.TypeOf(err).AssignableTo(targetType) {
124
+ targetVal.Elem().Set(reflectlite.ValueOf(err))
125
+ return true
126
+ }
127
+ if x, ok := err.(interface{ As(any) bool }); ok && x.As(target) {
128
+ return true
129
+ }
130
+ switch x := err.(type) {
131
+ case interface{ Unwrap() error }:
132
+ err = x.Unwrap()
133
+ if err == nil {
134
+ return false
135
+ }
136
+ case interface{ Unwrap() []error }:
137
+ for _, err := range x.Unwrap() {
138
+ if err == nil {
139
+ continue
140
+ }
141
+ if as(err, target, targetVal, targetType) {
142
+ return true
143
+ }
144
+ }
145
+ return false
146
+ default:
147
+ return false
148
+ }
149
+ }
150
+ }
151
+
152
+ var errorType = reflectlite.TypeOf((*error)(nil)).Elem()
153
+
154
+ // AsType finds the first error in err's tree that matches the type E, and
155
+ // if one is found, returns that error value and true. Otherwise, it
156
+ // returns the zero value of E and false.
157
+ //
158
+ // The tree consists of err itself, followed by the errors obtained by
159
+ // repeatedly calling its Unwrap() error or Unwrap() []error method. When
160
+ // err wraps multiple errors, AsType examines err followed by a
161
+ // depth-first traversal of its children.
162
+ //
163
+ // An error err matches the type E if the type assertion err.(E) holds,
164
+ // or if the error has a method As(any) bool such that err.As(target)
165
+ // returns true when target is a non-nil *E. In the latter case, the As
166
+ // method is responsible for setting target.
167
+ func AsType[E error](err error) (E, bool) {
168
+ if err == nil {
169
+ var zero E
170
+ return zero, false
171
+ }
172
+ var pe *E // lazily initialized
173
+ return asType(err, &pe)
174
+ }
175
+
176
+ func asType[E error](err error, ppe **E) (_ E, _ bool) {
177
+ for {
178
+ if e, ok := err.(E); ok {
179
+ return e, true
180
+ }
181
+ if x, ok := err.(interface{ As(any) bool }); ok {
182
+ if *ppe == nil {
183
+ *ppe = new(E)
184
+ }
185
+ if x.As(*ppe) {
186
+ return **ppe, true
187
+ }
188
+ }
189
+ switch x := err.(type) {
190
+ case interface{ Unwrap() error }:
191
+ err = x.Unwrap()
192
+ if err == nil {
193
+ return
194
+ }
195
+ case interface{ Unwrap() []error }:
196
+ for _, err := range x.Unwrap() {
197
+ if err == nil {
198
+ continue
199
+ }
200
+ if x, ok := asType(err, ppe); ok {
201
+ return x, true
202
+ }
203
+ }
204
+ return
205
+ default:
206
+ return
207
+ }
208
+ }
209
+ }
go/src/errors/wrap_test.go ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package errors_test
6
+
7
+ import (
8
+ "errors"
9
+ "fmt"
10
+ "io/fs"
11
+ "os"
12
+ "reflect"
13
+ "testing"
14
+ )
15
+
16
+ func TestIs(t *testing.T) {
17
+ err1 := errors.New("1")
18
+ erra := wrapped{"wrap 2", err1}
19
+ errb := wrapped{"wrap 3", erra}
20
+
21
+ err3 := errors.New("3")
22
+
23
+ poser := &poser{"either 1 or 3", func(err error) bool {
24
+ return err == err1 || err == err3
25
+ }}
26
+
27
+ testCases := []struct {
28
+ err error
29
+ target error
30
+ match bool
31
+ }{
32
+ {nil, nil, true},
33
+ {nil, err1, false},
34
+ {err1, nil, false},
35
+ {err1, err1, true},
36
+ {erra, err1, true},
37
+ {errb, err1, true},
38
+ {err1, err3, false},
39
+ {erra, err3, false},
40
+ {errb, err3, false},
41
+ {poser, err1, true},
42
+ {poser, err3, true},
43
+ {poser, erra, false},
44
+ {poser, errb, false},
45
+ {errorUncomparable{}, errorUncomparable{}, true},
46
+ {errorUncomparable{}, &errorUncomparable{}, false},
47
+ {&errorUncomparable{}, errorUncomparable{}, true},
48
+ {&errorUncomparable{}, &errorUncomparable{}, false},
49
+ {errorUncomparable{}, err1, false},
50
+ {&errorUncomparable{}, err1, false},
51
+ {multiErr{}, err1, false},
52
+ {multiErr{err1, err3}, err1, true},
53
+ {multiErr{err3, err1}, err1, true},
54
+ {multiErr{err1, err3}, errors.New("x"), false},
55
+ {multiErr{err3, errb}, errb, true},
56
+ {multiErr{err3, errb}, erra, true},
57
+ {multiErr{err3, errb}, err1, true},
58
+ {multiErr{errb, err3}, err1, true},
59
+ {multiErr{poser}, err1, true},
60
+ {multiErr{poser}, err3, true},
61
+ {multiErr{nil}, nil, false},
62
+ }
63
+ for _, tc := range testCases {
64
+ t.Run("", func(t *testing.T) {
65
+ if got := errors.Is(tc.err, tc.target); got != tc.match {
66
+ t.Errorf("Is(%v, %v) = %v, want %v", tc.err, tc.target, got, tc.match)
67
+ }
68
+ })
69
+ }
70
+ }
71
+
72
+ type poser struct {
73
+ msg string
74
+ f func(error) bool
75
+ }
76
+
77
+ var poserPathErr = &fs.PathError{Op: "poser"}
78
+
79
+ func (p *poser) Error() string { return p.msg }
80
+ func (p *poser) Is(err error) bool { return p.f(err) }
81
+ func (p *poser) As(err any) bool {
82
+ switch x := err.(type) {
83
+ case **poser:
84
+ *x = p
85
+ case *errorT:
86
+ *x = errorT{"poser"}
87
+ case **fs.PathError:
88
+ *x = poserPathErr
89
+ default:
90
+ return false
91
+ }
92
+ return true
93
+ }
94
+
95
+ func TestAs(t *testing.T) {
96
+ var errT errorT
97
+ var errP *fs.PathError
98
+ var timeout interface{ Timeout() bool }
99
+ var p *poser
100
+ _, errF := os.Open("non-existing")
101
+ poserErr := &poser{"oh no", nil}
102
+
103
+ testCases := []struct {
104
+ err error
105
+ target any
106
+ match bool
107
+ want any // value of target on match
108
+ }{{
109
+ nil,
110
+ &errP,
111
+ false,
112
+ nil,
113
+ }, {
114
+ wrapped{"pitied the fool", errorT{"T"}},
115
+ &errT,
116
+ true,
117
+ errorT{"T"},
118
+ }, {
119
+ errF,
120
+ &errP,
121
+ true,
122
+ errF,
123
+ }, {
124
+ errorT{},
125
+ &errP,
126
+ false,
127
+ nil,
128
+ }, {
129
+ wrapped{"wrapped", nil},
130
+ &errT,
131
+ false,
132
+ nil,
133
+ }, {
134
+ &poser{"error", nil},
135
+ &errT,
136
+ true,
137
+ errorT{"poser"},
138
+ }, {
139
+ &poser{"path", nil},
140
+ &errP,
141
+ true,
142
+ poserPathErr,
143
+ }, {
144
+ poserErr,
145
+ &p,
146
+ true,
147
+ poserErr,
148
+ }, {
149
+ errors.New("err"),
150
+ &timeout,
151
+ false,
152
+ nil,
153
+ }, {
154
+ errF,
155
+ &timeout,
156
+ true,
157
+ errF,
158
+ }, {
159
+ wrapped{"path error", errF},
160
+ &timeout,
161
+ true,
162
+ errF,
163
+ }, {
164
+ multiErr{},
165
+ &errT,
166
+ false,
167
+ nil,
168
+ }, {
169
+ multiErr{errors.New("a"), errorT{"T"}},
170
+ &errT,
171
+ true,
172
+ errorT{"T"},
173
+ }, {
174
+ multiErr{errorT{"T"}, errors.New("a")},
175
+ &errT,
176
+ true,
177
+ errorT{"T"},
178
+ }, {
179
+ multiErr{errorT{"a"}, errorT{"b"}},
180
+ &errT,
181
+ true,
182
+ errorT{"a"},
183
+ }, {
184
+ multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}},
185
+ &errT,
186
+ true,
187
+ errorT{"a"},
188
+ }, {
189
+ multiErr{wrapped{"path error", errF}},
190
+ &timeout,
191
+ true,
192
+ errF,
193
+ }, {
194
+ multiErr{nil},
195
+ &errT,
196
+ false,
197
+ nil,
198
+ }}
199
+ for i, tc := range testCases {
200
+ name := fmt.Sprintf("%d:As(Errorf(..., %v), %v)", i, tc.err, tc.target)
201
+ // Clear the target pointer, in case it was set in a previous test.
202
+ rtarget := reflect.ValueOf(tc.target)
203
+ rtarget.Elem().Set(reflect.Zero(reflect.TypeOf(tc.target).Elem()))
204
+ t.Run(name, func(t *testing.T) {
205
+ match := errors.As(tc.err, tc.target)
206
+ if match != tc.match {
207
+ t.Fatalf("match: got %v; want %v", match, tc.match)
208
+ }
209
+ if !match {
210
+ return
211
+ }
212
+ if got := rtarget.Elem().Interface(); got != tc.want {
213
+ t.Fatalf("got %#v, want %#v", got, tc.want)
214
+ }
215
+ })
216
+ }
217
+ }
218
+
219
+ func TestAsValidation(t *testing.T) {
220
+ var s string
221
+ testCases := []any{
222
+ nil,
223
+ (*int)(nil),
224
+ "error",
225
+ &s,
226
+ }
227
+ err := errors.New("error")
228
+ for _, tc := range testCases {
229
+ t.Run(fmt.Sprintf("%T(%v)", tc, tc), func(t *testing.T) {
230
+ defer func() {
231
+ recover()
232
+ }()
233
+ if errors.As(err, tc) {
234
+ t.Errorf("As(err, %T(%v)) = true, want false", tc, tc)
235
+ return
236
+ }
237
+ t.Errorf("As(err, %T(%v)) did not panic", tc, tc)
238
+ })
239
+ }
240
+ }
241
+
242
+ func TestAsType(t *testing.T) {
243
+ var errT errorT
244
+ var errP *fs.PathError
245
+ type timeout interface {
246
+ Timeout() bool
247
+ error
248
+ }
249
+ _, errF := os.Open("non-existing")
250
+ poserErr := &poser{"oh no", nil}
251
+
252
+ testAsType(t,
253
+ nil,
254
+ errP,
255
+ false,
256
+ )
257
+ testAsType(t,
258
+ wrapped{"pitied the fool", errorT{"T"}},
259
+ errorT{"T"},
260
+ true,
261
+ )
262
+ testAsType(t,
263
+ errF,
264
+ errF,
265
+ true,
266
+ )
267
+ testAsType(t,
268
+ errT,
269
+ errP,
270
+ false,
271
+ )
272
+ testAsType(t,
273
+ wrapped{"wrapped", nil},
274
+ errT,
275
+ false,
276
+ )
277
+ testAsType(t,
278
+ &poser{"error", nil},
279
+ errorT{"poser"},
280
+ true,
281
+ )
282
+ testAsType(t,
283
+ &poser{"path", nil},
284
+ poserPathErr,
285
+ true,
286
+ )
287
+ testAsType(t,
288
+ poserErr,
289
+ poserErr,
290
+ true,
291
+ )
292
+ testAsType(t,
293
+ errors.New("err"),
294
+ timeout(nil),
295
+ false,
296
+ )
297
+ testAsType(t,
298
+ errF,
299
+ errF.(timeout),
300
+ true)
301
+ testAsType(t,
302
+ wrapped{"path error", errF},
303
+ errF.(timeout),
304
+ true,
305
+ )
306
+ testAsType(t,
307
+ multiErr{},
308
+ errT,
309
+ false,
310
+ )
311
+ testAsType(t,
312
+ multiErr{errors.New("a"), errorT{"T"}},
313
+ errorT{"T"},
314
+ true,
315
+ )
316
+ testAsType(t,
317
+ multiErr{errorT{"T"}, errors.New("a")},
318
+ errorT{"T"},
319
+ true,
320
+ )
321
+ testAsType(t,
322
+ multiErr{errorT{"a"}, errorT{"b"}},
323
+ errorT{"a"},
324
+ true,
325
+ )
326
+ testAsType(t,
327
+ multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}},
328
+ errorT{"a"},
329
+ true,
330
+ )
331
+ testAsType(t,
332
+ multiErr{wrapped{"path error", errF}},
333
+ errF.(timeout),
334
+ true,
335
+ )
336
+ testAsType(t,
337
+ multiErr{nil},
338
+ errT,
339
+ false,
340
+ )
341
+ }
342
+
343
+ type compError interface {
344
+ comparable
345
+ error
346
+ }
347
+
348
+ func testAsType[E compError](t *testing.T, err error, want E, wantOK bool) {
349
+ t.Helper()
350
+ name := fmt.Sprintf("AsType[%T](Errorf(..., %v))", want, err)
351
+ t.Run(name, func(t *testing.T) {
352
+ got, gotOK := errors.AsType[E](err)
353
+ if gotOK != wantOK || got != want {
354
+ t.Fatalf("got %v, %t; want %v, %t", got, gotOK, want, wantOK)
355
+ }
356
+ })
357
+ }
358
+
359
+ func BenchmarkIs(b *testing.B) {
360
+ err1 := errors.New("1")
361
+ err2 := multiErr{multiErr{multiErr{err1, errorT{"a"}}, errorT{"b"}}}
362
+
363
+ for i := 0; i < b.N; i++ {
364
+ if !errors.Is(err2, err1) {
365
+ b.Fatal("Is failed")
366
+ }
367
+ }
368
+ }
369
+
370
+ func BenchmarkAs(b *testing.B) {
371
+ err := multiErr{multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}}
372
+ for i := 0; i < b.N; i++ {
373
+ var target errorT
374
+ if !errors.As(err, &target) {
375
+ b.Fatal("As failed")
376
+ }
377
+ }
378
+ }
379
+
380
+ func BenchmarkAsType(b *testing.B) {
381
+ err := multiErr{multiErr{multiErr{errors.New("a"), errorT{"a"}}, errorT{"b"}}}
382
+ for range b.N {
383
+ if _, ok := errors.AsType[errorT](err); !ok {
384
+ b.Fatal("AsType failed")
385
+ }
386
+ }
387
+ }
388
+
389
+ func TestUnwrap(t *testing.T) {
390
+ err1 := errors.New("1")
391
+ erra := wrapped{"wrap 2", err1}
392
+
393
+ testCases := []struct {
394
+ err error
395
+ want error
396
+ }{
397
+ {nil, nil},
398
+ {wrapped{"wrapped", nil}, nil},
399
+ {err1, nil},
400
+ {erra, err1},
401
+ {wrapped{"wrap 3", erra}, erra},
402
+ }
403
+ for _, tc := range testCases {
404
+ if got := errors.Unwrap(tc.err); got != tc.want {
405
+ t.Errorf("Unwrap(%v) = %v, want %v", tc.err, got, tc.want)
406
+ }
407
+ }
408
+ }
409
+
410
+ type errorT struct{ s string }
411
+
412
+ func (e errorT) Error() string { return fmt.Sprintf("errorT(%s)", e.s) }
413
+
414
+ type wrapped struct {
415
+ msg string
416
+ err error
417
+ }
418
+
419
+ func (e wrapped) Error() string { return e.msg }
420
+ func (e wrapped) Unwrap() error { return e.err }
421
+
422
+ type multiErr []error
423
+
424
+ func (m multiErr) Error() string { return "multiError" }
425
+ func (m multiErr) Unwrap() []error { return []error(m) }
426
+
427
+ type errorUncomparable struct {
428
+ f []string
429
+ }
430
+
431
+ func (errorUncomparable) Error() string {
432
+ return "uncomparable error"
433
+ }
434
+
435
+ func (errorUncomparable) Is(target error) bool {
436
+ _, ok := target.(errorUncomparable)
437
+ return ok
438
+ }
go/src/expvar/expvar.go ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package expvar provides a standardized interface to public variables, such
6
+ // as operation counters in servers. It exposes these variables via HTTP at
7
+ // /debug/vars in JSON format. As of Go 1.22, the /debug/vars request must
8
+ // use GET.
9
+ //
10
+ // Operations to set or modify these public variables are atomic.
11
+ //
12
+ // In addition to adding the HTTP handler, this package registers the
13
+ // following variables:
14
+ //
15
+ // cmdline os.Args
16
+ // memstats runtime.Memstats
17
+ //
18
+ // The package is sometimes only imported for the side effect of
19
+ // registering its HTTP handler and the above variables. To use it
20
+ // this way, link this package into your program:
21
+ //
22
+ // import _ "expvar"
23
+ package expvar
24
+
25
+ import (
26
+ "encoding/json"
27
+ "internal/godebug"
28
+ "log"
29
+ "math"
30
+ "net/http"
31
+ "os"
32
+ "runtime"
33
+ "slices"
34
+ "strconv"
35
+ "sync"
36
+ "sync/atomic"
37
+ "unicode/utf8"
38
+ )
39
+
40
+ // Var is an abstract type for all exported variables.
41
+ type Var interface {
42
+ // String returns a valid JSON value for the variable.
43
+ // Types with String methods that do not return valid JSON
44
+ // (such as time.Time) must not be used as a Var.
45
+ String() string
46
+ }
47
+
48
+ type jsonVar interface {
49
+ // appendJSON appends the JSON representation of the receiver to b.
50
+ appendJSON(b []byte) []byte
51
+ }
52
+
53
+ // Int is a 64-bit integer variable that satisfies the [Var] interface.
54
+ type Int struct {
55
+ i atomic.Int64
56
+ }
57
+
58
+ func (v *Int) Value() int64 {
59
+ return v.i.Load()
60
+ }
61
+
62
+ func (v *Int) String() string {
63
+ return string(v.appendJSON(nil))
64
+ }
65
+
66
+ func (v *Int) appendJSON(b []byte) []byte {
67
+ return strconv.AppendInt(b, v.i.Load(), 10)
68
+ }
69
+
70
+ func (v *Int) Add(delta int64) {
71
+ v.i.Add(delta)
72
+ }
73
+
74
+ func (v *Int) Set(value int64) {
75
+ v.i.Store(value)
76
+ }
77
+
78
+ // Float is a 64-bit float variable that satisfies the [Var] interface.
79
+ type Float struct {
80
+ f atomic.Uint64
81
+ }
82
+
83
+ func (v *Float) Value() float64 {
84
+ return math.Float64frombits(v.f.Load())
85
+ }
86
+
87
+ func (v *Float) String() string {
88
+ return string(v.appendJSON(nil))
89
+ }
90
+
91
+ func (v *Float) appendJSON(b []byte) []byte {
92
+ return strconv.AppendFloat(b, math.Float64frombits(v.f.Load()), 'g', -1, 64)
93
+ }
94
+
95
+ // Add adds delta to v.
96
+ func (v *Float) Add(delta float64) {
97
+ for {
98
+ cur := v.f.Load()
99
+ curVal := math.Float64frombits(cur)
100
+ nxtVal := curVal + delta
101
+ nxt := math.Float64bits(nxtVal)
102
+ if v.f.CompareAndSwap(cur, nxt) {
103
+ return
104
+ }
105
+ }
106
+ }
107
+
108
+ // Set sets v to value.
109
+ func (v *Float) Set(value float64) {
110
+ v.f.Store(math.Float64bits(value))
111
+ }
112
+
113
+ // Map is a string-to-Var map variable that satisfies the [Var] interface.
114
+ type Map struct {
115
+ m sync.Map // map[string]Var
116
+ keysMu sync.RWMutex
117
+ keys []string // sorted
118
+ }
119
+
120
+ // KeyValue represents a single entry in a [Map].
121
+ type KeyValue struct {
122
+ Key string
123
+ Value Var
124
+ }
125
+
126
+ func (v *Map) String() string {
127
+ return string(v.appendJSON(nil))
128
+ }
129
+
130
+ func (v *Map) appendJSON(b []byte) []byte {
131
+ return v.appendJSONMayExpand(b, false)
132
+ }
133
+
134
+ func (v *Map) appendJSONMayExpand(b []byte, expand bool) []byte {
135
+ afterCommaDelim := byte(' ')
136
+ mayAppendNewline := func(b []byte) []byte { return b }
137
+ if expand {
138
+ afterCommaDelim = '\n'
139
+ mayAppendNewline = func(b []byte) []byte { return append(b, '\n') }
140
+ }
141
+
142
+ b = append(b, '{')
143
+ b = mayAppendNewline(b)
144
+ first := true
145
+ v.Do(func(kv KeyValue) {
146
+ if !first {
147
+ b = append(b, ',', afterCommaDelim)
148
+ }
149
+ first = false
150
+ b = appendJSONQuote(b, kv.Key)
151
+ b = append(b, ':', ' ')
152
+ switch v := kv.Value.(type) {
153
+ case nil:
154
+ b = append(b, "null"...)
155
+ case jsonVar:
156
+ b = v.appendJSON(b)
157
+ default:
158
+ b = append(b, v.String()...)
159
+ }
160
+ })
161
+ b = mayAppendNewline(b)
162
+ b = append(b, '}')
163
+ b = mayAppendNewline(b)
164
+ return b
165
+ }
166
+
167
+ // Init removes all keys from the map.
168
+ func (v *Map) Init() *Map {
169
+ v.keysMu.Lock()
170
+ defer v.keysMu.Unlock()
171
+ v.keys = v.keys[:0]
172
+ v.m.Clear()
173
+ return v
174
+ }
175
+
176
+ // addKey updates the sorted list of keys in v.keys.
177
+ func (v *Map) addKey(key string) {
178
+ v.keysMu.Lock()
179
+ defer v.keysMu.Unlock()
180
+ // Using insertion sort to place key into the already-sorted v.keys.
181
+ i, found := slices.BinarySearch(v.keys, key)
182
+ if found {
183
+ return
184
+ }
185
+ v.keys = slices.Insert(v.keys, i, key)
186
+ }
187
+
188
+ func (v *Map) Get(key string) Var {
189
+ i, _ := v.m.Load(key)
190
+ av, _ := i.(Var)
191
+ return av
192
+ }
193
+
194
+ func (v *Map) Set(key string, av Var) {
195
+ // Before we store the value, check to see whether the key is new. Try a Load
196
+ // before LoadOrStore: LoadOrStore causes the key interface to escape even on
197
+ // the Load path.
198
+ if _, ok := v.m.Load(key); !ok {
199
+ if _, dup := v.m.LoadOrStore(key, av); !dup {
200
+ v.addKey(key)
201
+ return
202
+ }
203
+ }
204
+
205
+ v.m.Store(key, av)
206
+ }
207
+
208
+ // Add adds delta to the *[Int] value stored under the given map key.
209
+ func (v *Map) Add(key string, delta int64) {
210
+ i, ok := v.m.Load(key)
211
+ if !ok {
212
+ var dup bool
213
+ i, dup = v.m.LoadOrStore(key, new(Int))
214
+ if !dup {
215
+ v.addKey(key)
216
+ }
217
+ }
218
+
219
+ // Add to Int; ignore otherwise.
220
+ if iv, ok := i.(*Int); ok {
221
+ iv.Add(delta)
222
+ }
223
+ }
224
+
225
+ // AddFloat adds delta to the *[Float] value stored under the given map key.
226
+ func (v *Map) AddFloat(key string, delta float64) {
227
+ i, ok := v.m.Load(key)
228
+ if !ok {
229
+ var dup bool
230
+ i, dup = v.m.LoadOrStore(key, new(Float))
231
+ if !dup {
232
+ v.addKey(key)
233
+ }
234
+ }
235
+
236
+ // Add to Float; ignore otherwise.
237
+ if iv, ok := i.(*Float); ok {
238
+ iv.Add(delta)
239
+ }
240
+ }
241
+
242
+ // Delete deletes the given key from the map.
243
+ func (v *Map) Delete(key string) {
244
+ v.keysMu.Lock()
245
+ defer v.keysMu.Unlock()
246
+ i, found := slices.BinarySearch(v.keys, key)
247
+ if found {
248
+ v.keys = slices.Delete(v.keys, i, i+1)
249
+ v.m.Delete(key)
250
+ }
251
+ }
252
+
253
+ // Do calls f for each entry in the map.
254
+ // The map is locked during the iteration,
255
+ // but existing entries may be concurrently updated.
256
+ func (v *Map) Do(f func(KeyValue)) {
257
+ v.keysMu.RLock()
258
+ defer v.keysMu.RUnlock()
259
+ for _, k := range v.keys {
260
+ i, _ := v.m.Load(k)
261
+ val, _ := i.(Var)
262
+ f(KeyValue{k, val})
263
+ }
264
+ }
265
+
266
+ // String is a string variable, and satisfies the [Var] interface.
267
+ type String struct {
268
+ s atomic.Value // string
269
+ }
270
+
271
+ func (v *String) Value() string {
272
+ p, _ := v.s.Load().(string)
273
+ return p
274
+ }
275
+
276
+ // String implements the [Var] interface. To get the unquoted string
277
+ // use [String.Value].
278
+ func (v *String) String() string {
279
+ return string(v.appendJSON(nil))
280
+ }
281
+
282
+ func (v *String) appendJSON(b []byte) []byte {
283
+ return appendJSONQuote(b, v.Value())
284
+ }
285
+
286
+ func (v *String) Set(value string) {
287
+ v.s.Store(value)
288
+ }
289
+
290
+ // Func implements [Var] by calling the function
291
+ // and formatting the returned value using JSON.
292
+ type Func func() any
293
+
294
+ func (f Func) Value() any {
295
+ return f()
296
+ }
297
+
298
+ func (f Func) String() string {
299
+ v, _ := json.Marshal(f())
300
+ return string(v)
301
+ }
302
+
303
+ // All published variables.
304
+ var vars Map
305
+
306
+ // Publish declares a named exported variable. This should be called from a
307
+ // package's init function when it creates its Vars. If the name is already
308
+ // registered then this will log.Panic.
309
+ func Publish(name string, v Var) {
310
+ if _, dup := vars.m.LoadOrStore(name, v); dup {
311
+ log.Panicln("Reuse of exported var name:", name)
312
+ }
313
+ vars.keysMu.Lock()
314
+ defer vars.keysMu.Unlock()
315
+ vars.keys = append(vars.keys, name)
316
+ slices.Sort(vars.keys)
317
+ }
318
+
319
+ // Get retrieves a named exported variable. It returns nil if the name has
320
+ // not been registered.
321
+ func Get(name string) Var {
322
+ return vars.Get(name)
323
+ }
324
+
325
+ // Convenience functions for creating new exported variables.
326
+
327
+ func NewInt(name string) *Int {
328
+ v := new(Int)
329
+ Publish(name, v)
330
+ return v
331
+ }
332
+
333
+ func NewFloat(name string) *Float {
334
+ v := new(Float)
335
+ Publish(name, v)
336
+ return v
337
+ }
338
+
339
+ func NewMap(name string) *Map {
340
+ v := new(Map).Init()
341
+ Publish(name, v)
342
+ return v
343
+ }
344
+
345
+ func NewString(name string) *String {
346
+ v := new(String)
347
+ Publish(name, v)
348
+ return v
349
+ }
350
+
351
+ // Do calls f for each exported variable.
352
+ // The global variable map is locked during the iteration,
353
+ // but existing entries may be concurrently updated.
354
+ func Do(f func(KeyValue)) {
355
+ vars.Do(f)
356
+ }
357
+
358
+ func expvarHandler(w http.ResponseWriter, r *http.Request) {
359
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
360
+ w.Write(vars.appendJSONMayExpand(nil, true))
361
+ }
362
+
363
+ // Handler returns the expvar HTTP Handler.
364
+ //
365
+ // This is only needed to install the handler in a non-standard location.
366
+ func Handler() http.Handler {
367
+ return http.HandlerFunc(expvarHandler)
368
+ }
369
+
370
+ func cmdline() any {
371
+ return os.Args
372
+ }
373
+
374
+ func memstats() any {
375
+ stats := new(runtime.MemStats)
376
+ runtime.ReadMemStats(stats)
377
+ return *stats
378
+ }
379
+
380
+ func init() {
381
+ if godebug.New("httpmuxgo121").Value() == "1" {
382
+ http.HandleFunc("/debug/vars", expvarHandler)
383
+ } else {
384
+ http.HandleFunc("GET /debug/vars", expvarHandler)
385
+ }
386
+ Publish("cmdline", Func(cmdline))
387
+ Publish("memstats", Func(memstats))
388
+ }
389
+
390
+ // TODO: Use json.appendString instead.
391
+ func appendJSONQuote(b []byte, s string) []byte {
392
+ const hex = "0123456789abcdef"
393
+ b = append(b, '"')
394
+ for _, r := range s {
395
+ switch {
396
+ case r < ' ' || r == '\\' || r == '"' || r == '<' || r == '>' || r == '&' || r == '\u2028' || r == '\u2029':
397
+ switch r {
398
+ case '\\', '"':
399
+ b = append(b, '\\', byte(r))
400
+ case '\n':
401
+ b = append(b, '\\', 'n')
402
+ case '\r':
403
+ b = append(b, '\\', 'r')
404
+ case '\t':
405
+ b = append(b, '\\', 't')
406
+ default:
407
+ b = append(b, '\\', 'u', hex[(r>>12)&0xf], hex[(r>>8)&0xf], hex[(r>>4)&0xf], hex[(r>>0)&0xf])
408
+ }
409
+ case r < utf8.RuneSelf:
410
+ b = append(b, byte(r))
411
+ default:
412
+ b = utf8.AppendRune(b, r)
413
+ }
414
+ }
415
+ b = append(b, '"')
416
+ return b
417
+ }