Debian Codegraph @

mem.go

raw symbols SCIP
1 package buffer
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8
9 "github.com/djherbis/buffer/limio"
10 )
11
12 type memory struct {
13 N int64
14 *bytes.Buffer
15 }
16
17 // New returns a new in memory BufferAt with max size N.
18 // It's backed by a bytes.Buffer.
19 func New(n int64) BufferAt {
20 return &memory{
21 N: n,
22 Buffer: bytes.NewBuffer(nil),
23 }
24 }
25
26 func (buf *memory) Cap() int64 {
27 return buf.N
28 }
29
30 func (buf *memory) Len() int64 {
31 return int64(buf.Buffer.Len())
32 }
33
34 func (buf *memory) Write(p []byte) (n int, err error) {
35 return limio.LimitWriter(buf.Buffer, Gap(buf)).Write(p)
36 }
37
38 func (buf *memory) WriteAt(p []byte, off int64) (n int, err error) {
39 if off > buf.Len() {
40 return 0, io.ErrShortWrite
41 } else if len64(p)+off <= buf.Len() {
42 d := buf.Bytes()[off:]
43 return copy(d, p), nil
44 } else {
45 d := buf.Bytes()[off:]
46 n = copy(d, p)
47 m, err := buf.Write(p[n:])
48 return n + m, err
49 }
50 }
51
52 func (buf *memory) ReadAt(p []byte, off int64) (n int, err error) {
53 return bytes.NewReader(buf.Bytes()).ReadAt(p, off)
54 }
55
56 func (buf *memory) Read(p []byte) (n int, err error) {
57 return io.LimitReader(buf.Buffer, buf.Len()).Read(p)
58 }
59
60 func (buf *memory) ReadFrom(r io.Reader) (n int64, err error) {
61 return buf.Buffer.ReadFrom(io.LimitReader(r, Gap(buf)))
62 }
63
64 func init() {
65 gob.Register(&memory{})
66 }
67
68 func (buf *memory) MarshalBinary() ([]byte, error) {
69 var b bytes.Buffer
70 fmt.Fprintln(&b, buf.N)
71 b.Write(buf.Bytes())
72 return b.Bytes(), nil
73 }
74
75 func (buf *memory) UnmarshalBinary(bindata []byte) error {
76 data := make([]byte, len(bindata))
77 copy(data, bindata)
78 b := bytes.NewBuffer(data)
79 _, err := fmt.Fscanln(b, &buf.N)
80 buf.Buffer = bytes.NewBuffer(b.Bytes())
81 return err
82 }