Skip to content

feat: RESP2/RESP3 parser (zero-alloc) #132

@FumingPower3925

Description

@FumingPower3925

Summary

Implement a zero-allocation RESP2/RESP3 protocol parser for the Redis driver. This is the foundation for all Redis communication.

Design

Package: driver/redis/protocol/resp.go

RESP2 Types

Prefix Type Example
+ Simple String +OK\r\n
- Error -ERR unknown command\r\n
: Integer :1000\r\n
$ Bulk String $5\r\nhello\r\n
* Array *2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n

RESP3 Additional Types

Prefix Type Example
_ Null _\r\n
# Boolean #t\r\n
, Double ,3.14\r\n
( Big Number (123456789\r\n
! Blob Error !21\r\nSYNTAX invalid\r\n
= Verbatim String =15\r\ntxt:Some string\r\n
~ Set ~2\r\n+a\r\n+b\r\n
% Map %2\r\n+key1\r\n:1\r\n+key2\r\n:2\r\n
| Attribute (metadata prefix)
> Push >3\r\n+message\r\n+channel\r\n$5\r\nhello\r\n

Parser

type Reader struct {
    buf  []byte
    pos  int
}

type Value struct {
    Type    byte      // prefix byte
    Str     []byte    // for string/bulk string/error (slice of buf, no alloc)
    Int     int64     // for integer
    Float   float64   // for double
    Bool    bool      // for boolean
    Array   []Value   // for array/set/push
    Map     []KV      // for map
    IsNull  bool
}

type KV struct {
    Key   Value
    Value Value
}

func (r *Reader) Feed(data []byte)
func (r *Reader) Next() (Value, error)  // returns ErrIncomplete if partial
func (r *Reader) Reset()

Zero-Alloc Strategy

  • Value.Str is a slice into Reader.buf (no copy)
  • Value.Array uses a pre-allocated slice pool
  • Integer parsing without strconv.Atoi (inline digit loop)
  • No interface{} boxing — typed fields on Value struct

Command Serialization

type Writer struct {
    buf []byte
}

func (w *Writer) WriteCommand(args ...string) []byte
func (w *Writer) WriteBulkString(s string)
func (w *Writer) WriteArray(n int)
func (w *Writer) Reset()

Serializes as RESP2 array of bulk strings (universal command format).

Acceptance Criteria

  • RESP2 parser handles all 5 types correctly
  • RESP3 parser handles all additional types
  • Nested arrays/maps parsed correctly
  • NULL bulk string and NULL array handled
  • Partial message returns ErrIncomplete (resumable)
  • Zero allocations on parse hot path (benchmark verified)
  • Command serialization produces valid RESP
  • Fuzz tests for parser robustness
  • Benchmark: parse throughput (MB/s) and allocs/op

Dependencies

None — standalone protocol implementation.

Metadata

Metadata

Labels

area/driverDatabase/cache driver infrastructuredriver/redisRedis driver

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions