summaryrefslogtreecommitdiff
path: root/src/lib/bufio.go
blob: fd3267fd44cab68f0bfe8bf9e2e08c636ff95509 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bufio

import (
	"os";
	"io";
	"utf8";
)


// TODO:
//	- maybe define an interface
//	- BufRead: ReadRune, UnreadRune ?
//		could make ReadRune generic if we dropped UnreadRune
//	- buffered output
// 	- would like to rename to Read, Write, but breaks
//	  embedding of these: would lose the Read, Write methods.

const (
	defaultBufSize = 4096
)

var (
	EndOfFile = os.NewError("end of file");
	PhaseError = os.NewError("phase error");
	BufferFull = os.NewError("buffer full");
	InternalError = os.NewError("bufio internal error");
	BadBufSize = os.NewError("bad bufio size");
	ShortWrite = os.NewError("short write");
)

func copySlice(dst []byte, src []byte) {
	for i := 0; i < len(dst); i++ {
		dst[i] = src[i]
	}
}


// Buffered input.

type BufRead struct {
	buf []byte;
	rd io.Read;
	r, w int;
	err *os.Error;
	lastbyte int;
}

func NewBufReadSize(rd io.Read, size int) (b *BufRead, err *os.Error) {
	if size <= 0 {
		return nil, BadBufSize
	}
	b = new(BufRead);
	b.buf = make([]byte, size);
	b.rd = rd;
	b.lastbyte = -1;
	return b, nil
}

func NewBufRead(rd io.Read) *BufRead {
	b, err := NewBufReadSize(rd, defaultBufSize);
	if err != nil {
		// cannot happen - defaultBufSize is a valid size
		panic("bufio: NewBufRead: ", err.String());
	}
	return b;
}

// Read a new chunk into the buffer.
func (b *BufRead) Fill() *os.Error {
	if b.err != nil {
		return b.err
	}

	// Slide existing data to beginning.
	if b.w > b.r {
		copySlice(b.buf[0:b.w-b.r], b.buf[b.r:b.w]);
		b.w -= b.r;
	} else {
		b.w = 0
	}
	b.r = 0;

	// Read new data.
	n, e := b.rd.Read(b.buf[b.w:len(b.buf)]);
	if e != nil {
		b.err = e;
		return e
	}
	b.w += n;
	return nil
}

// Read into p.
// Returns the number of bytes read into p.
// If nn < len(p), also returns an error explaining
// why the read is short.
func (b *BufRead) Read(p []byte) (nn int, err *os.Error) {
	nn = 0;
	for len(p) > 0 {
		n := len(p);
		if b.w == b.r {
			if len(p) >= len(b.buf) {
				// Large read, empty buffer.
				// Read directly into p to avoid copy.
				n, b.err = b.rd.Read(p);
				if n > 0 {
					b.lastbyte = int(p[n-1]);
				}
				p = p[n:len(p)];
				nn += n;
				if b.err != nil {
					return nn, b.err
				}
				if n == 0 {
					return nn, EndOfFile
				}
				continue;
			}
			b.Fill();
			if b.err != nil {
				return nn, b.err
			}
			if b.w == b.r {
				return nn, EndOfFile
			}
		}
		if n > b.w - b.r {
			n = b.w - b.r
		}
		copySlice(p[0:n], b.buf[b.r:b.r+n]);
		p = p[n:len(p)];
		b.r += n;
		b.lastbyte = int(b.buf[b.r-1]);
		nn += n
	}
	return nn, nil
}

// Read a single byte.
// If no byte available, returns error.
func (b *BufRead) ReadByte() (c byte, err *os.Error) {
	if b.w == b.r {
		b.Fill();
		if b.err != nil {
			return 0, b.err
		}
		if b.w == b.r {
			return 0, EndOfFile
		}
	}
	c = b.buf[b.r];
	b.r++;
	b.lastbyte = int(c);
	return c, nil
}

