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