From 9dbc7d92e2c87300bbf0192367743c4d2e7d4026 Mon Sep 17 00:00:00 2001 From: Lambda Date: Mon, 20 May 2024 16:49:42 +0000 Subject: [PATCH] utils: add helper for adding unbounded slices to tracing spans --- src/utils.rs | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/utils.rs b/src/utils.rs index 0b40acbb..8d9b6764 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,7 +1,7 @@ pub(crate) mod error; use std::{ - cmp, + cmp, fmt, str::FromStr, time::{SystemTime, UNIX_EPOCH}, }; @@ -170,3 +170,42 @@ pub(crate) fn deserialize_from_str< } 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 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( + slice: &[T], + max_len: usize, +) -> tracing::field::DebugValue> { + tracing::field::debug(TruncatedDebugSlice { + inner: slice, + max_len, + }) +}