package proto

import (
	
	
	
	
	
	
	

	
)

// DefaultBufferSize is the default size for read/write buffers (32 KiB).
const DefaultBufferSize = 32 * 1024

// redis resp protocol data type.
const (
	RespStatus    = '+' // +<string>\r\n
	RespError     = '-' // -<string>\r\n
	RespString    = '$' // $<length>\r\n<bytes>\r\n
	RespInt       = ':' // :<number>\r\n
	RespNil       = '_' // _\r\n
	RespFloat     = ',' // ,<floating-point-number>\r\n (golang float)
	RespBool      = '#' // true: #t\r\n false: #f\r\n
	RespBlobError = '!' // !<length>\r\n<bytes>\r\n
	RespVerbatim  = '=' // =<length>\r\nFORMAT:<bytes>\r\n
	RespBigInt    = '(' // (<big number>\r\n
	RespArray     = '*' // *<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 reply
	RespPush      = '>' // ><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 = '?'

//------------------------------------------------------------------------------

const Nil = RedisError("redis: nil") // nolint:errname

type RedisError string

func ( RedisError) () string { return string() }

func (RedisError) () {}

func ( []byte) error {
	 := string([1:])
	return parseTypedRedisError()
}

//------------------------------------------------------------------------------

type Reader struct {
	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 {
		return 0, 
	}
	if [0] == RespAttr {
		if  = .DiscardNext();  != nil {
			return 0, 
		}
		return .()
	}
	return [0], nil
}

// MinRESP3ReadBufferSize is the minimum buffer size used when RESP3 push
// notifications must be inspected without consuming them.
const MinRESP3ReadBufferSize = 128

// ErrPushNotificationNameTooLong is returned when the push header does not fit
// in the bounded peek window. Callers should consume the frame with ReadReply.
var ErrPushNotificationNameTooLong = 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  = 4096

	for {
		// 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 {
			if errors.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.
	if len() < 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
		}
		return util.BytesToString([ : +]), true, nil
	}

	// RespStatus: scan for the terminating CRLF.
	for  := ;  < len()-1; ++ {
		if [] == '\r' && [+1] == '\n' {
			return util.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", [])
		}
	}
	return len(), 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 {
		return nil, 
	}
	switch [0] {
	case RespError:
		return nil, ParseErrorReply()
	case RespNil:
		return nil, Nil
	case RespBlobError:
		var  string
		,  = .readStringReply()
		if  == nil {
			 = parseTypedRedisError()
		}
		return nil, 
	case RespAttr:
		if  = .Discard();  != nil {
			return nil, 
		}
		return .()
	}

	// Compatible with RESP2
	if IsNilReply() {
		return nil, 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 {
			return nil, 
		}

		 := make([]byte, len())
		copy(, )

		,  = .rd.ReadBytes('\n')
		if  != nil {
			return nil, 
		}

		 = append(, ...) //nolint:makezero
		 = 
	}
	if len() <= 2 || [len()-1] != '\n' || [len()-2] != '\r' {
		return nil, fmt.Errorf("redis: invalid reply: %q", )
	}
	return [:len()-2], nil
}

func ( *Reader) () (interface{}, error) {
	,  := .ReadLine()
	if  != nil {
		return nil, 
	}

	switch [0] {
	case RespStatus:
		return string([1:]), nil
	case RespInt:
		return util.ParseInt([1:], 10, 64)
	case RespFloat:
		return .readFloat()
	case RespBool:
		return .readBool()
	case RespBigInt:
		return .readBigInt()

	case RespString:
		return .readStringReply()
	case RespVerbatim:
		return .readVerb()

	case RespArray, RespSet, RespPush:
		return .readSlice()
	case RespMap:
		return .readMap()
	}
	return nil, fmt.Errorf("redis: can't parse %.100q", )
}

func ( *Reader) ( []byte) (float64, error) {
	 := util.BytesToString([1:])
	switch  {
	case "inf":
		return math.Inf(1), nil
	case "-inf":
		return math.Inf(-1), nil
	case "nan", "-nan":
		return math.NaN(), nil
	}
	return strconv.ParseFloat(, 64)
}

func ( *Reader) ( []byte) (bool, error) {
	switch util.BytesToString([1:]) {
	case "t":
		return true, nil
	case "f":
		return false, nil
	}
	return false, 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
	}
	return nil, 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 "", 
	}

	return util.BytesToString([:]), nil
}

