github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/bytes/buffer.gno (about) 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 Read and 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 26 // The readOp constants describe the last action performed on 27 // the buffer, so that UnreadRune and UnreadByte can check for 28 // invalid usage. opReadRuneX constants are chosen such that 29 // converted to int they correspond to the rune size that was read. 30 type readOp int8 31 32 // Don't use iota for these, as the values need to correspond with the 33 // names and comments, which is easier to see when being explicit. 34 const ( 35 opRead readOp = -1 // Any other read operation. 36 opInvalid readOp = 0 // Non-read operation. 37 opReadRune1 readOp = 1 // Read rune of size 1. 38 opReadRune2 readOp = 2 // Read rune of size 2. 39 opReadRune3 readOp = 3 // Read rune of size 3. 40 opReadRune4 readOp = 4 // Read rune of size 4. 41 ) 42 43 // ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer. 44 var ( 45 ErrTooLarge = errors.New("bytes.Buffer: too large") 46 errNegativeRead = errors.New("bytes.Buffer: reader returned negative count from Read") 47 ) 48 49 const maxInt = int(^uint(0) >> 1) 50 51 // Bytes returns a slice of length b.Len() holding the unread portion of the buffer. 52 // The slice is valid for use only until the next buffer modification (that is, 53 // only until the next call to a method like Read, Write, Reset, or Truncate). 54 // The slice aliases the buffer content at least until the next buffer modification, 55 // so immediate changes to the slice will affect the result of future reads. 56 func (b *Buffer) Bytes() []byte { return b.buf[b.off:] } 57 58 // String returns the contents of the unread portion of the buffer 59 // as a string. If the Buffer is a nil pointer, it returns "<nil>". 60 // 61 // To build strings more efficiently, see the strings.Builder type. 62 func (b *Buffer) String() string { 63 if b == nil { 64 // Special case, useful in debugging. 65 return "<nil>" 66 } 67 return string(b.buf[b.off:]) 68 } 69 70 // empty reports whether the unread portion of the buffer is empty. 71 func (b *Buffer) empty() bool { return len(b.buf) <= b.off } 72 73 // Len returns the number of bytes of the unread portion of the buffer; 74 // b.Len() == len(b.Bytes()). 75 func (b *Buffer) Len() int { return len(b.buf) - b.off } 76 77 // Cap returns the capacity of the buffer's underlying byte slice, that is, the 78 // total space allocated for the buffer's data. 79 func (b *Buffer) Cap() int { return cap(b.buf) } 80 81 // Truncate discards all but the first n unread bytes from the buffer 82 // but continues to use the same allocated storage. 83 // It panics if n is negative or greater than the length of the buffer. 84 func (b *Buffer) Truncate(n int) { 85 if n == 0 { 86 b.Reset() 87 return 88 } 89 b.lastRead = opInvalid 90 if n < 0 || n > b.Len() { 91 panic("bytes.Buffer: truncation out of range") 92 } 93 b.buf = b.buf[:b.off+n] 94 } 95 96 // Reset resets the buffer to be empty, 97 // but it retains the underlying storage for use by future writes. 98 // Reset is the same as Truncate(0). 99 func (b *Buffer) Reset() { 100 b.buf = b.buf[:0] 101 b.off = 0 102 b.lastRead = opInvalid 103 } 104 105 // tryGrowByReslice is a inlineable version of grow for the fast-case where the 106 // internal buffer only needs to be resliced. 107 // It returns the index where bytes should be written and whether it succeeded. 108 func (b *Buffer) tryGrowByReslice(n int) (int, bool) { 109 if l := len(b.buf); n <= cap(b.buf)-l { 110 b.buf = b.buf[:l+n] 111 return l, true 112 } 113 return 0, false 114 } 115 116 // grow grows the buffer to guarantee space for n more bytes. 117 // It returns the index where bytes should be written. 118 // If the buffer can't grow it will panic with ErrTooLarge. 119 func (b *Buffer) grow(n int) int { 120 m := b.Len() 121 // If buffer is empty, reset to recover space. 122 if m == 0 && b.off != 0 { 123 b.Reset() 124 } 125 // Try to grow by means of a reslice. 126 if i, ok := b.tryGrowByReslice(n); ok { 127 return i 128 } 129 if b.buf == nil && n <= smallBufferSize { 130 b.buf = make([]byte, n, smallBufferSize) 131 return 0 132 } 133 c := cap(b.buf) 134 if n <= c/2-m { 135 // We can slide things down instead of allocating a new 136 // slice. We only need m+n <= c to slide, but 137 // we instead let capacity get twice as large so we 138 // don't spend all our time copying. 139 copy(b.buf, b.buf[b.off:]) 140 } else if c > maxInt-c-n { 141 panic(ErrTooLarge) 142 } else { 143 // Not enough space anywhere, we need to allocate. 144 buf := makeSlice(2*c + n) 145 copy(buf, b.buf[b.off:]) 146 b.buf = buf 147 } 148 // Restore b.off and len(b.buf). 149 b.off = 0 150 b.buf = b.buf[:m+n] 151 return m 152 } 153 154 // Grow grows the buffer's capacity, if necessary, to guarantee space for 155 // another n bytes. After Grow(n), at least n bytes can be written to the 156 // buffer without another allocation. 157 // If n is negative, Grow will panic. 158 // If the buffer can't grow it will panic with ErrTooLarge. 159 func (b *Buffer) Grow(n int) { 160 if n < 0 { 161 panic("bytes.Buffer.Grow: negative count") 162 } 163 m := b.grow(n) 164 b.buf = b.buf[:m] 165 } 166 167 // Write appends the contents of p to the buffer, growing the buffer as 168 // needed. The return value n is the length of p; err is always nil. If the 169 // buffer becomes too large, Write will panic with ErrTooLarge. 170 func (b *Buffer) Write(p []byte) (n int, err error) { 171 b.lastRead = opInvalid 172 m, ok := b.tryGrowByReslice(len(p)) 173 if !ok { 174 m = b.grow(len(p)) 175 } 176 return copy(b.buf[m:], p), nil 177 } 178 179 // WriteString appends the contents of s to the buffer, growing the buffer as 180 // needed. The return value n is the length of s; err is always nil. If the 181 // buffer becomes too large, WriteString will panic with ErrTooLarge. 182 func (b *Buffer) WriteString(s string) (n int, err error) { 183 b.lastRead = opInvalid 184 m, ok := b.tryGrowByReslice(len(s)) 185 if !ok { 186 m = b.grow(len(s)) 187 } 188 return copy(b.buf[m:], s), nil 189 } 190 191 // MinRead is the minimum slice size passed to a Read call by 192 // Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond 193 // what is required to hold the contents of r, ReadFrom will not grow the 194 // underlying buffer. 195 const MinRead = 512 196 197 // ReadFrom reads data from r until EOF and appends it to the buffer, growing 198 // the buffer as needed. The return value n is the number of bytes read. Any 199 // error except io.EOF encountered during the read is also returned. If the 200 // buffer becomes too large, ReadFrom will panic with ErrTooLarge. 201 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) { 202 b.lastRead = opInvalid 203 for { 204 i := b.grow(MinRead) 205 b.buf = b.buf[:i] 206 m, e := r.Read(b.buf[i:cap(b.buf)]) 207 if m < 0 { 208 panic(errNegativeRead) 209 } 210 211 b.buf = b.buf[:i+m] 212 n += int64(m) 213 if e == io.EOF { 214 return n, nil // e is EOF, so return nil explicitly 215 } 216 if e != nil { 217 return n, e 218 } 219 } 220 } 221 222 // makeSlice allocates a slice of size n. If the allocation fails, it panics 223 // with ErrTooLarge. 224 func makeSlice(n int) []byte { 225 // If the make fails, give a known error. 226 defer func() { 227 if recover() != nil { 228 panic(ErrTooLarge) 229 } 230 }() 231 return make([]byte, n) 232 } 233 234 // WriteTo writes data to w until the buffer is drained or an error occurs. 235 // The return value n is the number of bytes written; it always fits into an 236 // int, but it is int64 to match the io.WriterTo interface. Any error 237 // encountered during the write is also returned. 238 func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) { 239 b.lastRead = opInvalid 240 if nBytes := b.Len(); nBytes > 0 { 241 m, e := w.Write(b.buf[b.off:]) 242 if m > nBytes { 243 panic("bytes.Buffer.WriteTo: invalid Write count") 244 } 245 b.off += m 246 n = int64(m) 247 if e != nil { 248 return n, e 249 } 250 // all bytes should have been written, by definition of 251 // Write method in io.Writer 252 if m != nBytes { 253 return n, io.ErrShortWrite 254 } 255 } 256 // Buffer is now empty; reset. 257 b.Reset() 258 return n, nil 259 } 260 261 // WriteByte appends the byte c to the buffer, growing the buffer as needed. 262 // The returned error is always nil, but is included to match bufio.Writer's 263 // WriteByte. If the buffer becomes too large, WriteByte will panic with 264 // ErrTooLarge. 265 func (b *Buffer) WriteByte(c byte) error { 266 b.lastRead = opInvalid 267 m, ok := b.tryGrowByReslice(1) 268 if !ok { 269 m = b.grow(1) 270 } 271 b.buf[m] = c 272 return nil 273 } 274 275 // WriteRune appends the UTF-8 encoding of Unicode code point r to the 276 // buffer, returning its length and an error, which is always nil but is 277 // included to match bufio.Writer's WriteRune. The buffer is grown as needed; 278 // if it becomes too large, WriteRune will panic with ErrTooLarge. 279 func (b *Buffer) WriteRune(r rune) (n int, err error) { 280 // Compare as uint32 to correctly handle negative runes. 281 if uint32(r) < utf8.RuneSelf { 282 b.WriteByte(byte(r)) 283 return 1, nil 284 } 285 b.lastRead = opInvalid 286 m, ok := b.tryGrowByReslice(utf8.UTFMax) 287 if !ok { 288 m = b.grow(utf8.UTFMax) 289 } 290 n = utf8.EncodeRune(b.buf[m:m+utf8.UTFMax], r) 291 b.buf = b.buf[:m+n] 292 return n, nil 293 } 294 295 // Read reads the next len(p) bytes from the buffer or until the buffer 296 // is drained. The return value n is the number of bytes read. If the 297 // buffer has no data to return, err is io.EOF (unless len(p) is zero); 298 // otherwise it is nil. 299 func (b *Buffer) Read(p []byte) (n int, err error) { 300 b.lastRead = opInvalid 301 if b.empty() { 302 // Buffer is empty, reset to recover space. 303 b.Reset() 304 if len(p) == 0 { 305 return 0, nil 306 } 307 return 0, io.EOF 308 } 309 n = copy(p, b.buf[b.off:]) 310 b.off += n 311 if n > 0 { 312 b.lastRead = opRead 313 } 314 return n, nil 315 } 316 317 // Next returns a slice containing the next n bytes from the buffer, 318 // advancing the buffer as if the bytes had been returned by Read. 319 // If there are fewer than n bytes in the buffer, Next returns the entire buffer. 320 // The slice is only valid until the next call to a read or write method. 321 func (b *Buffer) Next(n int) []byte { 322 b.lastRead = opInvalid 323 m := b.Len() 324 if n > m { 325 n = m 326 } 327 data := b.buf[b.off : b.off+n] 328 b.off += n 329 if n > 0 { 330 b.lastRead = opRead 331 } 332 return data 333 } 334 335 // ReadByte reads and returns the next byte from the buffer. 336 // If no byte is available, it returns error io.EOF. 337 func (b *Buffer) ReadByte() (byte, error) { 338 if b.empty() { 339 // Buffer is empty, reset to recover space. 340 b.Reset() 341 return 0, io.EOF 342 } 343 c := b.buf[b.off] 344 b.off++ 345 b.lastRead = opRead 346 return c, nil 347 } 348 349 // ReadRune reads and returns the next UTF-8-encoded 350 // Unicode code point from the buffer. 351 // If no bytes are available, the error returned is io.EOF. 352 // If the bytes are an erroneous UTF-8 encoding, it 353 // consumes one byte and returns U+FFFD, 1. 354 func (b *Buffer) ReadRune() (r rune, size int, err error) { 355 if b.empty() { 356 // Buffer is empty, reset to recover space. 357 b.Reset() 358 return 0, 0, io.EOF 359 } 360 c := b.buf[b.off] 361 if c < utf8.RuneSelf { 362 b.off++ 363 b.lastRead = opReadRune1 364 return rune(c), 1, nil 365 } 366 r, n := utf8.DecodeRune(b.buf[b.off:]) 367 b.off += n 368 b.lastRead = readOp(n) 369 return r, n, nil 370 } 371 372 // UnreadRune unreads the last rune returned by ReadRune. 373 // If the most recent read or write operation on the buffer was 374 // not a successful ReadRune, UnreadRune returns an error. (In this regard 375 // it is stricter than UnreadByte, which will unread the last byte 376 // from any read operation.) 377 func (b *Buffer) UnreadRune() error { 378 if b.lastRead <= opInvalid { 379 return errors.New("bytes.Buffer: UnreadRune: previous operation was not a successful ReadRune") 380 } 381 if b.off >= int(b.lastRead) { 382 b.off -= int(b.lastRead) 383 } 384 b.lastRead = opInvalid 385 return nil 386 } 387 388 var errUnreadByte = errors.New("bytes.Buffer: UnreadByte: previous operation was not a successful read") 389 390 // UnreadByte unreads the last byte returned by the most recent successful 391 // read operation that read at least one byte. If a write has happened since 392 // the last read, if the last read returned an error, or if the read read zero 393 // bytes, UnreadByte returns an error. 394 func (b *Buffer) UnreadByte() error { 395 if b.lastRead == opInvalid { 396 return errUnreadByte 397 } 398 b.lastRead = opInvalid 399 if b.off > 0 { 400 b.off-- 401 } 402 return nil 403 } 404 405 // ReadBytes reads until the first occurrence of delim in the input, 406 // returning a slice containing the data up to and including the delimiter. 407 // If ReadBytes encounters an error before finding a delimiter, 408 // it returns the data read before the error and the error itself (often io.EOF). 409 // ReadBytes returns err != nil if and only if the returned data does not end in 410 // delim. 411 func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) { 412 slice, err := b.readSlice(delim) 413 // return a copy of slice. The buffer's backing array may 414 // be overwritten by later calls. 415 line = append(line, slice...) 416 return line, err 417 } 418 419 // readSlice is like ReadBytes but returns a reference to internal buffer data. 420 func (b *Buffer) readSlice(delim byte) (line []byte, err error) { 421 i := IndexByte(b.buf[b.off:], delim) 422 end := b.off + i + 1 423 if i < 0 { 424 end = len(b.buf) 425 err = io.EOF 426 } 427 line = b.buf[b.off:end] 428 b.off = end 429 b.lastRead = opRead 430 return line, err 431 } 432 433 // ReadString reads until the first occurrence of delim in the input, 434 // returning a string containing the data up to and including the delimiter. 435 // If ReadString encounters an error before finding a delimiter, 436 // it returns the data read before the error and the error itself (often io.EOF). 437 // ReadString returns err != nil if and only if the returned data does not end 438 // in delim. 439 func (b *Buffer) ReadString(delim byte) (line string, err error) { 440 slice, err := b.readSlice(delim) 441 return string(slice), err 442 } 443 444 // NewBuffer creates and initializes a new Buffer using buf as its 445 // initial contents. The new Buffer takes ownership of buf, and the 446 // caller should not use buf after this call. NewBuffer is intended to 447 // prepare a Buffer to read existing data. It can also be used to set 448 // the initial size of the internal buffer for writing. To do that, 449 // buf should have the desired capacity but a length of zero. 450 // 451 // In most cases, new(Buffer) (or just declaring a Buffer variable) is 452 // sufficient to initialize a Buffer. 453 func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} } 454 455 // NewBufferString creates and initializes a new Buffer using string s as its 456 // initial contents. It is intended to prepare a buffer to read an existing 457 // string. 458 // 459 // In most cases, new(Buffer) (or just declaring a Buffer variable) is 460 // sufficient to initialize a Buffer. 461 func NewBufferString(s string) *Buffer { 462 return &Buffer{buf: []byte(s)} 463 }