~rbn/neinp

ref: 062a107b140085acd6c48867e4328fb3f3466a87 neinp/stat/reader.go -rw-r--r-- 1.2 KiB
062a107bRuben Schuller use custom go.rbn.im import path 1 year, 2 months ago
                                                                                
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
package stat // import "go.rbn.im/neinp/stat"

import (
	"bytes"
	"fmt"
	"io"
)

/*Reader is a reader for multiple Stats, aka directories.*/
type Reader struct {
	stats   []Stat
	pos     int
	bytepos int64
}

/*NewReader returns a new Reader initialized with stats and ready for reading.*/
func NewReader(stats ...Stat) *Reader {
	return &Reader{stats: stats}
}

func (s *Reader) Read(p []byte) (int, error) {
	var outbuf bytes.Buffer
	var buf bytes.Buffer
	npos := s.pos

	if s.pos == len(s.stats) || len(s.stats) == 0 {
		return 0, io.EOF
	}

	for _, stat := range s.stats[s.pos:] {
		_, err := stat.Encode(&buf)
		if err != nil {
			return 0, err
		}

		if buf.Len()+outbuf.Len() > len(p) {
			break
		}

		_, err = buf.WriteTo(&outbuf)
		if err != nil {
			return 0, err
		}

		npos++
	}

	n := copy(p, outbuf.Bytes())

	s.bytepos += int64(n)
	s.pos = npos

	return n, nil
}

//Seek interface implementation.
func (s *Reader) Seek(offset int64, whence int) (int64, error) {
	if whence != io.SeekStart {
		return s.bytepos, fmt.Errorf("Unsupported whence %v", whence)
	}

	switch offset {
	case 0:
		s.pos = 0
		s.bytepos = 0
	case s.bytepos:
	default:
		return s.bytepos, fmt.Errorf("can't seek there")
	}

	return s.bytepos, nil
}