Source file src/io/io.go
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 io provides basic interfaces to I/O primitives. 6 // Its primary job is to wrap existing implementations of such primitives, 7 // such as those in package os, into shared public interfaces that 8 // abstract the functionality, plus some other related primitives. 9 // 10 // Because these interfaces and primitives wrap lower-level operations with 11 // various implementations, unless otherwise informed clients should not 12 // assume they are safe for parallel execution. 13 package io 14 15 import ( 16 "errors" 17 "sync" 18 ) 19 20 // Seek whence values. 21 const ( 22 SeekStart = 0 // seek relative to the origin of the file 23 SeekCurrent = 1 // seek relative to the current offset 24 SeekEnd = 2 // seek relative to the end 25 ) 26 27 // ErrShortWrite means that a write accepted fewer bytes than requested 28 // but failed to return an explicit error. 29 var ErrShortWrite = errors.New("short write") 30 31 // errInvalidWrite means that a write returned an impossible count. 32 var errInvalidWrite = errors.New("invalid write result") 33 34 // ErrShortBuffer means that a read required a longer buffer than was provided. 35 var ErrShortBuffer = errors.New("short buffer") 36 37 // EOF is the error returned by Read when no more input is available. 38 // (Read must return EOF itself, not an error wrapping EOF, 39 // because callers will test for EOF using ==.) 40 // Functions should return EOF only to signal a graceful end of input. 41 // If the EOF occurs unexpectedly in a structured data stream, 42 // the appropriate error is either ErrUnexpectedEOF or some other error 43 // giving more detail. 44 var EOF = errors.New("EOF") 45 46 // ErrUnexpectedEOF means that EOF was encountered in the 47 // middle of reading a fixed-size block or data structure. 48 var ErrUnexpectedEOF = errors.New("unexpected EOF") 49 50 // ErrNoProgress is returned by some clients of a Reader when 51 // many calls to Read have failed to return any data or error, 52 // usually the sign of a broken Reader implementation. 53 var ErrNoProgress = errors.New("multiple Read calls return no data or error") 54 55 // Reader is the interface that wraps the basic Read method. 56 // 57 // Read reads up to len(p) bytes into p. It returns the number of bytes 58 // read (0 <= n <= len(p)) and any error encountered. Even if Read 59 // returns n < len(p), it may use all of p as scratch space during the call. 60 // If some data is available but not len(p) bytes, Read conventionally 61 // returns what is available instead of waiting for more. 62 // 63 // When Read encounters an error or end-of-file condition after 64 // successfully reading n > 0 bytes, it returns the number of 65 // bytes read. It may return the (non-nil) error from the same call 66 // or return the error (and n == 0) from a subsequent call. 67 // An instance of this general case is that a Reader returning 68 // a non-zero number of bytes at the end of the input stream may 69 // return either err == EOF or err == nil. The next Read should 70 // return 0, EOF. 71 // 72 // Callers should always process the n > 0 bytes returned before 73 // considering the error err. Doing so correctly handles I/O errors 74 // that happen after reading some bytes and also both of the 75 // allowed EOF behaviors. 76 // 77 // If len(p) == 0, Read should always return n == 0. It may return a 78 // non-nil error if some error condition is known, such as EOF. 79 // 80 // Implementations of Read are discouraged from returning a 81 // zero byte count with a nil error, except when len(p) == 0. 82 // Callers should treat a return of 0 and nil as indicating that 83 // nothing happened; in particular it does not indicate EOF. 84 // 85 // Implementations must not retain p. 86 type Reader interface { 87 Read(p []byte) (n int, err error) 88 } 89 90 // Writer is the interface that wraps the basic Write method. 91 // 92 // Write writes len(p) bytes from p to the underlying data stream. 93 // It returns the number of bytes written from p (0 <= n <= len(p)) 94 // and any error encountered that caused the write to stop early. 95 // Write must return a non-nil error if it returns n < len(p). 96 // Write must not modify the slice data, even temporarily. 97 // 98 // Implementations must not retain p. 99 type Writer interface { 100 Write(p []byte) (n int, err error) 101 } 102 103 // Closer is the interface that wraps the basic Close method. 104 // 105 // The behavior of Close after the first call is undefined. 106 // Specific implementations may document their own behavior. 107 type Closer interface { 108 Close() error 109 } 110 111 // Seeker is the interface that wraps the basic Seek method. 112 // 113 // Seek sets the offset for the next Read or Write to offset, 114 // interpreted according to whence: 115 // SeekStart means relative to the start of the file, 116 // SeekCurrent means relative to the current offset, and 117 // SeekEnd means relative to the end 118 // (for example, offset = -2 specifies the penultimate byte of the file). 119 // Seek returns the new offset relative to the start of the 120 // file or an error, if any. 121 // 122 // Seeking to an offset before the start of the file is an error. 123 // Seeking to any positive offset may be allowed, but if the new offset exceeds 124 // the size of the underlying object the behavior of subsequent I/O operations 125 // is implementation-dependent. 126 type Seeker interface { 127 Seek(offset int64, whence int) (int64, error) 128 } 129 130 // ReadWriter is the interface that groups the basic Read and Write methods. 131 type ReadWriter interface { 132 Reader 133 Writer 134 } 135 136 // ReadCloser is the interface that groups the basic Read and Close methods. 137 type ReadCloser interface { 138 Reader 139 Closer 140 } 141 142 // WriteCloser is the interface that groups the basic Write and Close methods. 143 type WriteCloser interface { 144 Writer 145 Closer 146 } 147 148 // ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. 149 type ReadWriteCloser interface { 150 Reader 151 Writer 152 Closer 153 } 154 155 // ReadSeeker is the interface that groups the basic Read and Seek methods. 156 type ReadSeeker interface { 157 Reader 158 Seeker 159 } 160 161 // ReadSeekCloser is the interface that groups the basic Read, Seek and Close 162 // methods. 163 type ReadSeekCloser interface { 164 Reader 165 Seeker 166 Closer 167 } 168 169 // WriteSeeker is the interface that groups the basic Write and Seek methods. 170 type WriteSeeker interface { 171 Writer 172 Seeker 173 } 174 175 // ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. 176 type ReadWriteSeeker interface { 177 Reader 178 Writer 179 Seeker 180 } 181 182 // ReaderFrom is the interface that wraps the ReadFrom method. 183 // 184 // ReadFrom reads data from r until EOF or error. 185 // The return value n is the number of bytes read. 186 // Any error except EOF encountered during the read is also returned. 187 // 188 // The Copy function uses ReaderFrom if available. 189 type ReaderFrom interface { 190 ReadFrom(r Reader) (n int64, err error) 191 } 192 193 // WriterTo is the interface that wraps the WriteTo method. 194 // 195 // WriteTo writes data to w until there's no more data to write or 196 // when an error occurs. The return value n is the number of bytes 197 // written. Any error encountered during the write is also returned. 198 // 199 // The Copy function uses WriterTo if available. 200 type WriterTo interface { 201 WriteTo(w Writer) (n int64, err error) 202 } 203 204 // ReaderAt is the interface that wraps the basic ReadAt method. 205 // 206 // ReadAt reads len(p) bytes into p starting at offset off in the 207 // underlying input source. It returns the number of bytes 208 // read (0 <= n <= len(p)) and any error encountered. 209 // 210 // When ReadAt returns n < len(p), it returns a non-nil error 211 // explaining why more bytes were not returned. In this respect, 212 // ReadAt is stricter than Read. 213 // 214 // Even if ReadAt returns n < len(p), it may use all of p as scratch 215 // space during the call. If some data is available but not len(p) bytes, 216 // ReadAt blocks until either all the data is available or an error occurs. 217 // In this respect ReadAt is different from Read. 218 // 219 // If the n = len(p) bytes returned by ReadAt are at the end of the 220 // input source, ReadAt may return either err == EOF or err == nil. 221 // 222 // If ReadAt is reading from an input source with a seek offset, 223 // ReadAt should not affect nor be affected by the underlying 224 // seek offset. 225 // 226 // Clients of ReadAt can execute parallel ReadAt calls on the 227 // same input source. 228 // 229 // Implementations must not retain p. 230 type ReaderAt interface { 231 ReadAt(p []byte, off int64) (n int, err error) 232 } 233 234 // WriterAt is the interface that wraps the basic WriteAt method. 235 // 236 // WriteAt writes len(p) bytes from p to the underlying data stream 237 // at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) 238 // and any error encountered that caused the write to stop early. 239 // WriteAt must return a non-nil error if it returns n < len(p). 240 // 241 // If WriteAt is writing to a destination with a seek offset, 242 // WriteAt should not affect nor be affected by the underlying 243 // seek offset. 244 // 245 // Clients of WriteAt can execute parallel WriteAt calls on the same 246 // destination if the ranges do not overlap. 247 // 248 // Implementations must not retain p. 249 type WriterAt interface { 250 WriteAt(p []byte, off int64) (n int, err error) 251 } 252 253 // ByteReader is the interface that wraps the ReadByte method. 254 // 255 // ReadByte reads and returns the next byte from the input or 256 // any error encountered. If ReadByte returns an error, no input 257 // byte was consumed, and the returned byte value is undefined. 258 // 259 // ReadByte provides an efficient interface for byte-at-time 260 // processing. A Reader that does not implement ByteReader 261 // can be wrapped using bufio.NewReader to add this method. 262 type ByteReader interface { 263 ReadByte() (byte, error) 264 } 265 266 // ByteScanner is the interface that adds the UnreadByte method to the 267 // basic ReadByte method. 268 // 269 // UnreadByte causes the next call to ReadByte to return the last byte read. 270 // If the last operation was not a successful call to ReadByte, UnreadByte may 271 // return an error, unread the last byte read (or the byte prior to the 272 // last-unread byte), or (in implementations that support the Seeker interface) 273 // seek to one byte before the current offset. 274 type ByteScanner interface { 275 ByteReader 276 UnreadByte() error 277 } 278 279 // ByteWriter is the interface that wraps the WriteByte method. 280 type ByteWriter interface { 281 WriteByte(c byte) error 282 } 283 284 // RuneReader is the interface that wraps the ReadRune method. 285 // 286 // ReadRune reads a single encoded Unicode character 287 // and returns the rune and its size in bytes. If no character is 288 // available, err will be set. 289 type RuneReader interface { 290 ReadRune() (r rune, size int, err error) 291 } 292 293 // RuneScanner is the interface that adds the UnreadRune method to the 294 // basic ReadRune method. 295 // 296 // UnreadRune causes the next call to ReadRune to return the last rune read. 297 // If the last operation was not a successful call to ReadRune, UnreadRune may 298 // return an error, unread the last rune read (or the rune prior to the 299 // last-unread rune), or (in implementations that support the Seeker interface) 300 // seek to the start of the rune before the current offset. 301 type RuneScanner interface { 302 RuneReader 303 UnreadRune() error 304 } 305 306 // StringWriter is the interface that wraps the WriteString method. 307 type StringWriter interface { 308 WriteString(s string) (n int, err error) 309 } 310 311 // WriteString writes the contents of the string s to w, which accepts a slice of bytes. 312 // If w implements StringWriter, its WriteString method is invoked directly. 313 // Otherwise, w.Write is called exactly once. 314 func WriteString(w Writer, s string) (n int, err error) { 315 if sw, ok := w.(StringWriter); ok { 316 return sw.WriteString(s) 317 } 318 return w.Write([]byte(s)) 319 } 320 321 // ReadAtLeast reads from r into buf until it has read at least min bytes. 322 // It returns the number of bytes copied and an error if fewer bytes were read. 323 // The error is EOF only if no bytes were read. 324 // If an EOF happens after reading fewer than min bytes, 325 // ReadAtLeast returns ErrUnexpectedEOF. 326 // If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. 327 // On return, n >= min if and only if err == nil. 328 // If r returns an error having read at least min bytes, the error is dropped. 329 func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) { 330 if len(buf) < min { 331 return 0, ErrShortBuffer 332 } 333 for n < min && err == nil { 334 var nn int 335 nn, err = r.Read(buf[n:]) 336 n += nn 337 } 338 if n >= min { 339 err = nil 340 } else if n > 0 && err == EOF { 341 err = ErrUnexpectedEOF 342 } 343 return 344 } 345 346 // ReadFull reads exactly len(buf) bytes from r into buf. 347 // It returns the number of bytes copied and an error if fewer bytes were read. 348 // The error is EOF only if no bytes were read. 349 // If an EOF happens after reading some but not all the bytes, 350 // ReadFull returns ErrUnexpectedEOF. 351 // On return, n == len(buf) if and only if err == nil. 352 // If r returns an error having read at least len(buf) bytes, the error is dropped. 353 func ReadFull(r Reader, buf []byte) (n int, err error) { 354 return ReadAtLeast(r, buf, len(buf)) 355 } 356 357 // CopyN copies n bytes (or until an error) from src to dst. 358 // It returns the number of bytes copied and the earliest 359 // error encountered while copying. 360 // On return, written == n if and only if err == nil. 361 // 362 // If dst implements the ReaderFrom interface, 363 // the copy is implemented using it. 364 func CopyN(dst Writer, src Reader, n int64) (written int64, err error) { 365 written, err = Copy(dst, LimitReader(src, n)) 366 if written == n { 367 return n, nil 368 } 369 if written < n && err == nil { 370 // src stopped early; must have been EOF. 371 err = EOF 372 } 373 return 374 } 375 376 // Copy copies from src to dst until either EOF is reached 377 // on src or an error occurs. It returns the number of bytes 378 // copied and the first error encountered while copying, if any. 379 // 380 // A successful Copy returns err == nil, not err == EOF. 381 // Because Copy is defined to read from src until EOF, it does 382 // not treat an EOF from Read as an error to be reported. 383 // 384 // If src implements the WriterTo interface, 385 // the copy is implemented by calling src.WriteTo(dst). 386 // Otherwise, if dst implements the ReaderFrom interface, 387 // the copy is implemented by calling dst.ReadFrom(src). 388 func Copy(dst Writer, src Reader) (written int64, err error) { 389 return copyBuffer(dst, src, nil) 390 } 391 392 // CopyBuffer is identical to Copy except that it stages through the 393 // provided buffer (if one is required) rather than allocating a 394 // temporary one. If buf is nil, one is allocated; otherwise if it has 395 // zero length, CopyBuffer panics. 396 // 397 // If either src implements WriterTo or dst implements ReaderFrom, 398 // buf will not be used to perform the copy. 399 func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) { 400 if buf != nil && len(buf) == 0 { 401 panic("empty buffer in CopyBuffer") 402 } 403 return copyBuffer(dst, src, buf) 404 } 405 406 // copyBuffer is the actual implementation of Copy and CopyBuffer. 407 // if buf is nil, one is allocated. 408 func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) { 409 // If the reader has a WriteTo method, use it to do the copy. 410 // Avoids an allocation and a copy. 411 if wt, ok := src.(WriterTo); ok { 412 return wt.WriteTo(dst) 413 } 414 // Similarly, if the writer has a ReadFrom method, use it to do the copy. 415 if rt, ok := dst.(ReaderFrom); ok { 416 return rt.ReadFrom(src) 417 } 418 if buf == nil { 419 size := 32 * 1024 420 if l, ok := src.(*LimitedReader); ok && int64(size) > l.N { 421 if l.N < 1 { 422 size = 1 423 } else { 424 size = int(l.N) 425 } 426 } 427 buf = make([]byte, size) 428 } 429 for { 430 nr, er := src.Read(buf) 431 if nr > 0 { 432 nw, ew := dst.Write(buf[0:nr]) 433 if nw < 0 || nr < nw { 434 nw = 0 435 if ew == nil { 436 ew = errInvalidWrite 437 } 438 } 439 written += int64(nw) 440 if ew != nil { 441 err = ew 442 break 443 } 444 if nr != nw { 445 err = ErrShortWrite 446 break 447 } 448 } 449 if er != nil { 450 if er != EOF { 451 err = er 452 } 453 break 454 } 455 } 456 return written, err 457 } 458 459 // LimitReader returns a Reader that reads from r 460 // but stops with EOF after n bytes. 461 // The underlying implementation is a *LimitedReader. 462 func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} } 463 464 // A LimitedReader reads from R but limits the amount of 465 // data returned to just N bytes. Each call to Read 466 // updates N to reflect the new amount remaining. 467 // Read returns EOF when N <= 0 or when the underlying R returns EOF. 468 type LimitedReader struct { 469 R Reader // underlying reader 470 N int64 // max bytes remaining 471 } 472 473 func (l *LimitedReader) Read(p []byte) (n int, err error) { 474 if l.N <= 0 { 475 return 0, EOF 476 } 477 if int64(len(p)) > l.N { 478 p = p[0:l.N] 479 } 480 n, err = l.R.Read(p) 481 l.N -= int64(n) 482 return 483 } 484 485 // NewSectionReader returns a SectionReader that reads from r 486 // starting at offset off and stops with EOF after n bytes. 487 func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { 488 var remaining int64 489 const maxint64 = 1<<63 - 1 490 if off <= maxint64-n { 491 remaining = n + off 492 } else { 493 // Overflow, with no way to return error. 494 // Assume we can read up to an offset of 1<<63 - 1. 495 remaining = maxint64 496 } 497 return &SectionReader{r, off, off, remaining} 498 } 499 500 // SectionReader implements Read, Seek, and ReadAt on a section 501 // of an underlying ReaderAt. 502 type SectionReader struct { 503 r ReaderAt 504 base int64 505 off int64 506 limit int64 507 } 508 509 func (s *SectionReader) Read(p []byte) (n int, err error) { 510 if s.off >= s.limit { 511 return 0, EOF 512 } 513 if max := s.limit - s.off; int64(len(p)) > max { 514 p = p[0:max] 515 } 516 n, err = s.r.ReadAt(p, s.off) 517 s.off += int64(n) 518 return 519 } 520 521 var errWhence = errors.New("Seek: invalid whence") 522 var errOffset = errors.New("Seek: invalid offset") 523 524 func (s *SectionReader) Seek(offset int64, whence int) (int64, error) { 525 switch whence { 526 default: 527 return 0, errWhence 528 case SeekStart: 529 offset += s.base 530 case SeekCurrent: 531 offset += s.off 532 case SeekEnd: 533 offset += s.limit 534 } 535 if offset < s.base { 536 return 0, errOffset 537 } 538 s.off = offset 539 return offset - s.base, nil 540 } 541 542 func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) { 543 if off < 0 || off >= s.limit-s.base { 544 return 0, EOF 545 } 546 off += s.base 547 if max := s.limit - off; int64(len(p)) > max { 548 p = p[0:max] 549 n, err = s.r.ReadAt(p, off) 550 if err == nil { 551 err = EOF 552 } 553 return n, err 554 } 555 return s.r.ReadAt(p, off) 556 } 557 558 // Size returns the size of the section in bytes. 559 func (s *SectionReader) Size() int64 { return s.limit - s.base } 560 561 // An OffsetWriter maps writes at offset base to offset base+off in the underlying writer. 562 type OffsetWriter struct { 563 w WriterAt 564 base int64 // the original offset 565 off int64 // the current offset 566 } 567 568 // NewOffsetWriter returns an OffsetWriter that writes to w 569 // starting at offset off. 570 func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter { 571 return &OffsetWriter{w, off, off} 572 } 573 574 func (o *OffsetWriter) Write(p []byte) (n int, err error) { 575 n, err = o.w.WriteAt(p, o.off) 576 o.off += int64(n) 577 return 578 } 579 580 func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error) { 581 if off < 0 { 582 return 0, errOffset 583 } 584 585 off += o.base 586 return o.w.WriteAt(p, off) 587 } 588 589 func (o *OffsetWriter) Seek(offset int64, whence int) (int64, error) { 590 switch whence { 591 default: 592 return 0, errWhence 593 case SeekStart: 594 offset += o.base 595 case SeekCurrent: 596 offset += o.off 597 } 598 if offset < o.base { 599 return 0, errOffset 600 } 601 o.off = offset 602 return offset - o.base, nil 603 } 604 605 // TeeReader returns a Reader that writes to w what it reads from r. 606 // All reads from r performed through it are matched with 607 // corresponding writes to w. There is no internal buffering - 608 // the write must complete before the read completes. 609 // Any error encountered while writing is reported as a read error. 610 func TeeReader(r Reader, w Writer) Reader { 611 return &teeReader{r, w} 612 } 613 614 type teeReader struct { 615 r Reader 616 w Writer 617 } 618 619 func (t *teeReader) Read(p []byte) (n int, err error) { 620 n, err = t.r.Read(p) 621 if n > 0 { 622 if n, err := t.w.Write(p[:n]); err != nil { 623 return n, err 624 } 625 } 626 return 627 } 628 629 // Discard is a Writer on which all Write calls succeed 630 // without doing anything. 631 var Discard Writer = discard{} 632 633 type discard struct{} 634 635 // discard implements ReaderFrom as an optimization so Copy to 636 // io.Discard can avoid doing unnecessary work. 637 var _ ReaderFrom = discard{} 638 639 func (discard) Write(p []byte) (int, error) { 640 return len(p), nil 641 } 642 643 func (discard) WriteString(s string) (int, error) { 644 return len(s), nil 645 } 646 647 var blackHolePool = sync.Pool{ 648 New: func() any { 649 b := make([]byte, 8192) 650 return &b 651 }, 652 } 653 654 func (discard) ReadFrom(r Reader) (n int64, err error) { 655 bufp := blackHolePool.Get().(*[]byte) 656 readSize := 0 657 for { 658 readSize, err = r.Read(*bufp) 659 n += int64(readSize) 660 if err != nil { 661 blackHolePool.Put(bufp) 662 if err == EOF { 663 return n, nil 664 } 665 return 666 } 667 } 668 } 669 670 // NopCloser returns a ReadCloser with a no-op Close method wrapping 671 // the provided Reader r. 672 // If r implements WriterTo, the returned ReadCloser will implement WriterTo 673 // by forwarding calls to r. 674 func NopCloser(r Reader) ReadCloser { 675 if _, ok := r.(WriterTo); ok { 676 return nopCloserWriterTo{r} 677 } 678 return nopCloser{r} 679 } 680 681 type nopCloser struct { 682 Reader 683 } 684 685 func (nopCloser) Close() error { return nil } 686 687 type nopCloserWriterTo struct { 688 Reader 689 } 690 691 func (nopCloserWriterTo) Close() error { return nil } 692 693 func (c nopCloserWriterTo) WriteTo(w Writer) (n int64, err error) { 694 return c.Reader.(WriterTo).WriteTo(w) 695 } 696 697 // ReadAll reads from r until an error or EOF and returns the data it read. 698 // A successful call returns err == nil, not err == EOF. Because ReadAll is 699 // defined to read from src until EOF, it does not treat an EOF from Read 700 // as an error to be reported. 701 func ReadAll(r Reader) ([]byte, error) { 702 b := make([]byte, 0, 512) 703 for { 704 n, err := r.Read(b[len(b):cap(b)]) 705 b = b[:len(b)+n] 706 if err != nil { 707 if err == EOF { 708 err = nil 709 } 710 return b, err 711 } 712 713 if len(b) == cap(b) { 714 // Add more capacity (let append pick how much). 715 b = append(b, 0)[:len(b)] 716 } 717 } 718 } 719