Skip to content

Commit

Permalink
Make CodecRegion generic over codecs
Browse files Browse the repository at this point in the history
Signed-off-by: Moritz Hoffmann <[email protected]>
  • Loading branch information
antiguru committed Feb 12, 2024
1 parent d2c4773 commit 29cc112
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,15 @@ pub fn consolidate_slice<T: Ord>(slice: &mut [(T, usize)]) -> usize {
offset
}

/// A region that encodes its data in a codec `C`.
#[derive(Default, Debug)]
struct CodecRegion {
pub struct CodecRegion<C: Codec> {
inner: CopyRegion<u8>,
codec: DictionaryCodec,
codec: C,
staging: Vec<u8>,
}

impl Region for CodecRegion {
impl<C: Codec> Region for CodecRegion<C> {
type ReadItem<'a> = &'a [u8]
where
Self: 'a;
Expand All @@ -92,8 +93,8 @@ impl Region for CodecRegion {
let codecs = regions.clone().map(|r| &r.codec).collect::<Vec<_>>();
let codecs: Result<[_; 2], _> = codecs.try_into();
let codec = match codecs {
Ok(codecs) => DictionaryCodec::new_from(codecs),
Err(_) => DictionaryCodec::default(),
Ok(codecs) => C::new_from(codecs),
Err(_) => C::default(),
};
Self {
inner: CopyRegion::merge_regions(regions.map(|r| &r.inner)),
Expand All @@ -120,20 +121,14 @@ impl Region for CodecRegion {
}
}

impl CopyOnto<CodecRegion> for &[u8] {
fn copy_onto(self, target: &mut CodecRegion) -> <CodecRegion as Region>::Index {
impl<C: Codec> CopyOnto<CodecRegion<C>> for &[u8] {
fn copy_onto(self, target: &mut CodecRegion<C>) -> <CodecRegion<C> as Region>::Index {
target.staging.clear();
target.codec.encode(self, &mut target.staging);
target.staging.as_slice().copy_onto(&mut target.inner)
}
}

impl<'a> CopyOnto<CodecRegion> for std::iter::Once<&'a [u8]> {
fn copy_onto(mut self, target: &mut CodecRegion) -> <CodecRegion as Region>::Index {
self.next().unwrap_or(&[]).copy_onto(target)
}
}

/// TODO
pub trait Codec: Default + 'static {
/// Decodes an input byte slice into a sequence of byte slices.
Expand Down Expand Up @@ -370,12 +365,12 @@ mod misra_gries {

#[cfg(test)]
mod tests {
use super::{Codec, CodecRegion};
use super::{Codec, CodecRegion, DictionaryCodec};
use crate::*;

#[test]
fn test_simple() {
let mut r = CodecRegion::default();
let mut r = CodecRegion::<DictionaryCodec>::default();

for _ in 0..1000 {
let index = "abc".as_bytes().copy_onto(&mut r);
Expand Down

0 comments on commit 29cc112

Please sign in to comment.