use std::fmt;
use std::str::from_utf8;
const MAX_NUMBER_TEXT_LENGTH: usize = 64;
pub(in crate::wire) struct FixedNumberText {
bytes: [u8; MAX_NUMBER_TEXT_LENGTH],
length: usize,
}
impl FixedNumberText {
#[must_use]
#[inline]
pub(in crate::wire) fn new() -> Self {
Self {
bytes: [0; MAX_NUMBER_TEXT_LENGTH],
length: 0,
}
}
#[must_use]
#[inline]
pub(in crate::wire) fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.length]
}
#[must_use]
#[inline]
pub(in crate::wire) fn as_str(&self) -> &str {
from_utf8(self.as_bytes()).expect("formatted text must be valid UTF-8")
}
}
impl fmt::Write for FixedNumberText {
fn write_str(&mut self, value: &str) -> fmt::Result {
let Some(end) = self.length.checked_add(value.len()) else {
return Err(fmt::Error);
};
let Some(destination) = self.bytes.get_mut(self.length..end) else {
return Err(fmt::Error);
};
destination.copy_from_slice(value.as_bytes());
self.length = end;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::fmt::Write;
use super::FixedNumberText;
#[test]
fn test_accepts_text_that_exactly_fills_capacity() {
let mut text = FixedNumberText::new();
text.write_str(&"x".repeat(64)).unwrap();
assert_eq!(text.as_str().len(), 64, "exact-capacity text must fit");
}
#[test]
fn test_rejects_overflow_without_changing_written_text() {
let mut text = FixedNumberText::new();
text.write_str("prefix").unwrap();
assert!(
text.write_str(&"x".repeat(59)).is_err(),
"a fragment exceeding remaining capacity must fail"
);
assert_eq!(text.as_str(), "prefix", "overflow must preserve written text");
}
#[test]
fn test_appends_multiple_fragments() {
let mut text = FixedNumberText::new();
text.write_str("-1.25e").unwrap();
text.write_str("10").unwrap();
assert_eq!(text.as_str(), "-1.25e10", "fragments must append in order");
}
}