File: slice_buffer.go

package info (click to toggle)
golang-github-cupcake-rdb 0.0~git20161107.0.43ba341-12
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 460 kB
  • sloc: makefile: 4
file content (67 lines) | stat: -rw-r--r-- 1,057 bytes parent folder | download | duplicates (3)
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
package rdb

import (
	"errors"
	"io"
)

type sliceBuffer struct {
	s []byte
	i int
}

func newSliceBuffer(s []byte) *sliceBuffer {
	return &sliceBuffer{s, 0}
}

func (s *sliceBuffer) Slice(n int) ([]byte, error) {
	if s.i+n > len(s.s) {
		return nil, io.EOF
	}
	b := s.s[s.i : s.i+n]
	s.i += n
	return b, nil
}

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

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

func (s *sliceBuffer) Seek(offset int64, whence int) (int64, error) {
	var abs int64
	switch whence {
	case 0:
		abs = offset
	case 1:
		abs = int64(s.i) + offset
	case 2:
		abs = int64(len(s.s)) + offset
	default:
		return 0, errors.New("invalid whence")
	}
	if abs < 0 {
		return 0, errors.New("negative position")
	}
	if abs >= 1<<31 {
		return 0, errors.New("position out of range")
	}
	s.i = int(abs)
	return abs, nil
}