use crate::decode::{__read_marker, read_arg};
use crate::{Error, Marker, ReadBuffer, ReadBufferBorrowed};

/// Decode the length of a byte array from any suitable representation and the binary data itself.
#[inline(always)]
pub fn read_bin<'de>(buf: &mut ReadBuffer<'de>) -> Result<&'de [u8], Error> {
    __read_bin(&buf.borrow())
}

pub(crate) fn __read_bin<'de>(buf: &ReadBufferBorrowed<'de>) -> Result<&'de [u8], Error> {
    let snapshot = buf.snapshot();
    let len = match __read_marker(buf)? {
        Marker::B8 => read_arg!(buf as u8)? as usize,
        Marker::B16 => read_arg!(buf as u16)? as usize,
        Marker::B32 => read_arg!(buf as u32)? as usize,

        _ => {
            // Undo the read_marker call.
            buf.restore(snapshot);

            return Err(Error::Unexpected);
        }
    };

    buf.read_and_borrow(len)
}
