Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit 262179b

Browse files
committedApr 22, 2019
utils: binary reader, add ReadUntilFromBufioReader()
Signed-off-by: Arran Walker <[email protected]>
1 parent 5598068 commit 262179b

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed
 

‎utils/binary/read.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,7 @@ func Read(r io.Reader, data ...interface{}) error {
2626
// ReadUntil reads from r untin delim is found
2727
func ReadUntil(r io.Reader, delim byte) ([]byte, error) {
2828
if bufr, ok := r.(*bufio.Reader); ok {
29-
value, err := bufr.ReadBytes(delim)
30-
if err != nil || len(value) == 0 {
31-
return nil, err
32-
}
33-
34-
return value[:len(value)-1], nil
29+
return ReadUntilFromBufioReader(bufr, delim)
3530
}
3631

3732
var buf [1]byte
@@ -53,6 +48,17 @@ func ReadUntil(r io.Reader, delim byte) ([]byte, error) {
5348
}
5449
}
5550

51+
// ReadUntilFromBufioReader is like bufio.ReadBytes but drops the delimiter
52+
// from the result.
53+
func ReadUntilFromBufioReader(r *bufio.Reader, delim byte) ([]byte, error) {
54+
value, err := r.ReadBytes(delim)
55+
if err != nil || len(value) == 0 {
56+
return nil, err
57+
}
58+
59+
return value[:len(value)-1], nil
60+
}
61+
5662
// ReadVariableWidthInt reads and returns an int in Git VLQ special format:
5763
//
5864
// Ordinary VLQ has some redundancies, example: the number 358 can be

‎utils/binary/read_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package binary
22

33
import (
4+
"bufio"
45
"bytes"
56
"encoding/binary"
67
"testing"
@@ -39,6 +40,15 @@ func (s *BinarySuite) TestReadUntil(c *C) {
3940
c.Assert(string(b), Equals, "foo")
4041
}
4142

43+
func (s *BinarySuite) TestReadUntilFromBufioReader(c *C) {
44+
buf := bufio.NewReader(bytes.NewBuffer([]byte("foo bar")))
45+
46+
b, err := ReadUntilFromBufioReader(buf, ' ')
47+
c.Assert(err, IsNil)
48+
c.Assert(b, HasLen, 3)
49+
c.Assert(string(b), Equals, "foo")
50+
}
51+
4252
func (s *BinarySuite) TestReadVariableWidthInt(c *C) {
4353
buf := bytes.NewBuffer([]byte{129, 110})
4454

0 commit comments

Comments
 (0)