OSDN Git Service

7074834d6137f1aad12b0fd3cd919216efe71ce9
[pf3gnuchains/gcc-fork.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 type ReaderFrom interface {
134         ReadFrom(r Reader) (n int64, err error)
135 }
136
137 // WriterTo is the interface that wraps the WriteTo method.
138 type WriterTo interface {
139         WriteTo(w Writer) (n int64, err error)
140 }
141
142 // ReaderAt is the interface that wraps the basic ReadAt method.
143 //
144 // ReadAt reads len(p) bytes into p starting at offset off in the
145 // underlying input source.  It returns the number of bytes
146 // read (0 <= n <= len(p)) and any error encountered.
147 //
148 // When ReadAt returns n < len(p), it returns a non-nil error
149 // explaining why more bytes were not returned.  In this respect,
150 // ReadAt is stricter than Read.
151 //
152 // Even if ReadAt returns n < len(p), it may use all of p as scratch
153 // space during the call.  If some data is available but not len(p) bytes,
154 // ReadAt blocks until either all the data is available or an error occurs.
155 // In this respect ReadAt is different from Read.
156 //
157 // If the n = len(p) bytes returned by ReadAt are at the end of the
158 // input source, ReadAt may return either err == EOF or err == nil.
159 //
160 // If ReadAt is reading from an input source with a seek offset,
161 // ReadAt should not affect nor be affected by the underlying
162 // seek offset.
163 //
164 // Clients of ReadAt can execute parallel ReadAt calls on the
165 // same input source.
166 type ReaderAt interface {
167         ReadAt(p []byte, off int64) (n int, err error)
168 }
169
170 // WriterAt is the interface that wraps the basic WriteAt method.
171 //
172 // WriteAt writes len(p) bytes from p to the underlying data stream
173 // at offset off.  It returns the number of bytes written from p (0 <= n <= len(p))
174 // and any error encountered that caused the write to stop early.
175 // WriteAt must return a non-nil error if it returns n < len(p).
176 type WriterAt interface {
177         WriteAt(p []byte, off int64) (n int, err error)
178 }
179
180 // ByteReader is the interface that wraps the ReadByte method.
181 //
182 // ReadByte reads and returns the next byte from the input.
183 // If no byte is available, err will be set.
184 type ByteReader interface {
185         ReadByte() (c byte, err error)
186 }
187
188 // ByteScanner is the interface that adds the UnreadByte method to the
189 // basic ReadByte method.
190 //
191 // UnreadByte causes the next call to ReadByte to return the same byte
192 // as the previous call to ReadByte.
193 // It may be an error to call UnreadByte twice without an intervening
194 // call to ReadByte.
195 type ByteScanner interface {
196         ByteReader
197         UnreadByte() error
198 }
199
200 // RuneReader is the interface that wraps the ReadRune method.
201 //
202 // ReadRune reads a single UTF-8 encoded Unicode character
203 // and returns the rune and its size in bytes. If no character is
204 // available, err will be set.
205 type RuneReader interface {
206         ReadRune() (r rune, size int, err error)
207 }
208
209 // RuneScanner is the interface that adds the UnreadRune method to the
210 // basic ReadRune method.
211 //
212 // UnreadRune causes the next call to ReadRune to return the same rune
213 // as the previous call to ReadRune.
214 // It may be an error to call UnreadRune twice without an intervening
215 // call to ReadRune.
216 type RuneScanner interface {
217         RuneReader
218         UnreadRune() error
219 }
220
221 // stringWriter is the interface that wraps the WriteString method.
222 type stringWriter interface {
223         WriteString(s string) (n int, err error)
224 }
225
226 // WriteString writes the contents of the string s to w, which accepts an array of bytes.
227 // If w already implements a WriteString method, it is invoked directly.
228 func WriteString(w Writer, s string) (n int, err error) {
229         if sw, ok := w.(stringWriter); ok {
230                 return sw.WriteString(s)
231         }
232         return w.Write([]byte(s))
233 }
234
235 // ReadAtLeast reads from r into buf until it has read at least min bytes.
236 // It returns the number of bytes copied and an error if fewer bytes were read.
237 // The error is EOF only if no bytes were read.
238 // If an EOF happens after reading fewer than min bytes,
239 // ReadAtLeast returns ErrUnexpectedEOF.
240 // If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer.
241 func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) {
242         if len(buf) < min {
243                 return 0, ErrShortBuffer
244         }
245         for n < min && err == nil {
246                 var nn int
247                 nn, err = r.Read(buf[n:])
248                 n += nn
249         }
250         if err == EOF {
251                 if n >= min {
252                         err = nil
253                 } else if n > 0 {
254                         err = ErrUnexpectedEOF
255                 }
256         }
257         return
258 }
259
260 // ReadFull reads exactly len(buf) bytes from r into buf.
261 // It returns the number of bytes copied and an error if fewer bytes were read.
262 // The error is EOF only if no bytes were read.
263 // If an EOF happens after reading some but not all the bytes,
264 // ReadFull returns ErrUnexpectedEOF.
265 func ReadFull(r Reader, buf []byte) (n int, err error) {
266         return ReadAtLeast(r, buf, len(buf))
267 }
268
269 // CopyN copies n bytes (or until an error) from src to dst.
270 // It returns the number of bytes copied and the earliest
271 // error encountered while copying.  Because Read can
272 // return the full amount requested as well as an error
273 // (including EOF), so can CopyN.
274 //
275 // If dst implements the ReaderFrom interface,
276 // the copy is implemented using it.
277 func CopyN(dst Writer, src Reader, n int64) (written int64, err error) {
278         // If the writer has a ReadFrom method, use it to do the copy.
279         // Avoids a buffer allocation and a copy.
280         if rt, ok := dst.(ReaderFrom); ok {
281                 written, err = rt.ReadFrom(LimitReader(src, n))
282                 if written < n && err == nil {
283                         // rt stopped early; must have been EOF.
284                         err = EOF
285                 }
286                 return
287         }
288         buf := make([]byte, 32*1024)
289         for written < n {
290                 l := len(buf)
291                 if d := n - written; d < int64(l) {
292                         l = int(d)
293                 }
294                 nr, er := src.Read(buf[0:l])
295                 if nr > 0 {
296                         nw, ew := dst.Write(buf[0:nr])
297                         if nw > 0 {
298                                 written += int64(nw)
299                         }
300                         if ew != nil {
301                                 err = ew
302                                 break
303                         }
304                         if nr != nw {
305                                 err = ErrShortWrite
306                                 break
307                         }
308                 }
309                 if er != nil {
310                         err = er
311                         break
312                 }
313         }
314         return written, err
315 }
316
317 // Copy copies from src to dst until either EOF is reached
318 // on src or an error occurs.  It returns the number of bytes
319 // copied and the first error encountered while copying, if any.
320 //
321 // A successful Copy returns err == nil, not err == EOF.
322 // Because Copy is defined to read from src until EOF, it does
323 // not treat an EOF from Read as an error to be reported.
324 //
325 // If dst implements the ReaderFrom interface,
326 // the copy is implemented by calling dst.ReadFrom(src).
327 // Otherwise, if src implements the WriterTo interface,
328 // the copy is implemented by calling src.WriteTo(dst).
329 func Copy(dst Writer, src Reader) (written int64, err error) {
330         // If the writer has a ReadFrom method, use it to do the copy.
331         // Avoids an allocation and a copy.
332         if rt, ok := dst.(ReaderFrom); ok {
333                 return rt.ReadFrom(src)
334         }
335         // Similarly, if the reader has a WriteTo method, use it to do the copy.
336         if wt, ok := src.(WriterTo); ok {
337                 return wt.WriteTo(dst)
338         }
339         buf := make([]byte, 32*1024)
340         for {
341                 nr, er := src.Read(buf)
342                 if nr > 0 {
343                         nw, ew := dst.Write(buf[0:nr])
344                         if nw > 0 {
345                                 written += int64(nw)
346                         }
347                         if ew != nil {
348                                 err = ew
349                                 break
350                         }
351                         if nr != nw {
352                                 err = ErrShortWrite
353                                 break
354                         }
355                 }
356                 if er == EOF {
357                         break
358                 }
359                 if er != nil {
360                         err = er
361                         break
362                 }
363         }
364         return written, err
365 }
366
367 // LimitReader returns a Reader that reads from r
368 // but stops with EOF after n bytes.
369 // The underlying implementation is a *LimitedReader.
370 func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
371
372 // A LimitedReader reads from R but limits the amount of
373 // data returned to just N bytes. Each call to Read
374 // updates N to reflect the new amount remaining.
375 type LimitedReader struct {
376         R Reader // underlying reader
377         N int64  // max bytes remaining
378 }
379
380 func (l *LimitedReader) Read(p []byte) (n int, err error) {
381         if l.N <= 0 {
382                 return 0, EOF
383         }
384         if int64(len(p)) > l.N {
385                 p = p[0:l.N]
386         }
387         n, err = l.R.Read(p)
388         l.N -= int64(n)
389         return
390 }
391
392 // NewSectionReader returns a SectionReader that reads from r
393 // starting at offset off and stops with EOF after n bytes.
394 func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader {
395         return &SectionReader{r, off, off, off + n}
396 }
397
398 // SectionReader implements Read, Seek, and ReadAt on a section
399 // of an underlying ReaderAt.
400 type SectionReader struct {
401         r     ReaderAt
402         base  int64
403         off   int64
404         limit int64
405 }
406
407 func (s *SectionReader) Read(p []byte) (n int, err error) {
408         if s.off >= s.limit {
409                 return 0, EOF
410         }
411         if max := s.limit - s.off; int64(len(p)) > max {
412                 p = p[0:max]
413         }
414         n, err = s.r.ReadAt(p, s.off)
415         s.off += int64(n)
416         return
417 }
418
419 var errWhence = errors.New("Seek: invalid whence")
420 var errOffset = errors.New("Seek: invalid offset")
421
422 func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err error) {
423         switch whence {
424         default:
425                 return 0, errWhence
426         case 0:
427                 offset += s.base
428         case 1:
429                 offset += s.off
430         case 2:
431                 offset += s.limit
432         }
433         if offset < s.base || offset > s.limit {
434                 return 0, errOffset
435         }
436         s.off = offset
437         return offset - s.base, nil
438 }
439
440 func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) {
441         if off < 0 || off >= s.limit-s.base {
442                 return 0, EOF
443         }
444         off += s.base
445         if max := s.limit - off; int64(len(p)) > max {
446                 p = p[0:max]
447         }
448         return s.r.ReadAt(p, off)
449 }
450
451 // Size returns the size of the section in bytes.
452 func (s *SectionReader) Size() int64 { return s.limit - s.base }
453
454 // TeeReader returns a Reader that writes to w what it reads from r.
455 // All reads from r performed through it are matched with
456 // corresponding writes to w.  There is no internal buffering -
457 // the write must complete before the read completes.
458 // Any error encountered while writing is reported as a read error.
459 func TeeReader(r Reader, w Writer) Reader {
460         return &teeReader{r, w}
461 }
462
463 type teeReader struct {
464         r Reader
465         w Writer
466 }
467
468 func (t *teeReader) Read(p []byte) (n int, err error) {
469         n, err = t.r.Read(p)
470         if n > 0 {
471                 if n, err := t.w.Write(p[:n]); err != nil {
472                         return n, err
473                 }
474         }
475         return
476 }