Debian Codegraph @

libgo/go/io/io.go

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