mirror of https://github.com/dirtbags/fluffy.git
GapstrReader for encodings/binary
This commit is contained in:
parent
44d3c5dc6b
commit
262462af53
|
@ -143,3 +143,25 @@ func (g *Gapstr) Slice(beg, end int) *Gapstr {
|
|||
|
||||
return &Gapstr{chunks}
|
||||
}
|
||||
|
||||
type GapstrReader struct {
|
||||
g *Gapstr
|
||||
pos int
|
||||
GapRead bool
|
||||
}
|
||||
|
||||
func NewGapstrReader(g *Gapstr) (*GapstrReader) {
|
||||
return &GapstrReader{g, 0, false}
|
||||
}
|
||||
|
||||
func (gr *GapstrReader) Read(p []byte) (n int, err error) {
|
||||
gs := gr.g.Slice(gr.pos, gr.pos + len(p))
|
||||
if gs.HasGaps() {
|
||||
gr.GapRead = true
|
||||
}
|
||||
|
||||
s := []byte(gs.String())
|
||||
nread := copy(p, s)
|
||||
gr.pos += nread
|
||||
return nread, nil
|
||||
}
|
|
@ -1,12 +1,21 @@
|
|||
package netarch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func DUMP(a ...interface{}) {
|
||||
_, file, line, _ := runtime.Caller(1)
|
||||
fmt.Printf("%s:%d ", file, line)
|
||||
fmt.Println(a...)
|
||||
}
|
||||
|
||||
func AssertEqual(t *testing.T, a, b interface{}) {
|
||||
_, file, line, _ := runtime.Caller(1)
|
||||
if a != b {
|
||||
t.Errorf("Not equal: %#v, %#v", a, b)
|
||||
t.Errorf("%s:%d Not equal: %#v, %#v", file, line, a, b)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -41,3 +50,26 @@ func TestGapstr(t *testing.T) {
|
|||
|
||||
AssertEqual(t, g.Slice(0, 12).String(), gs[0:12])
|
||||
}
|
||||
|
||||
func TestGapstrReader(t *testing.T) {
|
||||
g := new(Gapstr)
|
||||
g = g.AppendString("\xff\xff")
|
||||
g = g.AppendGap(8)
|
||||
g = g.AppendString("\xff\xff\xff")
|
||||
|
||||
gs := g.String()
|
||||
|
||||
gr := NewGapstrReader(g)
|
||||
|
||||
b := make([]byte, 4)
|
||||
for i := 0; i < 4; i += 1 {
|
||||
beg := i*4
|
||||
end := min((i+1) * 4, len(gs))
|
||||
truth := gs[beg:end]
|
||||
nread, err := gr.Read(b)
|
||||
|
||||
AssertEqual(t, nread, len(truth))
|
||||
AssertEqual(t, err, nil)
|
||||
AssertEqual(t, string(b[:nread]), truth)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue