package proto

import (
	

	
)

// maxBufferedFrameDepth bounds the nesting HasBufferedReply follows. A deeper
// reply reports false, which is always safe: the caller then reads it the
// normal way.
const maxBufferedFrameDepth = 32

// HasBufferedReply reports whether the buffer already holds one complete
// reply, with any push frames and attributes in front of it, so reading that
// reply needs no socket read. It does not read from the socket and consumes
// nothing. A frame it does not know, a malformed one, or a streamed aggregate
// reports false; the caller then reads it the normal way, which reports any
// error.
func ( *Reader) () bool {
	,  := .rd.Peek(.rd.Buffered())
	for len() > 0 {
		,  := bufferedFrameLen(, 0)
		if ! {
			return false
		}
		 := [0]
		 = [:]
		if  != RespPush &&  != RespAttr {
			return true
		}
	}
	return false
}

// bufferedValueLen returns the length of one complete value at the start of
// b, including the attribute frames that may prefix it: inside an aggregate an
// attribute decorates the element after it and is not an element itself.
func bufferedValueLen( []byte,  int) (int, bool) {
	 := 0
	for {
		,  := bufferedFrameLen([:], )
		if ! {
			return 0, false
		}
		 := []
		 += 
		if  != RespAttr {
			return , true
		}
	}
}

// bufferedFrameLen returns the length of the complete frame at the start of
// b. ok is false when b holds only part of it or the frame is not valid.
func bufferedFrameLen( []byte,  int) ( int,  bool) {
	if  > maxBufferedFrameDepth {
		return 0, false
	}
	 := bytes.IndexByte(, '\n')
	if  < 2 || [-1] != '\r' {
		return 0, false
	}
	 := [:-1]
	 :=  + 1
	switch [0] {
	case RespStatus, RespError, RespInt, RespNil, RespFloat, RespBool, RespBigInt:
		return , true
	}
	,  := util.Atoi([1:])
	if  != nil ||  < -1 {
		return 0, false
	}
	switch [0] {
	case RespString, RespVerbatim, RespBlobError:
		if  == -1 {
			return , true
		}
		if  > len()--2 {
			return 0, false
		}
		 :=  +  + 2
		if [-2] != '\r' || [-1] != '\n' {
			return 0, false
		}
		return , true
	case RespArray, RespSet, RespPush, RespMap, RespAttr:
		if  == -1 {
			return , true
		}
		 := 1
		if [0] == RespMap || [0] == RespAttr {
			 = 2
		}
		 := 
		// Every element takes at least 3 bytes, so a count the buffer cannot
		// hold ends the loop early instead of running cnt times.
		for  := 0;  < ; ++ {
			for  := 0;  < ; ++ {
				,  := bufferedValueLen([:], +1)
				if ! {
					return 0, false
				}
				 += 
			}
		}
		return , true
	}
	return 0, false
}