61 lines
1.8 KiB
Rust
61 lines
1.8 KiB
Rust
/// Serialisation mechanism that is chosen over bytestring concatenation
|
|
/// both for performance and simplicity.
|
|
///
|
|
/// See [`Serializable`].
|
|
pub trait Serializer {
|
|
/// Writes bytes from a slice. Should advance value of [`Serializer::tell()`] by [`buf.len`].
|
|
///
|
|
/// [`buf.len`]: slice::len
|
|
fn write(&mut self, buf: &[u8]);
|
|
/// Current position of the stream. Used by [`CheckedSerialize`].
|
|
///
|
|
/// [`CheckedSerialize`]: crate::rstd::inlining::CheckedSerialize
|
|
fn tell(&self) -> usize;
|
|
}
|
|
|
|
/// See [`Serializer`].
|
|
pub trait Serializable {
|
|
/// Expected to use [`Serializer::write`].
|
|
fn serialize(&self, serializer: &mut dyn Serializer);
|
|
}
|
|
|
|
impl Serializer for Vec<u8> {
|
|
fn write(&mut self, buf: &[u8]) {
|
|
self.extend(buf);
|
|
}
|
|
|
|
fn tell(&self) -> usize {
|
|
self.len()
|
|
}
|
|
}
|
|
|
|
/// Trait representing a readable stream used for parsing.
|
|
///
|
|
/// See [`Serializer`], [`FactoryParse::deserialize`].
|
|
///
|
|
/// [`FactoryParse::deserialize`]: super::FactoryParse::deserialize
|
|
pub trait Deserializer {
|
|
/// Read at most `n` bytes.
|
|
fn read_n(&mut self, n: usize) -> &[u8];
|
|
/// Read til the end of the stream.
|
|
fn read_all(&mut self) -> &[u8];
|
|
/// Current position of the stream. Used by [`crate::rstd::inlining::CheckedParse`].
|
|
fn tell(&self) -> usize;
|
|
}
|
|
|
|
/// Extension trait for [Deserializer]s.
|
|
pub trait DeserializerExt {
|
|
/// Try to read exactly `N` bytes.
|
|
fn read_n_const<const N: usize>(&mut self) -> Result<[u8; N], &[u8]>;
|
|
}
|
|
|
|
impl<D: ?Sized + Deserializer> DeserializerExt for D {
|
|
fn read_n_const<const N: usize>(&mut self) -> Result<[u8; N], &[u8]> {
|
|
let slice = self.read_n(N);
|
|
match slice.try_into() {
|
|
Ok(array) => Ok(array),
|
|
Err(_) => Err(slice),
|
|
}
|
|
}
|
|
}
|