package protoimport ()// DefaultBufferSize is the default size for read/write buffers (32 KiB).constDefaultBufferSize = 32 * 1024// redis resp protocol data type.const (RespStatus = '+'// +<string>\r\nRespError = '-'// -<string>\r\nRespString = '$'// $<length>\r\n<bytes>\r\nRespInt = ':'// :<number>\r\nRespNil = '_'// _\r\nRespFloat = ','// ,<floating-point-number>\r\n (golang float)RespBool = '#'// true: #t\r\n false: #f\r\nRespBlobError = '!'// !<length>\r\n<bytes>\r\nRespVerbatim = '='// =<length>\r\nFORMAT:<bytes>\r\nRespBigInt = '('// (<big number>\r\nRespArray = '*'// *<len>\r\n... (same as resp2)RespMap = '%'// %<len>\r\n(key)\r\n(value)\r\n... (golang map)RespSet = '~'// ~<len>\r\n... (same as Array)RespAttr = '|'// |<len>\r\n(key)\r\n(value)\r\n... + command replyRespPush = '>'// ><len>\r\n... (same as Array))// Not used temporarily.// Redis has not used these two data types for the time being, and will implement them later.// Streamed = "EOF:"// StreamedAggregated = '?'//------------------------------------------------------------------------------constNil = RedisError("redis: nil") // nolint:errnametypeRedisErrorstringfunc ( RedisError) () string { returnstring() }func (RedisError) () {}func ( []byte) error { := string([1:])returnparseTypedRedisError()}//------------------------------------------------------------------------------typeReaderstruct { rd *bufio.Reader}func ( io.Reader) *Reader {return &Reader{rd: bufio.NewReaderSize(, DefaultBufferSize), }}func ( io.Reader, int) *Reader {return &Reader{rd: bufio.NewReaderSize(, ), }}func ( *Reader) () int {return .rd.Buffered()}// Size returns the size of the underlying read buffer.func ( *Reader) () int {return .rd.Size()}func ( *Reader) ( int) ([]byte, error) {return .rd.Peek()}func ( *Reader) ( io.Reader) { .rd.Reset()}// PeekReplyType returns the data type of the next response without advancing the Reader,// and discard the attribute type.func ( *Reader) () (byte, error) { , := .rd.Peek(1)if != nil {return0, }if [0] == RespAttr {if = .DiscardNext(); != nil {return0, }return .() }return [0], nil}// MinRESP3ReadBufferSize is the minimum buffer size used when RESP3 push// notifications must be inspected without consuming them.constMinRESP3ReadBufferSize = 128// ErrPushNotificationNameTooLong is returned when the push header does not fit// in the bounded peek window. Callers should consume the frame with ReadReply.varErrPushNotificationNameTooLong = errors.New("redis: push notification name exceeds peek window")// PeekPushNotificationName returns the notification name of the next RESP3// push frame without consuming it. The caller is expected to have already// verified that the next reply is a push notification (e.g. via PeekReplyType// returning RespPush).//// To identify the name the method may block reading more bytes from the// underlying connection, but only ever waits for one byte beyond the valid// frame prefix it has already seen. That byte is guaranteed to arrive: an// incomplete prefix means the server is still committed to sending the rest// of the frame. Demanding any fixed amount instead can deadlock — a complete// frame such as a subscribe confirmation for a short channel name can be// smaller than the fixed window, and once it is buffered the server has// nothing more to send (issue #3935). Blocking for in-flight bytes is// preferred to a truncated peek, which would silently misidentify the// notification and cause the caller's ReadReply to consume (and drop) the// frame; see issue #3839.func ( *Reader) () (string, error) { , := .rd.Peek(1)if != nil {return"", }if [0] != RespPush {return"", fmt.Errorf("redis: can't peek push notification name, next reply is not a push notification") }const = 4096for {// Parse from what is already buffered; this never blocks. := .rd.Buffered()if > { = } , := .rd.Peek()if != nil {return"", } , , := parsePushNotificationName()if != nil {return"", }if {return , nil }if >= {return"", ErrPushNotificationNameTooLong }// Valid but incomplete prefix: the rest of the frame is in flight. // Block for exactly one more byte — the read that delivers it picks // up whatever else has already arrived — then re-parse.if , := .rd.Peek( + 1); != nil {iferrors.Is(, bufio.ErrBufferFull) {return"", ErrPushNotificationNameTooLong }return"", } }}// parsePushNotificationName extracts the notification name from a buffered// RESP3 push frame prefix. The three return values are://// - (name, true, nil): the full name is in buf.// - ("", false, nil): buf is a valid prefix but too short to determine the// name; the caller should fetch more bytes and retry.// - ("", _, err): buf is malformed.//// This split lets PeekPushNotificationName tell "incomplete header" apart// from "corrupt frame" without ever returning a truncated string.func parsePushNotificationName( []byte) (string, bool, error) {// Need at least ">N\r" before any meaningful work.iflen() < 3 {return"", false, nil }if [0] != RespPush {return"", false, fmt.Errorf("redis: can't parse push notification: %q", ) }// Skip the array length line ">N\r\n".const = 1// first byte after the '>' marker , , := skipDigitsThenCRLF(, )if != nil {return"", false, fmt.Errorf("redis: can't parse push notification: %w", ) }if ! {return"", false, nil }// Reject ">\r\n": RESP requires at least one digit for the array length. // Without this check the empty length looks like a valid prefix and the // caller would block fetching more bytes for a frame that is already // malformed.if -2 == {return"", false, fmt.Errorf("redis: empty push notification array length") }// First element type byte: '$' (bulk) or '+' (simple-string).if >= len() {return"", false, nil } := []if != RespString && != RespStatus {return"", false, fmt.Errorf("redis: can't parse push notification name: %q", [:]) } ++if == RespString {// Read "$M\r\n" then the M-byte name. := , , := skipDigitsThenCRLF(, )if != nil {return"", false, fmt.Errorf("redis: can't parse push notification name length: %w", ) }if ! {return"", false, nil }if -2 == {return"", false, fmt.Errorf("redis: empty push notification name length") } , := util.Atoi([ : -2])if != nil {return"", false, fmt.Errorf("redis: invalid push notification name length %q: %w", [:-2], ) }if < 0 {return"", false, fmt.Errorf("redis: negative push notification name length: %d", ) }// Compare against the remaining bytes instead of computing // next+nameLen: a hugely advertised length on malformed input could // overflow int, wrap negative, slip past an "end > len(buf)" guard and // panic the slice below. next <= len(buf) here, so the subtraction is // safe.if > len()- {return"", false, nil }returnutil.BytesToString([ : +]), true, nil }// RespStatus: scan for the terminating CRLF.for := ; < len()-1; ++ {if [] == '\r' && [+1] == '\n' {returnutil.BytesToString([:]), true, nil } }return"", false, nil}// skipDigitsThenCRLF advances past zero-or-more ASCII digits and the// terminating "\r\n" starting at offset start in buf. It returns the position// after the "\r\n" and true on success; (pos, false, nil) if buf is too// short; or an error if a non-digit non-CR byte is encountered before the CRLF.func skipDigitsThenCRLF( []byte, int) (int, bool, error) {for := ; < len()-1; ++ {if [] == '\r' && [+1] == '\n' {return + 2, true, nil }if [] < '0' || [] > '9' {return , false, fmt.Errorf("expected digit or CRLF, got %q", []) } }returnlen(), false, nil}// ReadLine Return a valid reply, it will check the protocol or redis error,// and discard the attribute type.func ( *Reader) () ([]byte, error) { , := .readLine()if != nil {returnnil, }switch [0] {caseRespError:returnnil, ParseErrorReply()caseRespNil:returnnil, NilcaseRespBlobError:varstring , = .readStringReply()if == nil { = parseTypedRedisError() }returnnil, caseRespAttr:if = .Discard(); != nil {returnnil, }return .() }// Compatible with RESP2ifIsNilReply() {returnnil, Nil }return , nil}// readLine returns an error if:// - there is a pending read error;// - or line does not end with \r\n.func ( *Reader) () ([]byte, error) { , := .rd.ReadSlice('\n')if != nil {if != bufio.ErrBufferFull {returnnil, } := make([]byte, len())copy(, ) , = .rd.ReadBytes('\n')if != nil {returnnil, } = append(, ...) //nolint:makezero = }iflen() <= 2 || [len()-1] != '\n' || [len()-2] != '\r' {returnnil, fmt.Errorf("redis: invalid reply: %q", ) }return [:len()-2], nil}func ( *Reader) () (interface{}, error) { , := .ReadLine()if != nil {returnnil, }switch [0] {caseRespStatus:returnstring([1:]), nilcaseRespInt:returnutil.ParseInt([1:], 10, 64)caseRespFloat:return .readFloat()caseRespBool:return .readBool()caseRespBigInt:return .readBigInt()caseRespString:return .readStringReply()caseRespVerbatim:return .readVerb()caseRespArray, RespSet, RespPush:return .readSlice()caseRespMap:return .readMap() }returnnil, fmt.Errorf("redis: can't parse %.100q", )}func ( *Reader) ( []byte) (float64, error) { := util.BytesToString([1:])switch {case"inf":returnmath.Inf(1), nilcase"-inf":returnmath.Inf(-1), nilcase"nan", "-nan":returnmath.NaN(), nil }returnstrconv.ParseFloat(, 64)}func ( *Reader) ( []byte) (bool, error) {switchutil.BytesToString([1:]) {case"t":returntrue, nilcase"f":returnfalse, nil }returnfalse, fmt.Errorf("redis: can't parse bool reply: %q", )}func ( *Reader) ( []byte) (*big.Int, error) { := new(big.Int)if , := .SetString(util.BytesToString([1:]), 10); {return , nil }returnnil, fmt.Errorf("redis: can't parse bigInt reply: %q", )}func ( *Reader) ( []byte) (string, error) { , := replyLen()if != nil {return"", } := make([]byte, +2) _, = io.ReadFull(.rd, )if != nil {return"", }returnutil.BytesToString([:]), nil}func ( *Reader) ( []byte) (string, error) { , := .readStringReply()if != nil {return"", }iflen() < 4 || [3] != ':' {return"", fmt.Errorf("redis: can't parse verbatim string reply: %q", ) }return [4:], nil}func ( *Reader) ( []byte) ([]interface{}, error) { , := replyLen()if != nil {returnnil, } := make([]interface{}, )for := 0; < len(); ++ { , := .ReadReply()if != nil {if == Nil { [] = nilcontinue }if , := .(RedisError); { [] = continue }returnnil, } [] = }return , nil}func ( *Reader) ( []byte) (map[interface{}]interface{}, error) { , := replyLen()if != nil {returnnil, } := make(map[interface{}]interface{}, )for := 0; < ; ++ { , := .ReadReply()if != nil {returnnil, }// Reject unhashable keys (arrays/maps) before they are used as a map // key, which would otherwise panic. This check must run before the // value is read so it also guards the Nil and RedisError paths below, // which write the key into the map and continue.switch .(type) {case []interface{}, map[interface{}]interface{}:returnnil, fmt.Errorf("redis: RESP3 map key must be a scalar type, got %T", ) } , := .ReadReply()if != nil {if == Nil { [] = nilcontinue }if , := .(RedisError); { [] = continue }returnnil, } [] = }return , nil}// -------------------------------func ( *Reader) () (int64, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespInt, RespStatus:returnutil.ParseInt([1:], 10, 64)caseRespString: , := .readStringReply()if != nil {return0, }returnstrconv.ParseInt(, 10, 64)caseRespBigInt: , := .readBigInt()if != nil {return0, }if !.IsInt64() {return0, fmt.Errorf("bigInt(%s) value out of range", .String()) }return .Int64(), nil }return0, fmt.Errorf("redis: can't parse int reply: %.100q", )}func ( *Reader) () (uint64, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespInt, RespStatus:returnutil.ParseUint([1:], 10, 64)caseRespString: , := .readStringReply()if != nil {return0, }returnstrconv.ParseUint(, 10, 64)caseRespBigInt: , := .readBigInt()if != nil {return0, }if !.IsUint64() {return0, fmt.Errorf("bigInt(%s) value out of range", .String()) }return .Uint64(), nil }return0, fmt.Errorf("redis: can't parse uint reply: %.100q", )}func ( *Reader) () (float64, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespFloat:return .readFloat()caseRespStatus:returnstrconv.ParseFloat(util.BytesToString([1:]), 64)caseRespString: , := .readStringReply()if != nil {return0, }returnstrconv.ParseFloat(, 64) }return0, fmt.Errorf("redis: can't parse float reply: %.100q", )}// ReadStringInto reads a string-typed reply directly into buf, avoiding the// per-call allocation that ReadString incurs. It returns the number of bytes// written to buf.//// Supported reply types:// - $<n>\r\n<payload>\r\n bulk string (the GET path; payload is read// straight into buf via bufio.Reader — for payloads larger than the// bufio buffer this is effectively zero-copy from the socket)// - +<status>\r\n simple string, copied from the header line// - :<int>\r\n integer, copied as its ASCII representation// - ,<float>\r\n float, copied as its ASCII representation//// Errors, nil, push notifications, and RESP3 attributes are intercepted// by ReadLine and surfaced through err. RESP3 verbatim strings// (=<n>\r\n<txt:payload>\r\n) are intentionally not handled — they are// never returned by GET-family commands, and including them re-introduces// a hazard class where the response-type byte read from a stale `line[0]`// after a bufio refill can be misinterpreted as the verbatim format tag.//// If the bulk payload does not fit in buf, an error is returned and the// payload plus the trailing CRLF are drained from the reader so the// connection stays aligned for the next reply. For simple-string / integer// / float responses the payload lives in the (already-consumed) header// line, so no drain is needed.func ( *Reader) ( []byte) (int, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespStatus:// Simple string — data is in the line itself. := [1:]iflen() > len() {return0, fmt.Errorf("redis: buffer too small: need %d bytes, have %d", len(), len()) }returncopy(, ), nilcaseRespString: , := replyLen()if != nil {return0, }if > len() {// Drain the payload + trailing \r\n so the next read on this // connection sees the start of the next reply rather than the // tail of this one. Otherwise the unread bytes corrupt the // stream and the bad connection gets handed back to the pool.if , := .rd.Discard( + 2); != nil {return0, }return0, fmt.Errorf("redis: buffer too small: need %d bytes, have %d", , len()) }// Read data directly into the user's buffer through the bufio.Reader. // bufio.Reader.Read first drains its internal buffer, then for // remaining data larger than its buffer size reads directly from the // underlying reader (socket) — effectively zero-copy. // // Fast path: when the caller VISIBLY hands over room for the trailing // CRLF too (len(buf) >= n+2), read the payload and the CRLF in a // single io.ReadFull. For large values this is one direct socket read // instead of a big read followed by a tiny separate Discard(2) read, // which is what makes GetToBuffer beat a regular Get (no payload // allocation and the same number of reads). The 2 trailing bytes land // past the returned length and are ignored. // // The gate is on len, NOT cap: a sub-slice of a larger buffer (e.g. // packed segments big[i*slot:(i+1)*slot]) exposes trailing capacity // that belongs to the caller's NEXT segment — writing the CRLF there // would silently corrupt caller-owned memory outside the slice they // passed. Callers who want the fast path pass len == payload+2 (the // returned length is still the payload length).iflen() >= +2 { := [:+2]if , := io.ReadFull(.rd, ); != nil {return0, }return , nil }// Slow path: buffer is exactly large enough for the payload only, so // read the payload into it and discard the CRLF separately.if , := io.ReadFull(.rd, [:]); != nil {return0, }if , := .rd.Discard(2); != nil {return0, }return , nilcaseRespInt, RespFloat: := [1:]iflen() > len() {return0, fmt.Errorf("redis: buffer too small: need %d bytes, have %d", len(), len()) }returncopy(, ), nil }return0, fmt.Errorf("redis: can't parse reply=%.100q reading string into buffer", )}func ( *Reader) () (string, error) { , := .ReadLine()if != nil {return"", }switch [0] {caseRespStatus, RespInt, RespFloat:returnstring([1:]), nilcaseRespString:return .readStringReply()caseRespBool: , := .readBool()returnstrconv.FormatBool(), caseRespVerbatim:return .readVerb()caseRespBigInt: , := .readBigInt()if != nil {return"", }return .String(), nil }return"", fmt.Errorf("redis: can't parse reply=%.100q reading string", )}func ( *Reader) () (bool, error) { , := .ReadString()if != nil {returnfalse, }return == "OK" || == "1" || == "true", nil}func ( *Reader) () ([]interface{}, error) { , := .ReadLine()if != nil {returnnil, }return .readSlice()}// ReadFixedArrayLen read fixed array length.func ( *Reader) ( int) error { , := .ReadArrayLen()if != nil {return }if != {returnfmt.Errorf("redis: got %d elements in the array, wanted %d", , ) }returnnil}// ReadArrayLen Read and return the length of the array.func ( *Reader) () (int, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespArray, RespSet, RespPush:returnreplyLen()default:return0, fmt.Errorf("redis: can't parse array/set/push reply: %.100q", ) }}// ReadFixedMapLen reads fixed map length.func ( *Reader) ( int) error { , := .ReadMapLen()if != nil {return }if != {returnfmt.Errorf("redis: got %d elements in the map, wanted %d", , ) }returnnil}// ReadMapLen reads the length of the map type.// If responding to the array type (RespArray/RespSet/RespPush),// it must be a multiple of 2 and return n/2.// Other types will return an error.func ( *Reader) () (int, error) { , := .ReadLine()if != nil {return0, }switch [0] {caseRespMap:returnreplyLen()caseRespArray, RespSet, RespPush:// Some commands and RESP2 protocol may respond to array types. , := replyLen()if != nil {return0, }if %2 != 0 {return0, fmt.Errorf("redis: the length of the array must be a multiple of 2, got: %d", ) }return / 2, nildefault:return0, fmt.Errorf("redis: can't parse map reply: %.100q", ) }}// DiscardNext read and discard the data represented by the next line.func ( *Reader) () error { , := .readLine()if != nil {return }return .Discard()}// Discard the data represented by line.func ( *Reader) ( []byte) ( error) {iflen() == 0 {returnerrors.New("redis: invalid line") }switch [0] {caseRespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:returnnil } , := replyLen()if != nil {if == Nil {// A nil reply ($-1, =-1, !-1, *-1, %-1) carries no payload; the // header line was already consumed by readLine, so there is // nothing to discard. Falling through would Discard(n+2)==2 bytes // that belong to the next reply and desync the stream, matching // how readRawReplyBuf/readRawReplyWriteTo already treat Nil.returnnil }return }switch [0] {caseRespBlobError, RespString, RespVerbatim:// +\r\n _, = .rd.Discard( + 2)returncaseRespArray, RespSet, RespPush:for := 0; < ; ++ {if = .DiscardNext(); != nil {return } }returnnilcaseRespMap, RespAttr:// Iterate over the n key/value pairs rather than n*2 elements: a count // above MaxInt/2 makes n*2 overflow to a negative loop bound, which // would skip the body entirely and return nil, leaving the map bytes in // the stream for the next reply to consume (a silent desync).for := 0; < ; ++ {if = .DiscardNext(); != nil {return }if = .DiscardNext(); != nil {return } }returnnil }returnfmt.Errorf("redis: can't parse %.100q", )}func replyLen( []byte) ( int, error) { , = util.Atoi([1:])if != nil {return0, }if < -1 {return0, fmt.Errorf("redis: invalid reply: %q", ) }switch [0] {caseRespString, RespVerbatim, RespBlobError,RespArray, RespSet, RespPush, RespMap, RespAttr:if == -1 {return0, Nil } }return , nil}// IsNilReply detects redis.Nil of RESP2.func ( []byte) bool {returnlen() == 3 && ([0] == RespString || [0] == RespArray) && [1] == '-' && [2] == '1'}// ReadRawReply reads the next RESP reply and returns it as raw bytes without parsing.func ( *Reader) () ([]byte, error) {return .readRawReplyBuf(nil)}func ( *Reader) ( []byte) ([]byte, error) { , := .readLine()if != nil {return , } = append(, ...) = append(, '\r', '\n')switch [0] {caseRespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:return , nilcaseRespString, RespVerbatim, RespBlobError: , := replyLen()if != nil {if == Nil {return , nil }return , } := len() = append(, make([]byte, +2)...) _, = io.ReadFull(.rd, [:])return , caseRespArray, RespSet, RespPush: , := replyLen()if != nil {if == Nil {return , nil }return , }for := 0; < ; ++ { , = .()if != nil {return , } }return , nilcaseRespMap: , := replyLen()if != nil {if == Nil {return , nil }return , }for := 0; < ; ++ {for := 0; < 2; ++ { , = .()if != nil {return , } } }return , nilcaseRespAttr:// Per RESP3 spec, an attribute is always followed by the actual command reply. // We need to read the attribute's key-value pairs AND the following reply. , := replyLen()if != nil {if == Nil {return , nil }return , }// Read the attribute key-value pairs. Iterate over pairs rather than // n*2 elements so a count above MaxInt/2 can't overflow int to a // negative loop bound and skip the body.for := 0; < ; ++ {for := 0; < 2; ++ { , = .()if != nil {return , } } }// Read the command reply that follows the attributereturn .() }return , fmt.Errorf("redis: can't read raw reply: %.100q", )}var crlf = []byte{'\r', '\n'}// ReadRawReplyWriteTo streams the next RESP reply directly to w without intermediate allocations.// Returns the number of bytes written and any error encountered.func ( *Reader) ( io.Writer) (int64, error) {return .readRawReplyWriteTo()}func ( *Reader) ( io.Writer) (int64, error) { , := .readLine()if != nil {return0, }varint64 , := .Write() += int64()if != nil {return , } , = .Write(crlf) += int64()if != nil {return , }switch [0] {caseRespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:return , nilcaseRespString, RespVerbatim, RespBlobError: , := replyLen()if != nil {if == Nil {return , nil }return , } , := io.CopyN(, .rd, int64()+2) += return , caseRespArray, RespSet, RespPush: , := replyLen()if != nil {if == Nil {return , nil }return , }for := 0; < ; ++ { , := .() += if != nil {return , } }return , nilcaseRespMap: , := replyLen()if != nil {if == Nil {return , nil }return , }for := 0; < ; ++ {for := 0; < 2; ++ { , := .() += if != nil {return , } } }return , nilcaseRespAttr:// Per RESP3 spec, an attribute is always followed by the actual command reply. // We need to read the attribute's key-value pairs AND the following reply. , := replyLen()if != nil {if == Nil {return , nil }return , }// Read the attribute key-value pairs. Iterate over pairs rather than // count*2 elements so a count above MaxInt/2 can't overflow int to a // negative loop bound and skip the body.for := 0; < ; ++ {for := 0; < 2; ++ { , := .() += if != nil {return , } } }// Read the command reply that follows the attribute , := .() += return , }return , fmt.Errorf("redis: can't read raw reply: %.100q", )}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.