use super::*;
#[derive(Debug)]
pub struct Serialised {
pub ser_id: SerId,
pub data: Bytes,
}
impl TryFrom<(SerId, Bytes)> for Serialised {
type Error = SerError;
fn try_from(t: (SerId, Bytes)) -> Result<Self, Self::Error> {
Ok(Serialised {
ser_id: t.0,
data: t.1,
})
}
}
impl<T, S> TryFrom<(&T, &S)> for Serialised
where
T: std::fmt::Debug,
S: Serialiser<T>,
{
type Error = SerError;
fn try_from(t: (&T, &S)) -> Result<Self, Self::Error> {
crate::serialisation::ser_helpers::serialiser_to_serialised(t.0, t.1)
}
}
impl TryFrom<&dyn Serialisable> for Serialised {
type Error = SerError;
fn try_from(ser: &dyn Serialisable) -> Result<Self, Self::Error> {
crate::serialisation::ser_helpers::serialise_to_serialised(ser)
}
}
impl<E> TryFrom<Result<Serialised, E>> for Serialised {
type Error = E;
fn try_from(res: Result<Serialised, E>) -> Result<Self, Self::Error> {
res
}
}
#[derive(Debug)]
pub enum SerialisedFrame {
Bytes(Bytes),
ChunkLease(ChunkLease),
ChunkRef(ChunkRef),
}
impl SerialisedFrame {
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
match self {
SerialisedFrame::ChunkLease(chunk) => chunk.remaining(),
SerialisedFrame::ChunkRef(chunk) => chunk.remaining(),
SerialisedFrame::Bytes(bytes) => bytes.remaining(),
}
}
pub fn bytes(&self) -> &[u8] {
match self {
SerialisedFrame::ChunkLease(chunk) => chunk.chunk(),
SerialisedFrame::ChunkRef(chunk) => chunk.chunk(),
SerialisedFrame::Bytes(bytes) => bytes.chunk(),
}
}
pub fn make_contiguous(&mut self) {
let len = self.len();
if len > self.bytes().len() {
match self {
SerialisedFrame::ChunkLease(chunk) => {
*self = SerialisedFrame::Bytes(chunk.copy_to_bytes(len));
}
SerialisedFrame::ChunkRef(chunk) => {
*self = SerialisedFrame::Bytes(chunk.copy_to_bytes(len));
}
_ => {
panic!("Impossible error, can't convert uncontiguous Bytes to contiguous");
}
}
}
}
}