58 lines
1.6 KiB
Rust
58 lines
1.6 KiB
Rust
#[cfg(doc)]
|
|
use super::*;
|
|
|
|
/// 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()`.
|
|
fn write(&mut self, buf: &[u8]);
|
|
/// Current position of the stream. Used by [`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`], [`Factory::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 ExtDeserializer {
|
|
/// Try to read exactly `N` bytes.
|
|
fn read_n_const<const N: usize>(&mut self) -> Result<[u8; N], &[u8]>;
|
|
}
|
|
|
|
impl<D: ?Sized + Deserializer> ExtDeserializer 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),
|
|
}
|
|
}
|
|
}
|