1use super::{Zeroize, ZeroizeOnDrop, Zeroizing};
3
4pub struct StackText<const N: usize> {
7 bytes: Zeroizing<[u8; N]>,
8 length: usize,
9}
10#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
12pub enum FormatError {
13 #[error("sensitive text capacity exceeded")]
15 Capacity,
16 #[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 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 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}