Skip to main content

buffa/sensitive/
text.rs

1// Modified by ReallyMe Technologies Limited.
2use super::{Zeroize, ZeroizeOnDrop, Zeroizing};
3
4/// A bounded temporary text buffer whose entire storage is wiped on drop.
5/// Formatting writes directly into the owner, without intermediate heap strings.
6pub struct StackText<const N: usize> {
7    bytes: Zeroizing<[u8; N]>,
8    length: usize,
9}
10/// A bounded text-formatting failure without input data in its diagnostics.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
12pub enum FormatError {
13    /// The fixed buffer could not hold the formatted representation.
14    #[error("sensitive text capacity exceeded")]
15    Capacity,
16    /// A writer produced invalid UTF-8.
17    #[error("sensitive text is not UTF-8")]
18    Utf8,
19}
20impl<const N: usize> Default for StackText<N> {
21    fn default() -> Self {
22        Self {
23            bytes: Zeroizing::new([0; N]),
24            length: 0,
25        }
26    }
27}
28impl<const N: usize> StackText<N> {
29    /// Borrow the initialized text.
30    /// # Errors
31    /// Returns a fixed error if a writer produced invalid UTF-8.
32    pub fn as_str(&self) -> Result<&str, FormatError> {
33        let bytes = self.bytes.get(..self.length).ok_or(FormatError::Capacity)?;
34        core::str::from_utf8(bytes).map_err(|_| FormatError::Utf8)
35    }
36}
37impl<const N: usize> core::fmt::Write for StackText<N> {
38    fn write_str(&mut self, value: &str) -> core::fmt::Result {
39        let end = self
40            .length
41            .checked_add(value.len())
42            .ok_or(core::fmt::Error)?;
43        let target = self
44            .bytes
45            .get_mut(self.length..end)
46            .ok_or(core::fmt::Error)?;
47        target.copy_from_slice(value.as_bytes());
48        self.length = end;
49        Ok(())
50    }
51}
52impl<const N: usize> Zeroize for StackText<N> {
53    fn zeroize(&mut self) {
54        self.bytes.zeroize();
55        self.length.zeroize();
56    }
57}
58impl<const N: usize> Drop for StackText<N> {
59    fn drop(&mut self) {
60        self.zeroize();
61    }
62}
63impl<const N: usize> ZeroizeOnDrop for StackText<N> {}
64
65#[cfg(feature = "json")]
66pub(crate) fn serialize_decimal<T: core::fmt::Display, S: serde::Serializer>(
67    value: &T,
68    serializer: S,
69) -> Result<S::Ok, S::Error> {
70    use core::fmt::Write;
71    // u64::MAX and i64::MIN both need at most twenty decimal characters.
72    const DECIMAL_CAPACITY: usize = 20;
73    let mut output = StackText::<DECIMAL_CAPACITY>::default();
74    write!(&mut output, "{value}").map_err(|_| serde::ser::Error::custom(FormatError::Capacity))?;
75    serializer.serialize_str(output.as_str().map_err(serde::ser::Error::custom)?)
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use core::fmt::Write;
82    #[test]
83    fn formatting_is_bounded_and_reusable_after_erasure() {
84        let mut text = StackText::<4>::default();
85        text.write_str("é").unwrap();
86        assert_eq!(text.as_str().unwrap(), "é");
87        assert!(text.write_str("abc").is_err());
88        assert_eq!(text.as_str().unwrap(), "é");
89        text.zeroize();
90        assert_eq!(text.as_str().unwrap(), "");
91        assert!(text.bytes.iter().all(|byte| *byte == 0));
92        text.write_str("1234").unwrap();
93        assert!(text.write_char('5').is_err());
94        assert!(StackText::<0>::default().write_char('x').is_err());
95    }
96}