package pgio

import (
	
	
	
	
)

// ErrInsufficientBytes is wrapped by all Reader errors caused by a read past
// the end of the source.
var ErrInsufficientBytes = errors.New("insufficient bytes")

// Reader is a bounds-checked reader for the PostgreSQL binary format. It is
// designed so that decoders of untrusted input cannot forget a length check:
// every read validates against the remaining bytes, and the first failure
// sticks. After a failure all subsequent reads return zero values, so a
// decoder can read an entire structure without intermediate error checks and
// inspect Err or Finish once at the end.
//
// Reads never panic. A decoder that branches on a value it just read (e.g. an
// element count used to size an allocation) should check Err before acting on
// the value.
type Reader struct {
	s   []byte
	rp  int
	err error
}

func ( []byte) *Reader {
	return &Reader{s: }
}

func ( *Reader) ( error) {
	if .err == nil {
		.err = 
	}
}

// need reports whether n more bytes are available, recording an error if not.
//
// The error is built by failShort rather than here so that need stays within
// the inliner's budget. Reads of fixed-size values are the hottest path in the
// driver, and an un-inlined bounds check costs more than the read itself.
func ( *Reader) ( int) bool {
	if .err != nil {
		return false
	}
	if len(.s)-.rp <  {
		.failShort()
		return false
	}
	return true
}

func ( *Reader) ( int) {
	.fail(fmt.Errorf("%w: %d needed at offset %d, %d remain", ErrInsufficientBytes, , .rp, len(.s)-.rp))
}

// Err returns the first error encountered, if any.
func ( *Reader) () error {
	return .err
}

// Remaining returns the number of unread bytes.
func ( *Reader) () int {
	return len(.s) - .rp
}

func ( *Reader) () byte {
	if !.need(1) {
		return 0
	}
	 := .s[.rp]
	.rp += 1
	return 
}

func ( *Reader) () uint16 {
	if !.need(2) {
		return 0
	}
	 := binary.BigEndian.Uint16(.s[.rp:])
	.rp += 2
	return 
}

func ( *Reader) () int16 {
	return int16(.Uint16())
}

func ( *Reader) () uint32 {
	if !.need(4) {
		return 0
	}
	 := binary.BigEndian.Uint32(.s[.rp:])
	.rp += 4
	return 
}

func ( *Reader) () int32 {
	return int32(.Uint32())
}

func ( *Reader) () uint64 {
	if !.need(8) {
		return 0
	}
	 := binary.BigEndian.Uint64(.s[.rp:])
	.rp += 8
	return 
}

func ( *Reader) () int64 {
	return int64(.Uint64())
}

// Bytes reads the next n bytes. The returned slice aliases the source; it is
// not a copy.
func ( *Reader) ( int) []byte {
	if  < 0 {
		.fail(fmt.Errorf("invalid byte count %d at offset %d", , .rp))
		return nil
	}
	if !.need() {
		return nil
	}
	 := .s[.rp : .rp+]
	.rp += 
	return 
}

// CString reads a NUL-terminated string, returning the bytes before the
// terminator and consuming the terminator. The returned slice aliases the
// source; it is not a copy.
func ( *Reader) () []byte {
	if .err != nil {
		return nil
	}
	 := bytes.IndexByte(.s[.rp:], 0)
	if  < 0 {
		.fail(fmt.Errorf("%w: unterminated string at offset %d", ErrInsufficientBytes, .rp))
		return nil
	}
	 := .s[.rp : .rp+]
	.rp +=  + 1
	return 
}

// Count reads an int32 element count and validates it against the remaining
// bytes: the count must be non-negative, and since each element occupies at
// least minElemSize bytes, count*minElemSize must not exceed the remaining
// message. This bounds allocations sized from the count against a malicious
// or corrupt message claiming a huge count. Returns 0 on any failure.
func ( *Reader) ( int) int {
	 := .rp
	 := int(.Int32())
	if .err != nil {
		return 0
	}
	if  < 0 {
		.fail(fmt.Errorf("invalid element count %d at offset %d", , ))
		return 0
	}
	if  < 1 {
		 = 1
	}
	if  > .Remaining()/ {
		.fail(fmt.Errorf("element count %d at offset %d exceeds %d remaining bytes", , , .Remaining()))
		return 0
	}
	return 
}

// Value reads an int32 length followed by that many bytes — the standard
// PostgreSQL binary representation of a value. A length of -1 means NULL and
// returns (nil, true). Any other negative length is an error. The returned
// slice aliases the source; null is only meaningful if Err returns nil.
func ( *Reader) () ( []byte,  bool) {
	 := .rp
	 := .Int32()
	if .err != nil {
		return nil, false
	}
	if  == -1 {
		return nil, true
	}
	if  < 0 {
		.fail(fmt.Errorf("invalid value length %d at offset %d", , ))
		return nil, false
	}
	return .Bytes(int()), false
}

// Finish returns the first error encountered, or an error if unread bytes
// remain. Decoders that must consume the entire source should end with Finish.
func ( *Reader) () error {
	if .err != nil {
		return .err
	}
	if .rp != len(.s) {
		return .errTrailing()
	}
	return nil
}

func ( *Reader) () error {
	return fmt.Errorf("%d unexpected trailing bytes at offset %d", len(.s)-.rp, .rp)
}

// ErrInvalidLength is wrapped by the errors returned from the exact-length
// read functions below.
var ErrInvalidLength = errors.New("invalid length")

func (,  int) error {
	return fmt.Errorf("%w: expected %d bytes, got %d", ErrInvalidLength, , )
}

// The Uint*Exact functions read a single fixed-size value that makes up an
// entire message, which is what the scan plans for the fixed-size PostgreSQL
// types receive. They are the counterpart to Reader for values that have no
// internal structure: there is no position to track and no error to make
// sticky, just an exact-length assertion the caller cannot skip. Keeping them
// separate from Reader is deliberate — these are the hottest decode paths in
// the driver and they are small enough for the compiler to inline, which a
// Reader method carrying a bounds check and a read pointer is not.

// Uint16Exact returns the big-endian uint16 in src, which must be exactly 2 bytes.
func ( []byte) (uint16, error) {
	if len() != 2 {
		return 0, errLength(2, len())
	}
	return binary.BigEndian.Uint16(), nil
}

// Uint32Exact returns the big-endian uint32 in src, which must be exactly 4 bytes.
func ( []byte) (uint32, error) {
	if len() != 4 {
		return 0, errLength(4, len())
	}
	return binary.BigEndian.Uint32(), nil
}

// Uint64Exact returns the big-endian uint64 in src, which must be exactly 8 bytes.
func ( []byte) (uint64, error) {
	if len() != 8 {
		return 0, errLength(8, len())
	}
	return binary.BigEndian.Uint64(), nil
}