From 2377ea60785297aa898ffd80a3fab6ec427b441d Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Mon, 4 Aug 2014 21:36:48 +0000 Subject: [PATCH] read bulkstrings --- values.go | 22 ++++++++++++++++++++-- values_test.go | 5 +++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/values.go b/values.go index 795e8b7..8664e1c 100644 --- a/values.go +++ b/values.go @@ -48,7 +48,7 @@ func readValue(r io.Reader) (value, error) { case start_integer: return readInteger(line[1:]) case start_bulkstring: - return readBulkString(line[1:], r) + return readBulkString(line[1:], br) default: return nil, fmt.Errorf("unable to read redis protocol value: illegal start character: %c", line[0]) } @@ -87,5 +87,23 @@ func readInteger(b []byte) (value, error) { type BulkString string func readBulkString(prefix []byte, r io.Reader) (value, error) { - return nil, nil + n, err := strconv.ParseInt(string(prefix), 10, 64) + if err != nil { + return nil, fmt.Errorf("unable to read bulkstring in redis protocol: bad prefix: %v", err) + } + + b := make([]byte, n) + n_read, err := r.Read(b) + switch err { + case io.EOF, nil: + break + default: + return nil, fmt.Errorf("unable to read bulkstring in redis protocol: error on read: %v", err) + } + + if int64(n_read) != n { + return nil, fmt.Errorf("unable to read bulkstring in redis protocol: read %d bytes, expected to read %d bytes", int64(n_read), n) + } + + return BulkString(b), nil } diff --git a/values_test.go b/values_test.go index 03bf125..777f550 100644 --- a/values_test.go +++ b/values_test.go @@ -31,6 +31,11 @@ var valueTests = []valueTest{ {"-one two ", Error("one two ")}, // trailing space {"- one two", Error(" one two")}, // leading space + {"$0\r\n\r\n", BulkString("")}, // is this even a thing? + {"$1\r\nx\r\n", BulkString("x")}, + {"$4\r\netsy\r\n", BulkString("etsy")}, + {"$12\r\nSaskatchewan\r\n", BulkString("Saskatchewan")}, + {":0", Integer(0)}, {":1", Integer(1)}, {":-1", Integer(-1)},