OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [bufio/] [bufio.go] - Blame information for rev 814

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.