utils: add helper for adding unbounded slices to tracing spans

This commit is contained in:
Lambda 2024-05-20 16:49:42 +00:00
parent 5a178ba393
commit 9dbc7d92e2

View file

@ -1,7 +1,7 @@
pub(crate) mod error; pub(crate) mod error;
use std::{ use std::{
cmp, cmp, fmt,
str::FromStr, str::FromStr,
time::{SystemTime, UNIX_EPOCH}, time::{SystemTime, UNIX_EPOCH},
}; };
@ -170,3 +170,42 @@ pub(crate) fn deserialize_from_str<
} }
deserializer.deserialize_str(Visitor(std::marker::PhantomData)) deserializer.deserialize_str(Visitor(std::marker::PhantomData))
} }
/// Debug-formats the given slice, but only up to the first `max_len` elements.
/// Any further elements are replaced by an ellipsis.
///
/// See also [`debug_slice_truncated()`],
pub(crate) struct TruncatedDebugSlice<'a, T> {
inner: &'a [T],
max_len: usize,
}
impl<T: fmt::Debug> fmt::Debug for TruncatedDebugSlice<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.inner.len() <= self.max_len {
write!(f, "{:?}", self.inner)
} else {
f.debug_list()
.entries(&self.inner[..self.max_len])
.entry(&"...")
.finish()
}
}
}
/// See [`TruncatedDebugSlice`]. Useful for `#[instrument]`:
///
/// ```ignore
/// #[tracing::instrument(fields(
/// foos = debug_slice_truncated(foos, N)
/// ))]
/// ```
pub(crate) fn debug_slice_truncated<T: fmt::Debug>(
slice: &[T],
max_len: usize,
) -> tracing::field::DebugValue<TruncatedDebugSlice<'_, T>> {
tracing::field::debug(TruncatedDebugSlice {
inner: slice,
max_len,
})
}