irox_tools/codec/
mod.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5//!
6//! A [`Codec`] is a trait that provides `encode` and `decode` to convert to/from different byte
7//! encoding formats
8//!
9
10mod vbyte;
11pub use vbyte::*;
12mod varint;
13pub use varint::*;
14
15crate::cfg_feature_std! {
16    mod code_dictionary;
17    pub use code_dictionary::*;
18}
19
20crate::cfg_feature_alloc! {
21    extern crate alloc;
22    use alloc::string::{String, ToString};
23    use alloc::vec::Vec;
24}
25use irox_bits::{Bits, Error, MutBits};
26
27/// Something that can encode or decode bytes to bytes
28pub trait Codec {
29    /// Encodes the input, writing to output.  Returns the total number of bytes written.
30    fn encode<I: Bits, O: MutBits>(&self, input: I, output: &mut O) -> Result<usize, Error>;
31    /// Decodes the input, writing to output.  Returns the total number of bytes written.
32    fn decode<I: Bits, O: MutBits>(&self, input: I, output: &mut O) -> Result<usize, Error>;
33
34    crate::cfg_feature_alloc! {
35        /// Reads the entirety of the input in the raw format, and produces the encoded UTF-8 results
36        /// in an owned string.
37        fn encode_to_str<I: Bits>(&self, input: I) -> Result<String, Error> {
38            let vec = self.encode_to_vec(input)?;
39            Ok(String::from_utf8_lossy(vec.as_slice()).to_string())
40        }
41    }
42    crate::cfg_feature_alloc! {
43        /// Reads the entirety of the input in the raw format, and produces the encoded results in an
44        /// owned Vec
45        fn encode_to_vec<I: Bits>(&self, input: I) -> Result<Vec<u8>, Error> {
46            let mut vec = Vec::new();
47            self.encode(input, &mut vec)?;
48            Ok(vec)
49        }
50    }
51    crate::cfg_feature_alloc! {
52        /// Reads the entirety of input in coded format, and produces the results in an owned UTF-8 encoded
53        /// string, dropping any non-UTF-8 characters.
54        fn decode_to_str_lossy<I: Bits>(&self, input: I) -> Result<String, Error> {
55            let vec = self.decode_to_vec(input)?;
56            Ok(String::from_utf8_lossy(&vec).to_string())
57        }
58    }
59    crate::cfg_feature_alloc! {
60        /// Reads the entirety of input in coded format, and produces the results in an owned Vec
61        fn decode_to_vec<I: Bits>(&self, input: I) -> Result<Vec<u8>, Error> {
62            let mut vec = Vec::new();
63            self.decode(input, &mut vec)?;
64            Ok(vec)
65        }
66    }
67}