Skip to main content

tuwunel_core/utils/
bytes.rs

1//! Byte-size parsing, display, and integer encoding helpers.
2//!
3//! The module handles human-readable sizes alongside fixed-width big-endian
4//! counters. Its size deserializers integrate human-readable values with Serde.
5
6#[cfg(test)]
7mod tests;
8
9use std::fmt::{self, Display, Formatter, Write};
10
11use bytesize::ByteSize;
12use serde::{Deserialize, Deserializer, de};
13
14use crate::{Result, at, err};
15
16struct EscapedBytes<'a>(&'a [u8]);
17
18/// Accepts an integer byte count or a string with SI/IEC suffix (e.g. "24 MiB")
19/// and returns a `usize`.
20pub fn deserialize_bytesize_usize<'de, D>(de: D) -> Result<usize, D::Error>
21where
22	D: Deserializer<'de>,
23{
24	ByteSize::deserialize(de)
25		.map(at!(0))
26		.map(usize::try_from)?
27		.map_err(de::Error::custom)
28}
29
30/// Accepts an integer byte count or a string with SI/IEC suffix (e.g. "32 MiB")
31/// and returns a `u64`.
32pub fn deserialize_bytesize_u64<'de, D>(de: D) -> Result<u64, D::Error>
33where
34	D: Deserializer<'de>,
35{
36	ByteSize::deserialize(de).map(at!(0))
37}
38
39/// Parse a human-writable size string w/ si-unit suffix into integer
40#[inline]
41pub fn from_str(str: &str) -> Result<usize> {
42	let bytes: ByteSize = str
43		.parse()
44		.map_err(|e| err!(Arithmetic("Failed to parse byte size: {e}")))?;
45
46	let bytes: usize = bytes
47		.as_u64()
48		.try_into()
49		.map_err(|e| err!(Arithmetic("Failed to convert u64 to usize: {e}")))?;
50
51	Ok(bytes)
52}
53
54/// Output a human-readable size string w/ iec-unit suffix
55#[inline]
56#[must_use]
57pub fn pretty(bytes: usize) -> String {
58	let bytes: u64 = bytes
59		.try_into()
60		.expect("failed to convert usize to u64");
61
62	ByteSize::b(bytes).display().iec().to_string()
63}
64
65/// Renders bytes as text, writing each non-printable byte as `\xHH`.
66///
67/// Printable ASCII passes through, so a database key reads as itself around its
68/// binary separators. The raw database admin commands read and write this form.
69#[must_use]
70pub fn escape_bytes(data: &[u8]) -> impl Display + '_ { EscapedBytes(data) }
71
72impl Display for EscapedBytes<'_> {
73	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
74		self.0.iter().try_for_each(|byte| match byte {
75			| 0x20..=0x7E => f.write_char(char::from(*byte)),
76			| _ => write!(f, "\\x{byte:02x}"),
77		})
78	}
79}
80
81/// Increments an optional big-endian counter with wrapping arithmetic.
82///
83/// Missing or malformed input is treated as zero. The returned array contains
84/// the incremented value in big-endian byte order.
85#[inline]
86#[must_use]
87pub fn increment(old: Option<&[u8]>) -> [u8; 8] {
88	old.map_or(0_u64, |bytes| u64_from_bytes(bytes).unwrap_or(0))
89		.wrapping_add(1)
90		.to_be_bytes()
91}
92
93/// Parses 8 big-endian bytes into an u64; panic on invalid argument
94#[inline]
95#[must_use]
96pub fn u64_from_u8(bytes: &[u8]) -> u64 {
97	u64_from_bytes(bytes).expect("must slice at least 8 bytes")
98}
99
100/// Parses the big-endian bytes into an u64.
101#[inline]
102pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64> { Ok(u64::from_be_bytes(bytes.try_into()?)) }
103
104/// Returns the least byte prefix strictly after every key with this prefix.
105///
106/// Trailing maximum bytes are removed before the remaining last byte advances.
107/// An empty or all-maximum prefix has no successor. The owned buffer is reused.
108#[must_use]
109pub fn prefix_successor(mut prefix: Vec<u8>) -> Option<Vec<u8>> {
110	let index = prefix.iter().rposition(|byte| *byte != u8::MAX)?;
111
112	prefix.truncate(index.saturating_add(1));
113	prefix[index] = prefix[index].saturating_add(1);
114	Some(prefix)
115}