From 262462af5333eaa934d1db637ae9269877fa4b6c Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Wed, 20 Aug 2014 17:07:09 -0600 Subject: [PATCH] GapstrReader for encodings/binary --- src/netarch/gapstr.go | 22 ++++++++++++++++++++++ src/netarch/gapstr_test.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/netarch/gapstr.go b/src/netarch/gapstr.go index f2f1d17..f992dcf 100644 --- a/src/netarch/gapstr.go +++ b/src/netarch/gapstr.go @@ -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 +} \ No newline at end of file diff --git a/src/netarch/gapstr_test.go b/src/netarch/gapstr_test.go index feb422f..c7eed50 100644 --- a/src/netarch/gapstr_test.go +++ b/src/netarch/gapstr_test.go @@ -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) + } +} \ No newline at end of file