summaryrefslogtreecommitdiff
path: root/vendor/github.com/go-pg/pg/v10/internal/pool/reader_bytes.go
blob: 93646b1da0de163e3da6a9e8b5d78032fbc53c60 (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
// Copyright 2012 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 pool

import (
	"bytes"
	"errors"
	"io"
)

type BytesReader struct {
	s []byte
	i int
}

func NewBytesReader(b []byte) *BytesReader {
	return &BytesReader{
		s: b,
	}
}

func (r *BytesReader) Reset(b []byte) {
	r.s = b
	r.i = 0
}

func (r *BytesReader) Buffered() int {
	return len(r.s) - r.i
}

func (r *BytesReader) Bytes() []byte {
	return r.s[r.i:]
}

func (r *BytesReader) Read(b []byte) (n int, err error) {
	if r.i >= len(r.s) {
		return 0, io.EOF
	}
	n = copy(b, r.s[r.i:])
	r.i += n
	return
}

func (r *BytesReader) ReadByte() (byte, error) {
	if r.i >= len(r.s) {
		return 0, io.EOF
	}
	b := r.s[r.i]
	r.i++
	return b, nil
}

func (r *BytesReader) UnreadByte() error {
	if r.i <= 0 {
		return errors.New("UnreadByte: at beginning of slice")
	}
	r.i--
	return nil
}

func (r *BytesReader) ReadSlice(delim byte) ([]byte, error) {
	if i := bytes.IndexByte(r.s[r.i:], delim); i >= 0 {
		i++
		line := r.s[r.i : r.i+i]
		r.i += i
		return line, nil
	}

	line := r.s[r.i:]
	r.i = len(r.s)
	return line, io.EOF
}

func (r *BytesReader) ReadBytes(fn func(byte) bool) ([]byte, error) {
	for i, c := range r.s[r.i:] {
		if !fn(c) {
			i++
			line := r.s[r.i : r.i+i]
			r.i += i
			return line, nil
		}
	}

	line := r.s[r.i:]
	r.i = len(r.s)
	return line, io.EOF
}

func (r *BytesReader) Discard(n int) (int, error) {
	b, err := r.ReadN(n)
	return len(b), err
}

func (r *BytesReader) ReadN(n int) ([]byte, error) {
	nn := n
	if nn > len(r.s) {
		nn = len(r.s)
	}

	b := r.s[r.i : r.i+nn]
	r.i += nn
	if n > nn {
		return b, io.EOF
	}
	return b, nil
}

func (r *BytesReader) ReadFull() ([]byte, error) {
	b := make([]byte, len(r.s)-r.i)
	copy(b, r.s[r.i:])
	r.i = len(r.s)
	return b, nil
}

func (r *BytesReader) ReadFullTemp() ([]byte, error) {
	b := r.s[r.i:]
	r.i = len(r.s)
	return b, nil
}