func ( *Reader) ( []byte) (string, error) {
	,  := .readStringReply()
	if  != nil {
		return "", 
	}
	if len() < 4 || [3] != ':' {
		return "", fmt.Errorf("redis: can't parse verbatim string reply: %q", )
	}
	return [4:], nil
}

func ( *Reader) ( []byte) ([]interface{}, error) {
	,  := replyLen()
	if  != nil {
		return nil, 
	}

	 := make([]interface{}, )
	for  := 0;  < len(); ++ {
		,  := .ReadReply()
		if  != nil {
			if  == Nil {
				[] = nil
				continue
			}
			if ,  := .(RedisError);  {
				[] = 
				continue
			}
			return nil, 
		}
		[] = 
	}
	return , nil
}

func ( *Reader) ( []byte) (map[interface{}]interface{}, error) {
	,  := replyLen()
	if  != nil {
		return nil, 
	}
	 := make(map[interface{}]interface{}, )
	for  := 0;  < ; ++ {
		,  := .ReadReply()
		if  != nil {
			return nil, 
		}

		// 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{}:
			return nil, fmt.Errorf("redis: RESP3 map key must be a scalar type, got %T", )
		}

		,  := .ReadReply()
		if  != nil {
			if  == Nil {
				[] = nil
				continue
			}
			if ,  := .(RedisError);  {
				[] = 
				continue
			}
			return nil, 
		}

		[] = 
	}
	return , nil
}

// -------------------------------

func ( *Reader) () (int64, error) {
	,  := .ReadLine()
	if  != nil {
		return 0, 
	}
	switch [0] {
	case RespInt, RespStatus:
		return util.ParseInt([1:], 10, 64)
	case RespString:
		,  := .readStringReply()
		if  != nil {
			return 0, 
		}
		return strconv.ParseInt(, 10, 64)
	case RespBigInt:
		,  := .readBigInt()
		if  != nil {
			return 0, 
		}
		if !.IsInt64() {
			return 0, fmt.Errorf("bigInt(%s) value out of range", .String())
		}
		return .Int64(), nil
	}
	return 0, fmt.Errorf("redis: can't parse int reply: %.100q", )
}

func ( *Reader) () (uint64, error) {
	,  := .ReadLine()
	if  != nil {
		return 0, 
	}
	switch [0] {
	case RespInt, RespStatus:
		return util.ParseUint([1:], 10, 64)
	case RespString:
		,  := .readStringReply()
		if  != nil {
			return 0, 
		}
		return strconv.ParseUint(, 10, 64)
	case RespBigInt:
		,  := .readBigInt()
		if  != nil {
			return 0, 
		}
		if !.IsUint64() {
			return 0, fmt.Errorf("bigInt(%s) value out of range", .String())
		}
		return .Uint64(), nil
	}
	return 0, fmt.Errorf("redis: can't parse uint reply: %.100q", )
}

func ( *Reader) () (float64, error) {
	,  := .ReadLine()
	if  != nil {
		return 0, 
	}
	switch [0] {
	case RespFloat:
		return .readFloat()
	case RespStatus:
		return strconv.ParseFloat(util.BytesToString([1:]), 64)
	case RespString:
		,  := .readStringReply()
		if  != nil {
			return 0, 
		}
		return strconv.ParseFloat(, 64)
	}
	return 0, 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 {
		return 0, 
	}

	switch [0] {
	case RespStatus:
		// Simple string — data is in the line itself.
		 := [1:]
		if len() > len() {
			return 0, fmt.Errorf("redis: buffer too small: need %d bytes, have %d", len(), len())
		}
		return copy(, ), nil

	case RespString:
		,  := replyLen()
		if  != nil {
			return 0, 
		}
		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 {
				return 0, 
			}
			return 0, 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).
		if len() >= +2 {
			 := [:+2]
			if ,  := io.ReadFull(.rd, );  != nil {
				return 0, 
			}
			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 {
			return 0, 
		}
		if ,  := .rd.Discard(2);  != nil {
			return 0, 
		}
		return , nil

	case RespInt, RespFloat:
		 := [1:]
		if len() > len() {
			return 0, fmt.Errorf("redis: buffer too small: need %d bytes, have %d", len(), len())
		}
		return copy(, ), nil
	}

	return 0, fmt.Errorf("redis: can't parse reply=%.100q reading string into buffer", )
}

