ct_codecs/
lib.rs

1//! Constant-time codecs.
2
3#![cfg_attr(not(feature = "std"), no_std)]
4#![forbid(unsafe_code)]
5
6mod base64;
7mod error;
8mod hex;
9
10pub use base64::*;
11pub use error::*;
12pub use hex::*;
13
14pub trait Encoder {
15    /// Length of `bin_len` bytes after encoding.
16    fn encoded_len(bin_len: usize) -> Result<usize, Error>;
17
18    /// Encode `bin` into `encoded`.
19    /// The output buffer can be larger than required; the returned slice is
20    /// a view of the buffer with the correct length.
21    fn encode<IN: AsRef<[u8]>>(encoded: &mut [u8], bin: IN) -> Result<&[u8], Error>;
22
23    /// Encode `bin` into `encoded`, return the result as a `str`.
24    /// The output buffer can be larger than required; the returned slice is
25    /// a view of the buffer with the correct length.
26    fn encode_to_str<IN: AsRef<[u8]>>(encoded: &mut [u8], bin: IN) -> Result<&str, Error> {
27        Ok(core::str::from_utf8(Self::encode(encoded, bin)?).unwrap())
28    }
29
30    /// Encode `bin` as a `String`.
31    #[cfg(feature = "std")]
32    fn encode_to_string<IN: AsRef<[u8]>>(bin: IN) -> Result<String, Error> {
33        let mut encoded = vec![0u8; Self::encoded_len(bin.as_ref().len())?];
34        let encoded_len = Self::encode(&mut encoded, bin)?.len();
35        encoded.truncate(encoded_len);
36        Ok(String::from_utf8(encoded).unwrap())
37    }
38}
39
40pub trait Decoder {
41    /// Decode `encoded` into `bin`.
42    /// The output buffer can be larger than required; the returned slice is
43    /// a view of the buffer with the correct length.
44    /// `ignore` is an optional set of characters to ignore.
45    fn decode<'t, IN: AsRef<[u8]>>(
46        bin: &'t mut [u8],
47        encoded: IN,
48        ignore: Option<&[u8]>,
49    ) -> Result<&'t [u8], Error>;
50
51    /// Decode `encoded` into a `Vec<u8>`.
52    /// `ignore` is an optional set of characters to ignore.
53    #[cfg(feature = "std")]
54    fn decode_to_vec<IN: AsRef<[u8]>>(
55        encoded: IN,
56        ignore: Option<&[u8]>,
57    ) -> Result<Vec<u8>, Error> {
58        let mut bin = vec![0u8; encoded.as_ref().len()];
59        let bin_len = Self::decode(&mut bin, encoded, ignore)?.len();
60        bin.truncate(bin_len);
61        Ok(bin)
62    }
63}