use std::fmt;
use std::fmt::Debug;
use std::fmt::Write as _;
pub(in crate::domain) fn bounded_debug<T>(value: &T, maximum: usize) -> (String, bool)
where
T: Debug + ?Sized,
{
let mut writer = BoundedCapture::new(maximum);
let _ = write!(&mut writer, "{value:?}");
writer.finish()
}
struct BoundedCapture {
output: String,
maximum: usize,
truncated: bool,
}
impl BoundedCapture {
fn new(maximum: usize) -> Self {
Self {
output: String::new(),
maximum,
truncated: false,
}
}
fn finish(self) -> (String, bool) {
(self.output, self.truncated)
}
}
impl fmt::Write for BoundedCapture {
fn write_str(&mut self, value: &str) -> fmt::Result {
let mut end = 0;
for (index, character) in value.char_indices() {
let next = index + character.len_utf8();
if next > self.maximum.saturating_sub(self.output.len()) {
self.truncated = true;
return Err(fmt::Error);
}
end = next;
}
self.output.push_str(&value[..end]);
Ok(())
}
}