func ( *Reader) () (string, error) {
	,  := .ReadLine()
	if  != nil {
		return "", 
	}

	switch [0] {
	case RespStatus, RespInt, RespFloat:
		return string([1:]), nil
	case RespString:
		return .readStringReply()
	case RespBool:
		,  := .readBool()
		return strconv.FormatBool(), 
	case RespVerbatim:
		return .readVerb()
	case RespBigInt:
		,  := .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 {
		return false, 
	}
	return  == "OK" ||  == "1" ||  == "true", nil
}

func ( *Reader) () ([]interface{}, error) {
	,  := .ReadLine()
	if  != nil {
		return nil, 
	}
	return .readSlice()
}

// ReadFixedArrayLen read fixed array length.
func ( *Reader) ( int) error {
	,  := .ReadArrayLen()
	if  != nil {
		return 
	}
	if  !=  {
		return fmt.Errorf("redis: got %d elements in the array, wanted %d", , )
	}
	return nil
}

// ReadArrayLen Read and return the length of the array.
func ( *Reader) () (int, error) {
	,  := .ReadLine()
	if  != nil {
		return 0, 
	}
	switch [0] {
	case RespArray, RespSet, RespPush:
		return replyLen()
	default:
		return 0, 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  !=  {
		return fmt.Errorf("redis: got %d elements in the map, wanted %d", , )
	}
	return nil
}

// 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 {
		return 0, 
	}
	switch [0] {
	case RespMap:
		return replyLen()
	case RespArray, RespSet, RespPush:
		// Some commands and RESP2 protocol may respond to array types.
		,  := replyLen()
		if  != nil {
			return 0, 
		}
		if %2 != 0 {
			return 0, fmt.Errorf("redis: the length of the array must be a multiple of 2, got: %d", )
		}
		return  / 2, nil
	default:
		return 0, 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) {
	if len() == 0 {
		return errors.New("redis: invalid line")
	}
	switch [0] {
	case RespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:
		return nil
	}

	,  := 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.
			return nil
		}
		return 
	}

	switch [0] {
	case RespBlobError, RespString, RespVerbatim:
		// +\r\n
		_,  = .rd.Discard( + 2)
		return 
	case RespArray, RespSet, RespPush:
		for  := 0;  < ; ++ {
			if  = .DiscardNext();  != nil {
				return 
			}
		}
		return nil
	case RespMap, 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 
			}
		}
		return nil
	}

	return fmt.Errorf("redis: can't parse %.100q", )
}

func replyLen( []byte) ( int,  error) {
	,  = util.Atoi([1:])
	if  != nil {
		return 0, 
	}

	if  < -1 {
		return 0, fmt.Errorf("redis: invalid reply: %q", )
	}

	switch [0] {
	case RespString, RespVerbatim, RespBlobError,
		RespArray, RespSet, RespPush, RespMap, RespAttr:
		if  == -1 {
			return 0, Nil
		}
	}
	return , nil
}

// IsNilReply detects redis.Nil of RESP2.
func ( []byte) bool {
	return len() == 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] {
	case RespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:
		return , nil

	case RespString, RespVerbatim, RespBlobError:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		 := len()
		 = append(, make([]byte, +2)...)
		_,  = io.ReadFull(.rd, [:])
		return , 

	case RespArray, RespSet, RespPush:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		for  := 0;  < ; ++ {
			,  = .()
			if  != nil {
				return , 
			}
		}
		return , nil

	case RespMap:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		for  := 0;  < ; ++ {
			for  := 0;  < 2; ++ {
				,  = .()
				if  != nil {
					return , 
				}
			}
		}
		return , nil

	case RespAttr:
		// 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 attribute
		return .()
	}

	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 {
		return 0, 
	}

	var  int64
	,  := .Write()
	 += int64()
	if  != nil {
		return , 
	}
	,  = .Write(crlf)
	 += int64()
	if  != nil {
		return , 
	}

	switch [0] {
	case RespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:
		return , nil

	case RespString, RespVerbatim, RespBlobError:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		,  := io.CopyN(, .rd, int64()+2)
		 += 
		return , 

	case RespArray, RespSet, RespPush:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		for  := 0;  < ; ++ {
			,  := .()
			 += 
			if  != nil {
				return , 
			}
		}
		return , nil

	case RespMap:
		,  := replyLen()
		if  != nil {
			if  == Nil {
				return , nil
			}
			return , 
		}
		for  := 0;  < ; ++ {
			for  := 0;  < 2; ++ {
				,  := .()
				 += 
				if  != nil {
					return , 
				}
			}
		}
		return , nil

	case RespAttr:
		// 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", )
}