use crate::{Error, payload::{Decode, Encode}, Payload};
use std::io::{Read, Seek};

#[derive(Debug, Clone, PartialEq)]
pub struct RawPayload(pub Vec<u8>);

impl AsRef<[u8]> for RawPayload {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl Decode for RawPayload {
    fn decode<R: Read + Seek>(mut reader: R, chunk_len: usize) -> Result<Self, Error> {
        let mut data = vec![0; chunk_len];
        reader.read_exact(&mut data).map_err(Error::from)?;

        Ok(Self(data))
    }
}

impl Encode for RawPayload {
    fn encode(&self) -> Vec<u8> {
        use std::iter::once;

        once(Payload::START_BYTE)
            .chain(self.0.iter().copied())
            .chain(once(Payload::END_BYTE))
            .collect()
    }
}