// Unread the last byte.  Only guaranteed to be able to unread one byte.
func (b *BufRead) UnreadByte() *os.Error {
	if b.err != nil {
		return b.err
	}
	if b.r == b.w && b.lastbyte >= 0 {
		b.w = 1;
		b.r = 0;
		b.buf[0] = byte(b.lastbyte);
		b.lastbyte = -1;
		return nil;
	}
	if b.r <= 0 {
		return PhaseError
	}
	b.r--;
	b.lastbyte = -1;
	return nil
}

// Read a single Unicode character; returns the rune and its size.
func (b *BufRead) ReadRune() (rune int, size int, err *os.Error) {
	for b.r + utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) {
		n := b.w - b.r;
		b.Fill();
		if b.err != nil {
			return 0, 0, b.err
		}
		if b.w - b.r == n {
			// no bytes read
			if b.r == b.w {
				return 0, 0, EndOfFile
			}
			break;
		}
	}
	rune, size = int(b.buf[b.r]), 1;
	if rune >= 0x80 {
		rune, size = utf8.DecodeRune(b.buf[b.r:b.w]);
	}
	b.r += size;
	b.lastbyte = int(b.buf[b.r-1]);
	return rune, size, nil
}

// Helper function: look for byte c in array p,
// returning its index or -1.
func findByte(p []byte, c byte) int {
	for i := 0; i < len(p); i++ {
		if p[i] == c {
			return i
		}
	}
	return -1
}

// Returns the number of bytes that can be read.
func (b *BufRead) Buffered() int {
	return b.w - b.r;
}

// Read until the first occurrence of delim in the input,
// returning a slice pointing at the bytes in the buffer.
// The bytes stop being valid at the next read call.
// Fails if the line doesn't fit in the buffer.
// For internal (or advanced) use only.
// Use ReadLineString or ReadLineBytes instead.

func (b *BufRead) ReadLineSlice(delim byte) (line []byte, err *os.Error) {
	if b.err != nil {
		return nil, b.err
	}

	// Look in buffer.
	if i := findByte(b.buf[b.r:b.w], delim); i >= 0 {
		line1 := b.buf[b.r:b.r+i+1];
		b.r += i+1;
		return line1, nil
	}

	// Read more into buffer, until buffer fills or we find delim.
	for {
		n := b.Buffered();
		b.Fill();
		if b.err != nil {
			return nil, b.err
		}
		if b.Buffered() == n {	// no data added; end of file
			line := b.buf[b.r:b.w];
			b.r = b.w;
			return line, EndOfFile
		}

		// Search new part of buffer
		if i := findByte(b.buf[n:b.w], delim); i >= 0 {
			line := b.buf[0:n+i+1];
			b.r = n+i+1;
			return line, nil
		}

		// Buffer is full?
		if b.Buffered() >= len(b.buf) {
			return nil, BufferFull
		}
	}

	// BUG 6g bug100
	return nil, nil
}

// Read until the first occurrence of delim in the input,
// returning a new byte array containing the line.
// If an error happens, returns the data (without a delimiter)
// and the error.  (Can't leave the data in the buffer because
// we might have read more than the buffer size.)
func (b *BufRead) ReadLineBytes(delim byte) (line []byte, err *os.Error) {
	if b.err != nil {
		return nil, b.err
	}

	// Use ReadLineSlice to look for array,
	// accumulating full buffers.
	var frag []byte;
	var full [][]byte;
	nfull := 0;
	err = nil;

	for {
		var e *os.Error;
		frag, e = b.ReadLineSlice(delim);
		if e == nil {	// got final fragment
			break
		}
		if e != BufferFull {	// unexpected error
			err = e;
			break
		}

		// Read bytes out of buffer.
		buf := make([]byte, b.Buffered());
		var n int;
		n, e = b.Read(buf);
		if e != nil {
			frag = buf[0:n];
			err = e;
			break
		}
		if n != len(buf) {
			frag = buf[0:n];
			err = InternalError;
			break
		}

		// Grow list if needed.
		if full == nil {
			full = make([][]byte, 16);
		} else if nfull >= len(full) {
			newfull := make([][]byte, len(full)*2);
			// BUG slice assignment
			for i := 0; i < len(full); i++ {
				newfull[i] = full[i];
			}
			full = newfull
		}

		// Save buffer
		full[nfull] = buf;
		nfull++;
	}

	// Allocate new buffer to hold the full pieces and the fragment.
	n := 0;
	for i := 0; i < nfull; i++ {
		n += len(full[i])
	}
	n += len(frag);

	// Copy full pieces and fragment in.
	buf := make([]byte, n);
	n = 0;
	for i := 0; i < nfull; i++ {
		copySlice(buf[n:n+len(full[i])], full[i]);
		n += len(full[i])
	}
	copySlice(buf[n:n+len(frag)], frag);
	return buf, err
}

