OSDN Git Service

libgo: Update to weekly 2011-11-09.
[pf3gnuchains/gcc-fork.git] / libgo / go / bufio / bufio.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 bufio implements buffered I/O.  It wraps an io.Reader or io.Writer
6 // object, creating another object (Reader or Writer) that also implements
7 // the interface but provides buffering and some help for textual I/O.
8 package bufio
9
10 import (
11         "bytes"
12         "io"
13         "strconv"
14         "unicode/utf8"
15 )
16
17 const (
18         defaultBufSize = 4096
19 )
20
21 // Errors introduced by this package.
22 type Error struct {
23         ErrorString string
24 }
25
26 func (err *Error) Error() string { return err.ErrorString }
27
28 var (
29         ErrInvalidUnreadByte error = &Error{"bufio: invalid use of UnreadByte"}
30         ErrInvalidUnreadRune error = &Error{"bufio: invalid use of UnreadRune"}
31         ErrBufferFull        error = &Error{"bufio: buffer full"}
32         ErrNegativeCount     error = &Error{"bufio: negative count"}
33         errInternal          error = &Error{"bufio: internal error"}
34 )
35
36 // BufSizeError is the error representing an invalid buffer size.
37 type BufSizeError int
38
39 func (b BufSizeError) Error() string {
40         return "bufio: bad buffer size " + strconv.Itoa(int(b))
41 }
42
43 // Buffered input.
44
45 // Reader implements buffering for an io.Reader object.
46 type Reader struct {
47         buf          []byte
48         rd           io.Reader
49         r, w         int
50         err          error
51         lastByte     int
52         lastRuneSize int
53 }
54
55 // NewReaderSize creates a new Reader whose buffer has the specified size,
56 // which must be greater than one.  If the argument io.Reader is already a
57 // Reader with large enough size, it returns the underlying Reader.
58 // It returns the Reader and any error.
59 func NewReaderSize(rd io.Reader, size int) (*Reader, error) {
60         if size <= 1 {
61                 return nil, BufSizeError(size)
62         }
63         // Is it already a Reader?
64         b, ok := rd.(*Reader)
65         if ok && len(b.buf) >= size {
66                 return b, nil
67         }
68         b = new(Reader)
69         b.buf = make([]byte, size)
70         b.rd = rd
71         b.lastByte = -1
72         b.lastRuneSize = -1
73         return b, nil
74 }
75
76 // NewReader returns a new Reader whose buffer has the default size.
77 func NewReader(rd io.Reader) *Reader {
78         b, err := NewReaderSize(rd, defaultBufSize)
79         if err != nil {
80                 // cannot happen - defaultBufSize is a valid size
81                 panic(err)
82         }
83         return b
84 }
85
86 // fill reads a new chunk into the buffer.
87 func (b *Reader) fill() {
88         // Slide existing data to beginning.
89         if b.r > 0 {
90                 copy(b.buf, b.buf[b.r:b.w])
91                 b.w -= b.r
92                 b.r = 0
93         }
94
95         // Read new data.
96         n, e := b.rd.Read(b.buf[b.w:])
97         b.w += n
98         if e != nil {
99                 b.err = e
100         }
101 }
102
103 func (b *Reader) readErr() error {
104         err := b.err
105         b.err = nil
106         return err
107 }
108
109 // Peek returns the next n bytes without advancing the reader. The bytes stop
110 // being valid at the next read call. If Peek returns fewer than n bytes, it
111 // also returns an error explaining why the read is short. The error is
112 // ErrBufferFull if n is larger than b's buffer size.
113 func (b *Reader) Peek(n int) ([]byte, error) {
114         if n < 0 {
115                 return nil, ErrNegativeCount
116         }
117         if n > len(b.buf) {
118                 return nil, ErrBufferFull
119         }
120         for b.w-b.r < n && b.err == nil {
121                 b.fill()
122         }
123         m := b.w - b.r
124         if m > n {
125                 m = n
126         }
127         err := b.readErr()
128         if m < n && err == nil {
129                 err = ErrBufferFull
130         }
131         return b.buf[b.r : b.r+m], err
132 }
133
134 // Read reads data into p.
135 // It returns the number of bytes read into p.
136 // It calls Read at most once on the underlying Reader,
137 // hence n may be less than len(p).
138 // At EOF, the count will be zero and err will be io.EOF.
139 func (b *Reader) Read(p []byte) (n int, err error) {
140         n = len(p)
141         if n == 0 {
142                 return 0, b.readErr()
143         }
144         if b.w == b.r {
145                 if b.err != nil {
146                         return 0, b.readErr()
147                 }
148                 if len(p) >= len(b.buf) {
149                         // Large read, empty buffer.
150                         // Read directly into p to avoid copy.
151                         n, b.err = b.rd.Read(p)
152                         if n > 0 {
153                                 b.lastByte = int(p[n-1])
154                                 b.lastRuneSize = -1
155                         }
156                         return n, b.readErr()
157                 }
158                 b.fill()
159                 if b.w == b.r {
160                         return 0, b.readErr()
161                 }
162         }
163
164         if n > b.w-b.r {
165                 n = b.w - b.r
166         }
167         copy(p[0:n], b.buf[b.r:])
168         b.r += n
169         b.lastByte = int(b.buf[b.r-1])
170         b.lastRuneSize = -1
171         return n, nil
172 }
173
174 // ReadByte reads and returns a single byte.
175 // If no byte is available, returns an error.
176 func (b *Reader) ReadByte() (c byte, err error) {
177         b.lastRuneSize = -1
178         for b.w == b.r {
179                 if b.err != nil {
180                         return 0, b.readErr()
181                 }
182                 b.fill()
183         }
184         c = b.buf[b.r]
185         b.r++
186         b.lastByte = int(c)
187         return c, nil
188 }
189
190 // UnreadByte unreads the last byte.  Only the most recently read byte can be unread.
191 func (b *Reader) UnreadByte() error {
192         b.lastRuneSize = -1
193         if b.r == b.w && b.lastByte >= 0 {
194                 b.w = 1
195                 b.r = 0
196                 b.buf[0] = byte(b.lastByte)
197                 b.lastByte = -1
198                 return nil
199         }
200         if b.r <= 0 {
201                 return ErrInvalidUnreadByte
202         }
203         b.r--
204         b.lastByte = -1
205         return nil
206 }
207
208 // ReadRune reads a single UTF-8 encoded Unicode character and returns the
209 // rune and its size in bytes.
210 func (b *Reader) ReadRune() (r rune, size int, err error) {
211         for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil {
212                 b.fill()
213         }
214         b.lastRuneSize = -1
215         if b.r == b.w {
216                 return 0, 0, b.readErr()
217         }
218         r, size = rune(b.buf[b.r]), 1
219         if r >= 0x80 {
220                 r, size = utf8.DecodeRune(b.buf[b.r:b.w])
221         }
222         b.r += size
223         b.lastByte = int(b.buf[b.r-1])
224         b.lastRuneSize = size
225         return r, size, nil
226 }
227
228 // UnreadRune unreads the last rune.  If the most recent read operation on
229 // the buffer was not a ReadRune, UnreadRune returns an error.  (In this
230 // regard it is stricter than UnreadByte, which will unread the last byte
231 // from any read operation.)
232 func (b *Reader) UnreadRune() error {
233         if b.lastRuneSize < 0 || b.r == 0 {
234                 return ErrInvalidUnreadRune
235         }
236         b.r -= b.lastRuneSize
237         b.lastByte = -1
238         b.lastRuneSize = -1
239         return nil
240 }
241
242 // Buffered returns the number of bytes that can be read from the current buffer.
243 func (b *Reader) Buffered() int { return b.w - b.r }
244
245 // ReadSlice reads until the first occurrence of delim in the input,
246 // returning a slice pointing at the bytes in the buffer.
247 // The bytes stop being valid at the next read call.
248 // If ReadSlice encounters an error before finding a delimiter,
249 // it returns all the data in the buffer and the error itself (often io.EOF).
250 // ReadSlice fails with error ErrBufferFull if the buffer fills without a delim.
251 // Because the data returned from ReadSlice will be overwritten
252 // by the next I/O operation, most clients should use
253 // ReadBytes or ReadString instead.
254 // ReadSlice returns err != nil if and only if line does not end in delim.
255 func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
256         // Look in buffer.
257         if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
258                 line1 := b.buf[b.r : b.r+i+1]
259                 b.r += i + 1
260                 return line1, nil
261         }
262
263         // Read more into buffer, until buffer fills or we find delim.
264         for {
265                 if b.err != nil {
266                         line := b.buf[b.r:b.w]
267                         b.r = b.w
268                         return line, b.readErr()
269                 }
270
271                 n := b.Buffered()
272                 b.fill()
273
274                 // Search new part of buffer
275                 if i := bytes.IndexByte(b.buf[n:b.w], delim); i >= 0 {
276                         line := b.buf[0 : n+i+1]
277                         b.r = n + i + 1
278                         return line, nil
279                 }
280
281                 // Buffer is full?
282                 if b.Buffered() >= len(b.buf) {
283                         b.r = b.w
284                         return b.buf, ErrBufferFull
285                 }
286         }
287         panic("not reached")
288 }
289
290 // ReadLine tries to return a single line, not including the end-of-line bytes.
291 // If the line was too long for the buffer then isPrefix is set and the
292 // beginning of the line is returned. The rest of the line will be returned
293 // from future calls. isPrefix will be false when returning the last fragment
294 // of the line. The returned buffer is only valid until the next call to
295 // ReadLine. ReadLine either returns a non-nil line or it returns an error,
296 // never both.
297 func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
298         line, err = b.ReadSlice('\n')
299         if err == ErrBufferFull {
300                 // Handle the case where "\r\n" straddles the buffer.
301                 if len(line) > 0 && line[len(line)-1] == '\r' {
302                         // Put the '\r' back on buf and drop it from line.
303                         // Let the next call to ReadLine check for "\r\n".
304                         if b.r == 0 {
305                                 // should be unreachable
306                                 panic("bufio: tried to rewind past start of buffer")
307                         }
308                         b.r--
309                         line = line[:len(line)-1]
310                 }
311                 return line, true, nil
312         }
313
314         if len(line) == 0 {
315                 if err != nil {
316                         line = nil
317                 }
318                 return
319         }
320         err = nil
321
322         if line[len(line)-1] == '\n' {
323                 drop := 1
324                 if len(line) > 1 && line[len(line)-2] == '\r' {
325                         drop = 2
326                 }
327                 line = line[:len(line)-drop]
328         }
329         return
330 }
331
332 // ReadBytes reads until the first occurrence of delim in the input,
333 // returning a slice containing the data up to and including the delimiter.
334 // If ReadBytes encounters an error before finding a delimiter,
335 // it returns the data read before the error and the error itself (often io.EOF).
336 // ReadBytes returns err != nil if and only if the returned data does not end in
337 // delim.
338 func (b *Reader) ReadBytes(delim byte) (line []byte, err error) {
339         // Use ReadSlice to look for array,
340         // accumulating full buffers.
341         var frag []byte
342         var full [][]byte
343         err = nil
344
345         for {
346                 var e error
347                 frag, e = b.ReadSlice(delim)
348                 if e == nil { // got final fragment
349                         break
350                 }
351                 if e != ErrBufferFull { // unexpected error
352                         err = e
353                         break
354                 }
355
356                 // Make a copy of the buffer.
357                 buf := make([]byte, len(frag))
358                 copy(buf, frag)
359                 full = append(full, buf)
360         }
361
362         // Allocate new buffer to hold the full pieces and the fragment.
363         n := 0
364         for i := range full {
365                 n += len(full[i])
366         }
367         n += len(frag)
368
369         // Copy full pieces and fragment in.
370         buf := make([]byte, n)
371         n = 0
372         for i := range full {
373                 n += copy(buf[n:], full[i])
374         }
375         copy(buf[n:], frag)
376         return buf, err
377 }
378
379 // ReadString reads until the first occurrence of delim in the input,
380 // returning a string containing the data up to and including the delimiter.
381 // If ReadString encounters an error before finding a delimiter,
382 // it returns the data read before the error and the error itself (often io.EOF).
383 // ReadString returns err != nil if and only if the returned data does not end in
384 // delim.
385 func (b *Reader) ReadString(delim byte) (line string, err error) {
386         bytes, e := b.ReadBytes(delim)
387         return string(bytes), e
388 }
389
390 // buffered output
391
392 // Writer implements buffering for an io.Writer object.
393 type Writer struct {
394         err error
395         buf []byte
396         n   int
397         wr  io.Writer
398 }
399
400 // NewWriterSize creates a new Writer whose buffer has the specified size,
401 // which must be greater than zero. If the argument io.Writer is already a
402 // Writer with large enough size, it returns the underlying Writer.
403 // It returns the Writer and any error.
404 func NewWriterSize(wr io.Writer, size int) (*Writer, error) {
405         if size <= 0 {
406                 return nil, BufSizeError(size)
407         }
408         // Is it already a Writer?
409         b, ok := wr.(*Writer)
410         if ok && len(b.buf) >= size {
411                 return b, nil
412         }
413         b = new(Writer)
414         b.buf = make([]byte, size)
415         b.wr = wr
416         return b, nil
417 }
418
419 // NewWriter returns a new Writer whose buffer has the default size.
420 func NewWriter(wr io.Writer) *Writer {
421         b, err := NewWriterSize(wr, defaultBufSize)
422         if err != nil {
423                 // cannot happen - defaultBufSize is valid size
424                 panic(err)
425         }
426         return b
427 }
428
429 // Flush writes any buffered data to the underlying io.Writer.
430 func (b *Writer) Flush() error {
431         if b.err != nil {
432                 return b.err
433         }
434         if b.n == 0 {
435                 return nil
436         }
437         n, e := b.wr.Write(b.buf[0:b.n])
438         if n < b.n && e == nil {
439                 e = io.ErrShortWrite
440         }
441         if e != nil {
442                 if n > 0 && n < b.n {
443                         copy(b.buf[0:b.n-n], b.buf[n:b.n])
444                 }
445                 b.n -= n
446                 b.err = e
447                 return e
448         }
449         b.n = 0
450         return nil
451 }
452
453 // Available returns how many bytes are unused in the buffer.
454 func (b *Writer) Available() int { return len(b.buf) - b.n }
455
456 // Buffered returns the number of bytes that have been written into the current buffer.
457 func (b *Writer) Buffered() int { return b.n }
458
459 // Write writes the contents of p into the buffer.
460 // It returns the number of bytes written.
461 // If nn < len(p), it also returns an error explaining
462 // why the write is short.
463 func (b *Writer) Write(p []byte) (nn int, err error) {
464         for len(p) > b.Available() && b.err == nil {
465                 var n int
466                 if b.Buffered() == 0 {
467                         // Large write, empty buffer.
468                         // Write directly from p to avoid copy.
469                         n, b.err = b.wr.Write(p)
470                 } else {
471                         n = copy(b.buf[b.n:], p)
472                         b.n += n
473                         b.Flush()
474                 }
475                 nn += n
476                 p = p[n:]
477         }
478         if b.err != nil {
479                 return nn, b.err
480         }
481         n := copy(b.buf[b.n:], p)
482         b.n += n
483         nn += n
484         return nn, nil
485 }
486
487 // WriteByte writes a single byte.
488 func (b *Writer) WriteByte(c byte) error {
489         if b.err != nil {
490                 return b.err
491         }
492         if b.Available() <= 0 && b.Flush() != nil {
493                 return b.err
494         }
495         b.buf[b.n] = c
496         b.n++
497         return nil
498 }
499
500 // WriteRune writes a single Unicode code point, returning
501 // the number of bytes written and any error.
502 func (b *Writer) WriteRune(r rune) (size int, err error) {
503         if r < utf8.RuneSelf {
504                 err = b.WriteByte(byte(r))
505                 if err != nil {
506                         return 0, err
507                 }
508                 return 1, nil
509         }
510         if b.err != nil {
511                 return 0, b.err
512         }
513         n := b.Available()
514         if n < utf8.UTFMax {
515                 if b.Flush(); b.err != nil {
516                         return 0, b.err
517                 }
518                 n = b.Available()
519                 if n < utf8.UTFMax {
520                         // Can only happen if buffer is silly small.
521                         return b.WriteString(string(r))
522                 }
523         }
524         size = utf8.EncodeRune(b.buf[b.n:], r)
525         b.n += size
526         return size, nil
527 }
528
529 // WriteString writes a string.
530 // It returns the number of bytes written.
531 // If the count is less than len(s), it also returns an error explaining
532 // why the write is short.
533 func (b *Writer) WriteString(s string) (int, error) {
534         nn := 0
535         for len(s) > b.Available() && b.err == nil {
536                 n := copy(b.buf[b.n:], s)
537                 b.n += n
538                 nn += n
539                 s = s[n:]
540                 b.Flush()
541         }
542         if b.err != nil {
543                 return nn, b.err
544         }
545         n := copy(b.buf[b.n:], s)
546         b.n += n
547         nn += n
548         return nn, nil
549 }
550
551 // buffered input and output
552
553 // ReadWriter stores pointers to a Reader and a Writer.
554 // It implements io.ReadWriter.
555 type ReadWriter struct {
556         *Reader
557         *Writer
558 }
559
560 // NewReadWriter allocates a new ReadWriter that dispatches to r and w.
561 func NewReadWriter(r *Reader, w *Writer) *ReadWriter {
562         return &ReadWriter{r, w}
563 }