...
Run Format

Source file src/pkg/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	)
    18	
    19	// ErrShortWrite means that a write accepted fewer bytes than requested
    20	// but failed to return an explicit error.
    21	var ErrShortWrite = errors.New("short write")
    22	
    23	// ErrShortBuffer means that a read required a longer buffer than was provided.
    24	var ErrShortBuffer = errors.New("short buffer")
    25	
    26	// EOF is the error returned by Read when no more input is available.
    27	// Functions should return EOF only to signal a graceful end of input.
    28	// If the EOF occurs unexpectedly in a structured data stream,
    29	// the appropriate error is either ErrUnexpectedEOF or some other error
    30	// giving more detail.
    31	var EOF = errors.New("EOF")
    32	
    33	// ErrUnexpectedEOF means that EOF was encountered in the
    34	// middle of reading a fixed-size block or data structure.
    35	var ErrUnexpectedEOF = errors.New("unexpected EOF")
    36	
    37	// ErrNoProgress is returned by some clients of an io.Reader when
    38	// many calls to Read have failed to return any data or error,
    39	// usually the sign of a broken io.Reader implementation.
    40	var ErrNoProgress = errors.New("multiple Read calls return no data or error")
    41	
    42	// Reader is the interface that wraps the basic Read method.
    43	//
    44	// Read reads up to len(p) bytes into p.  It returns the number of bytes
    45	// read (0 <= n <= len(p)) and any error encountered.  Even if Read
    46	// returns n < len(p), it may use all of p as scratch space during the call.
    47	// If some data is available but not len(p) bytes, Read conventionally
    48	// returns what is available instead of waiting for more.
    49	//
    50	// When Read encounters an error or end-of-file condition after
    51	// successfully reading n > 0 bytes, it returns the number of
    52	// bytes read.  It may return the (non-nil) error from the same call
    53	// or return the error (and n == 0) from a subsequent call.
    54	// An instance of this general case is that a Reader returning
    55	// a non-zero number of bytes at the end of the input stream may
    56	// return either err == EOF or err == nil.  The next Read should
    57	// return 0, EOF regardless.
    58	//
    59	// Callers should always process the n > 0 bytes returned before
    60	// considering the error err.  Doing so correctly handles I/O errors
    61	// that happen after reading some bytes and also both of the
    62	// allowed EOF behaviors.
    63	//
    64	// Implementations of Read are discouraged from returning a
    65	// zero byte count with a nil error, and callers should treat
    66	// that situation as a no-op.
    67	type Reader interface {
    68		Read(p []byte) (n int, err error)
    69	}
    70	
    71	// Writer is the interface that wraps the basic Write method.
    72	//
    73	// Write writes len(p) bytes from p to the underlying data stream.
    74	// It returns the number of bytes written from p (0 <= n <= len(p))
    75	// and any error encountered that caused the write to stop early.
    76	// Write must return a non-nil error if it returns n < len(p).
    77	// Write must not modify the slice data, even temporarily.
    78	type Writer interface {
    79		Write(p []byte) (n int, err error)
    80	}
    81	
    82	// Closer is the interface that wraps the basic Close method.
    83	//
    84	// The behavior of Close after the first call is undefined.
    85	// Specific implementations may document their own behavior.
    86	type Closer interface {
    87		Close() error
    88	}
    89	
    90	// Seeker is the interface that wraps the basic Seek method.
    91	//
    92	// Seek sets the offset for the next Read or Write to offset,
    93	// interpreted according to whence: 0 means relative to the origin of
    94	// the file, 1 means relative to the current offset, and 2 means
    95	// relative to the end.  Seek returns the new offset and an error, if
    96	// any.
    97	//
    98	// Seeking to a negative offset is an error. Seeking to any positive
    99	// offset is legal, but the behavior of subsequent I/O operations on
   100	// the underlying object is implementation-dependent.
   101	type Seeker interface {
   102		Seek(offset int64, whence int) (int64, error)
   103	}
   104	
   105	// ReadWriter is the interface that groups the basic Read and Write methods.
   106	type ReadWriter interface {
   107		Reader
   108		Writer
   109	}
   110	
   111	// ReadCloser is the interface that groups the basic Read and Close methods.
   112	type ReadCloser interface {
   113		Reader
   114		Closer
   115	}
   116	
   117	// WriteCloser is the interface that groups the basic Write and Close methods.
   118	type WriteCloser interface {
   119		Writer
   120		Closer
   121	}
   122	
   123	// ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.
   124	type ReadWriteCloser interface {
   125		Reader
   126		Writer
   127		Closer
   128	}
   129	
   130	// ReadSeeker is the interface that groups the basic Read and Seek methods.
   131	type ReadSeeker interface {
   132		Reader
   133		Seeker
   134	}
   135	
   136	// WriteSeeker is the interface that groups the basic Write and Seek methods.
   137	type WriteSeeker interface {
   138		Writer
   139		Seeker
   140	}
   141	
   142	// ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.
   143	type ReadWriteSeeker interface {
   144		Reader
   145		Writer
   146		Seeker
   147	}
   148	
   149	// ReaderFrom is the interface that wraps the ReadFrom method.
   150	//
   151	// ReadFrom reads data from r until EOF or error.
   152	// The return value n is the number of bytes read.
   153	// Any error except io.EOF encountered during the read is also returned.
   154	//
   155	// The Copy function uses ReaderFrom if available.
   156	type ReaderFrom interface {
   157		ReadFrom(r Reader) (n int64, err error)
   158	}
   159	
   160	// WriterTo is the interface that wraps the WriteTo method.
   161	//
   162	// WriteTo writes data to w until there's no more data to write or
   163	// when an error occurs. The return value n is the number of bytes
   164	// written. Any error encountered during the write is also returned.
   165	//
   166	// The Copy function uses WriterTo if available.
   167	type WriterTo interface {
   168		WriteTo(w Writer) (n int64, err error)
   169	}
   170	
   171	// ReaderAt is the interface that wraps the basic ReadAt method.
   172	//
   173	// ReadAt reads len(p) bytes into p starting at offset off in the
   174	// underlying input source.  It returns the number of bytes
   175	// read (0 <= n <= len(p)) and any error encountered.
   176	//
   177	// When ReadAt returns n < len(p), it returns a non-nil error
   178	// explaining why more bytes were not returned.  In this respect,
   179	// ReadAt is stricter than Read.
   180	//
   181	// Even if ReadAt returns n < len(p), it may use all of p as scratch
   182	// space during the call.  If some data is available but not len(p) bytes,
   183	// ReadAt blocks until either all the data is available or an error occurs.
   184	// In this respect ReadAt is different from Read.
   185	//
   186	// If the n = len(p) bytes returned by ReadAt are at the end of the
   187	// input source, ReadAt may return either err == EOF or err == nil.
   188	//
   189	// If ReadAt is reading from an input source with a seek offset,
   190	// ReadAt should not affect nor be affected by the underlying
   191	// seek offset.
   192	//
   193	// Clients of ReadAt can execute parallel ReadAt calls on the
   194	// same input source.
   195	type ReaderAt interface {
   196		ReadAt(p []byte, off int64) (n int, err error)
   197	}
   198	
   199	// WriterAt is the interface that wraps the basic WriteAt method.
   200	//
   201	// WriteAt writes len(p) bytes from p to the underlying data stream
   202	// at offset off.  It returns the number of bytes written from p (0 <= n <= len(p))
   203	// and any error encountered that caused the write to stop early.
   204	// WriteAt must return a non-nil error if it returns n < len(p).
   205	//
   206	// If WriteAt is writing to a destination with a seek offset,
   207	// WriteAt should not affect nor be affected by the underlying
   208	// seek offset.
   209	//
   210	// Clients of WriteAt can execute parallel WriteAt calls on the same
   211	// destination if the ranges do not overlap.
   212	type WriterAt interface {
   213		WriteAt(p []byte, off int64) (n int, err error)
   214	}
   215	
   216	// ByteReader is the interface that wraps the ReadByte method.
   217	//
   218	// ReadByte reads and returns the next byte from the input.
   219	// If no byte is available, err will be set.
   220	type ByteReader interface {
   221		ReadByte() (c byte, err error)
   222	}
   223	
   224	// ByteScanner is the interface that adds the UnreadByte method to the
   225	// basic ReadByte method.
   226	//
   227	// UnreadByte causes the next call to ReadByte to return the same byte
   228	// as the previous call to ReadByte.
   229	// It may be an error to call UnreadByte twice without an intervening
   230	// call to ReadByte.
   231	type ByteScanner interface {
   232		ByteReader
   233		UnreadByte() error
   234	}
   235	
   236	// ByteWriter is the interface that wraps the WriteByte method.
   237	type ByteWriter interface {
   238		WriteByte(c byte) error
   239	}
   240	
   241	// RuneReader is the interface that wraps the ReadRune method.
   242	//
   243	// ReadRune reads a single UTF-8 encoded Unicode character
   244	// and returns the rune and its size in bytes. If no character is
   245	// available, err will be set.
   246	type RuneReader interface {
   247		ReadRune() (r rune, size int, err error)
   248	}
   249	
   250	// RuneScanner is the interface that adds the UnreadRune method to the
   251	// basic ReadRune method.
   252	//
   253	// UnreadRune causes the next call to ReadRune to return the same rune
   254	// as the previous call to ReadRune.
   255	// It may be an error to call UnreadRune twice without an intervening
   256	// call to ReadRune.
   257	type RuneScanner interface {
   258		RuneReader
   259		UnreadRune() error
   260	}
   261	
   262	// stringWriter is the interface that wraps the WriteString method.
   263	type stringWriter interface {
   264		WriteString(s string) (n int, err error)
   265	}
   266	
   267	// WriteString writes the contents of the string s to w, which accepts an array of bytes.
   268	// If w already implements a WriteString method, it is invoked directly.
   269	func WriteString(w Writer, s string) (n int, err error) {
   270		if sw, ok := w.(stringWriter); ok {
   271			return sw.WriteString(s)
   272		}
   273		return w.Write([]byte(s))
   274	}
   275	
   276	// ReadAtLeast reads from r into buf until it has read at least min bytes.
   277	// It returns the number of bytes copied and an error if fewer bytes were read.
   278	// The error is EOF only if no bytes were read.
   279	// If an EOF happens after reading fewer than min bytes,
   280	// ReadAtLeast returns ErrUnexpectedEOF.
   281	// If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer.
   282	// On return, n >= min if and only if err == nil.
   283	func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) {
   284		if len(buf) < min {
   285			return 0, ErrShortBuffer
   286		}
   287		for n < min && err == nil {
   288			var nn int
   289			nn, err = r.Read(buf[n:])
   290			n += nn
   291		}
   292		if n >= min {
   293			err = nil
   294		} else if n > 0 && err == EOF {
   295			err = ErrUnexpectedEOF
   296		}
   297		return
   298	}
   299	
   300	// ReadFull reads exactly len(buf) bytes from r into buf.
   301	// It returns the number of bytes copied and an error if fewer bytes were read.
   302	// The error is EOF only if no bytes were read.
   303	// If an EOF happens after reading some but not all the bytes,
   304	// ReadFull returns ErrUnexpectedEOF.
   305	// On return, n == len(buf) if and only if err == nil.
   306	func ReadFull(r Reader, buf []byte) (n int, err error) {
   307		return ReadAtLeast(r, buf, len(buf))
   308	}
   309	
   310	// CopyN copies n bytes (or until an error) from src to dst.
   311	// It returns the number of bytes copied and the earliest
   312	// error encountered while copying.
   313	// On return, written == n if and only if err == nil.
   314	//
   315	// If dst implements the ReaderFrom interface,
   316	// the copy is implemented using it.
   317	func CopyN(dst Writer, src Reader, n int64) (written int64, err error) {
   318		written, err = Copy(dst, LimitReader(src, n))
   319		if written == n {
   320			return n, nil
   321		}
   322		if written < n && err == nil {
   323			// src stopped early; must have been EOF.
   324			err = EOF
   325		}
   326		return
   327	}
   328	
   329	// Copy copies from src to dst until either EOF is reached
   330	// on src or an error occurs.  It returns the number of bytes
   331	// copied and the first error encountered while copying, if any.
   332	//
   333	// A successful Copy returns err == nil, not err == EOF.
   334	// Because Copy is defined to read from src until EOF, it does
   335	// not treat an EOF from Read as an error to be reported.
   336	//
   337	// If src implements the WriterTo interface,
   338	// the copy is implemented by calling src.WriteTo(dst).
   339	// Otherwise, if dst implements the ReaderFrom interface,
   340	// the copy is implemented by calling dst.ReadFrom(src).
   341	func Copy(dst Writer, src Reader) (written int64, err error) {
   342		// If the reader has a WriteTo method, use it to do the copy.
   343		// Avoids an allocation and a copy.
   344		if wt, ok := src.(WriterTo); ok {
   345			return wt.WriteTo(dst)
   346		}
   347		// Similarly, if the writer has a ReadFrom method, use it to do the copy.
   348		if rt, ok := dst.(ReaderFrom); ok {
   349			return rt.ReadFrom(src)
   350		}
   351		buf := make([]byte, 32*1024)
   352		for {
   353			nr, er := src.Read(buf)
   354			if nr > 0 {
   355				nw, ew := dst.Write(buf[0:nr])
   356				if nw > 0 {
   357					written += int64(nw)
   358				}
   359				if ew != nil {
   360					err = ew
   361					break
   362				}
   363				if nr != nw {
   364					err = ErrShortWrite
   365					break
   366				}
   367			}
   368			if er == EOF {
   369				break
   370			}
   371			if er != nil {
   372				err = er
   373				break
   374			}
   375		}
   376		return written, err
   377	}
   378	
   379	// LimitReader returns a Reader that reads from r
   380	// but stops with EOF after n bytes.
   381	// The underlying implementation is a *LimitedReader.
   382	func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
   383	
   384	// A LimitedReader reads from R but limits the amount of
   385	// data returned to just N bytes. Each call to Read
   386	// updates N to reflect the new amount remaining.
   387	type LimitedReader struct {
   388		R Reader // underlying reader
   389		N int64  // max bytes remaining
   390	}
   391	
   392	func (l *LimitedReader) Read(p []byte) (n int, err error) {
   393		if l.N <= 0 {
   394			return 0, EOF
   395		}
   396		if int64(len(p)) > l.N {
   397			p = p[0:l.N]
   398		}
   399		n, err = l.R.Read(p)
   400		l.N -= int64(n)
   401		return
   402	}
   403	
   404	// NewSectionReader returns a SectionReader that reads from r
   405	// starting at offset off and stops with EOF after n bytes.
   406	func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader {
   407		return &SectionReader{r, off, off, off + n}
   408	}
   409	
   410	// SectionReader implements Read, Seek, and ReadAt on a section
   411	// of an underlying ReaderAt.
   412	type SectionReader struct {
   413		r     ReaderAt
   414		base  int64
   415		off   int64
   416		limit int64
   417	}
   418	
   419	func (s *SectionReader) Read(p []byte) (n int, err error) {
   420		if s.off >= s.limit {
   421			return 0, EOF
   422		}
   423		if max := s.limit - s.off; int64(len(p)) > max {
   424			p = p[0:max]
   425		}
   426		n, err = s.r.ReadAt(p, s.off)
   427		s.off += int64(n)
   428		return
   429	}
   430	
   431	var errWhence = errors.New("Seek: invalid whence")
   432	var errOffset = errors.New("Seek: invalid offset")
   433	
   434	func (s *SectionReader) Seek(offset int64, whence int) (int64, error) {
   435		switch whence {
   436		default:
   437			return 0, errWhence
   438		case 0:
   439			offset += s.base
   440		case 1:
   441			offset += s.off
   442		case 2:
   443			offset += s.limit
   444		}
   445		if offset < s.base {
   446			return 0, errOffset
   447		}
   448		s.off = offset
   449		return offset - s.base, nil
   450	}
   451	
   452	func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) {
   453		if off < 0 || off >= s.limit-s.base {
   454			return 0, EOF
   455		}
   456		off += s.base
   457		if max := s.limit - off; int64(len(p)) > max {
   458			p = p[0:max]
   459			n, err = s.r.ReadAt(p, off)
   460			if err == nil {
   461				err = EOF
   462			}
   463			return n, err
   464		}
   465		return s.r.ReadAt(p, off)
   466	}
   467	
   468	// Size returns the size of the section in bytes.
   469	func (s *SectionReader) Size() int64 { return s.limit - s.base }
   470	
   471	// TeeReader returns a Reader that writes to w what it reads from r.
   472	// All reads from r performed through it are matched with
   473	// corresponding writes to w.  There is no internal buffering -
   474	// the write must complete before the read completes.
   475	// Any error encountered while writing is reported as a read error.
   476	func TeeReader(r Reader, w Writer) Reader {
   477		return &teeReader{r, w}
   478	}
   479	
   480	type teeReader struct {
   481		r Reader
   482		w Writer
   483	}
   484	
   485	func (t *teeReader) Read(p []byte) (n int, err error) {
   486		n, err = t.r.Read(p)
   487		if n > 0 {
   488			if n, err := t.w.Write(p[:n]); err != nil {
   489				return n, err
   490			}
   491		}
   492		return
   493	}
   494	

View as plain text