Coverage Report

Created: 2025-12-31 06:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/base16ct-0.2.0/src/lib.rs
Line
Count
Source
1
#![no_std]
2
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3
#![doc(
4
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
5
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
6
)]
7
#![warn(
8
    clippy::mod_module_files,
9
    clippy::unwrap_used,
10
    missing_docs,
11
    rust_2018_idioms,
12
    unused_lifetimes,
13
    unused_qualifications
14
)]
15
16
//! Pure Rust implementation of Base16 ([RFC 4648], a.k.a. hex).
17
//!
18
//! Implements lower and upper case Base16 variants without data-dependent branches
19
//! or lookup  tables, thereby providing portable "best effort" constant-time
20
//! operation. Not constant-time with respect to message length (only data).
21
//!
22
//! Supports `no_std` environments and avoids heap allocations in the core API
23
//! (but also provides optional `alloc` support for convenience).
24
//!
25
//! Based on code from: <https://github.com/Sc00bz/ConstTimeEncoding/blob/master/hex.cpp>
26
//!
27
//! # Examples
28
//! ```
29
//! let lower_hex_str = "abcd1234";
30
//! let upper_hex_str = "ABCD1234";
31
//! let mixed_hex_str = "abCD1234";
32
//! let raw = b"\xab\xcd\x12\x34";
33
//!
34
//! let mut buf = [0u8; 16];
35
//! // length of return slice can be different from the input buffer!
36
//! let res = base16ct::lower::decode(lower_hex_str, &mut buf).unwrap();
37
//! assert_eq!(res, raw);
38
//! let res = base16ct::lower::encode(raw, &mut buf).unwrap();
39
//! assert_eq!(res, lower_hex_str.as_bytes());
40
//! // you also can use `encode_str` and `encode_string` to get
41
//! // `&str` and `String` respectively
42
//! let res: &str = base16ct::lower::encode_str(raw, &mut buf).unwrap();
43
//! assert_eq!(res, lower_hex_str);
44
//!
45
//! let res = base16ct::upper::decode(upper_hex_str, &mut buf).unwrap();
46
//! assert_eq!(res, raw);
47
//! let res = base16ct::upper::encode(raw, &mut buf).unwrap();
48
//! assert_eq!(res, upper_hex_str.as_bytes());
49
//!
50
//! // In cases when you don't know if input contains upper or lower
51
//! // hex-encoded value, then use functions from the `mixed` module
52
//! let res = base16ct::mixed::decode(lower_hex_str, &mut buf).unwrap();
53
//! assert_eq!(res, raw);
54
//! let res = base16ct::mixed::decode(upper_hex_str, &mut buf).unwrap();
55
//! assert_eq!(res, raw);
56
//! let res = base16ct::mixed::decode(mixed_hex_str, &mut buf).unwrap();
57
//! assert_eq!(res, raw);
58
//! ```
59
//!
60
//! [RFC 4648]: https://tools.ietf.org/html/rfc4648
61
62
#[cfg(feature = "alloc")]
63
#[macro_use]
64
extern crate alloc;
65
#[cfg(feature = "std")]
66
extern crate std;
67
68
/// Function for decoding and encoding lower Base16 (hex)
69
pub mod lower;
70
/// Function for decoding mixed Base16 (hex)
71
pub mod mixed;
72
/// Function for decoding and encoding upper Base16 (hex)
73
pub mod upper;
74
75
/// Display formatter for hex.
76
mod display;
77
/// Error types.
78
mod error;
79
80
pub use crate::{
81
    display::HexDisplay,
82
    error::{Error, Result},
83
};
84
85
#[cfg(feature = "alloc")]
86
use alloc::{string::String, vec::Vec};
87
88
/// Compute decoded length of the given hex-encoded input.
89
#[inline(always)]
90
0
pub fn decoded_len(bytes: &[u8]) -> Result<usize> {
91
0
    if bytes.len() & 1 == 0 {
92
0
        Ok(bytes.len() / 2)
93
    } else {
94
0
        Err(Error::InvalidLength)
95
    }
96
0
}
97
98
/// Get the length of Base16 (hex) produced by encoding the given bytes.
99
#[inline(always)]
100
0
pub fn encoded_len(bytes: &[u8]) -> usize {
101
0
    bytes.len() * 2
102
0
}
103
104
0
fn decode_inner<'a>(
105
0
    src: &[u8],
106
0
    dst: &'a mut [u8],
107
0
    decode_nibble: impl Fn(u8) -> u16,
108
0
) -> Result<&'a [u8]> {
109
0
    let dst = dst
110
0
        .get_mut(..decoded_len(src)?)
111
0
        .ok_or(Error::InvalidLength)?;
112
113
0
    let mut err: u16 = 0;
114
0
    for (src, dst) in src.chunks_exact(2).zip(dst.iter_mut()) {
115
0
        let byte = (decode_nibble(src[0]) << 4) | decode_nibble(src[1]);
116
0
        err |= byte >> 8;
117
0
        *dst = byte as u8;
118
0
    }
119
120
0
    match err {
121
0
        0 => Ok(dst),
122
0
        _ => Err(Error::InvalidEncoding),
123
    }
124
0
}