tuwunel_core/utils/
bytes.rs1#[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
18pub 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
30pub 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#[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#[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#[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#[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#[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#[inline]
102pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64> { Ok(u64::from_be_bytes(bytes.try_into()?)) }
103
104#[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}