// Read until the first occurrence of delim in the input,
// returning a new string containing the line.
// If savedelim, keep delim in the result; otherwise chop it off.
func (b *BufRead) ReadLineString(delim byte, savedelim bool) (line string, err *os.Error) {
	bytes, e := b.ReadLineBytes(delim);
	if e != nil {
		return string(bytes), e
	}
	if !savedelim {
		bytes = bytes[0:len(bytes)-1]
	}
	return string(bytes), nil
}


// buffered output

type BufWrite struct {
	err *os.Error;
	buf []byte;
	n int;
	wr io.Write;
}

func NewBufWriteSize(wr io.Write, size int) (b *BufWrite, err *os.Error) {
	if size <= 0 {
		return nil, BadBufSize
	}
	b = new(BufWrite);
	b.buf = make([]byte, size);
	b.wr = wr;
	return b, nil
}

func NewBufWrite(wr io.Write) *BufWrite {
	b, err := NewBufWriteSize(wr, defaultBufSize);
	if err != nil {
		// cannot happen - defaultBufSize is valid size
		panic("bufio: NewBufWrite: ", err.String());
	}
	return b;
}

// Flush the output buffer.
func (b *BufWrite) Flush() *os.Error {
	if b.err != nil {
		return b.err
	}
	n := 0;
	for n < b.n {
		m, e := b.wr.Write(b.buf[n:b.n]);
		n += m;
		if m == 0 && e == nil {
			e = ShortWrite
		}
		if e != nil {
			if n < b.n {
				copySlice(b.buf[0:b.n-n], b.buf[n:b.n])
			}
			b.n -= n;
			b.err = e;
			return e
		}
	}
	b.n = 0;
	return nil
}

func (b *BufWrite) Available() int {
	return len(b.buf) - b.n
}

func (b *BufWrite) Buffered() int {
	return b.n
}

func (b *BufWrite) Write(p []byte) (nn int, err *os.Error) {
	if b.err != nil {
		return 0, b.err
	}
	nn = 0;
	for len(p) > 0 {
		n := b.Available();
		if n <= 0 {
			if b.Flush(); b.err != nil {
				break
			}
			n = b.Available()
		}
		if b.Available() == 0 && len(p) >= len(b.buf) {
			// Large write, empty buffer.
			// Write directly from p to avoid copy.
			n, b.err = b.wr.Write(p);
			nn += n;
			p = p[n:len(p)];
			if b.err != nil {
				break;
			}
			continue;
		}
		if n > len(p) {
			n = len(p)
		}
		copySlice(b.buf[b.n:b.n+n], p[0:n]);
		b.n += n;
		nn += n;
		p = p[n:len(p)]
	}
	return nn, b.err
}

func (b *BufWrite) WriteByte(c byte) *os.Error {
	if b.err != nil {
		return b.err
	}
	if b.Available() <= 0 && b.Flush() != nil {
		return b.err
	}
	b.buf[b.n] = c;
	b.n++;
	return nil
}

// buffered input and output

type BufReadWrite struct {
	*BufRead;
	*BufWrite;
}

func NewBufReadWrite(r *BufRead, w *BufWrite) *BufReadWrite {
	return &BufReadWrite(r, w)
}