diff --git a/src/packed.rs b/src/packed.rs index 5a8ccb2..3fa8be0 100644 --- a/src/packed.rs +++ b/src/packed.rs @@ -2,11 +2,88 @@ mod packedscalar; mod packedslice; mod packedstr; +use std::mem::replace; + pub use packedscalar::Packed; pub use packedslice::PackedSlice; pub use packedstr::PackedStr; +use zerocopy::FromBytes; + +use crate::Bytes; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PackError { BadLayout, } + +impl Bytes { + pub fn packed_prefix(&mut self) -> Option> + where T: FromBytes { + let slice = self.as_slice(); + let size = size_of::(); + let (data, rest) = slice.split_at(size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packed: Packed = data.try_into().ok()?; + _ = replace(self, rest); + Some(packed) + } + + pub fn packedslice_prefix(&mut self, count: usize) -> Option> + where T: FromBytes { + let slice = self.as_slice(); + let size = size_of::() * count; + let (data, rest) = slice.split_at(size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packedslice: PackedSlice = data.try_into().ok()?; + _ = replace(self, rest); + Some(packedslice) + } + + pub fn packedstr_prefix(&mut self, count: usize) -> Option + where T: FromBytes { + let slice = self.as_slice(); + let size = size_of::() * count; + let (data, rest) = slice.split_at(size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packedstr: PackedStr = data.try_into().ok()?; + _ = replace(self, rest); + Some(packedstr) + } + + pub fn packed_suffix(&mut self) -> Option> + where T: FromBytes { + let slice = self.as_slice(); + let size = size_of::(); + let (data, rest) = slice.split_at(slice.len() - size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packed: Packed = data.try_into().ok()?; + _ = replace(self, rest); + Some(packed) + } + + pub fn packedslice_suffix(&mut self, count: usize) -> Option> + where T: FromBytes { + let slice = self.as_slice(); + let size = size_of::() * count; + let (data, rest) = slice.split_at(slice.len() - size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packedslice: PackedSlice = data.try_into().ok()?; + _ = replace(self, rest); + Some(packedslice) + } + + pub fn packedstr_suffix(&mut self, size: usize) -> Option { + let slice = self.as_slice(); + let (data, rest) = slice.split_at(slice.len() - size); + let data = self.slice_to_bytes(data)?; + let rest = self.slice_to_bytes(rest)?; + let packedstr: PackedStr = data.try_into().ok()?; + _ = replace(self, rest); + Some(packedstr) + } +} \ No newline at end of file