Initially copy/pasted from Add a formatting specifier to limit the max length displayed of collections · Issue #906 · rust-lang/libs-team · GitHub, but with some minor changes.
Sometimes, collections get super long, and all that really matters is the length and/or first few entries. This especially comes up in scientific analysis code and in big data processing utilities, where even test programs sometimes generate so much temporary data that a single format!("{:?}", value) could fill up multiple terminal screens.
- This Internals comment asked for something similar to this at a high level, just recursion-aware.
- Someone filed util.inspect is not so hot on large typed arrays · Issue #3648 · nodejs/node · GitHub about basically the same issue as here in Node.js's similar-purpose
util.inspect(value), but concerning large typed arrays (analogous toBox<[PrimitiveType]>in Rust). Node.js resolved this by limiting the number of entries by default and adding amaxArrayLengthoption to configure/remove that limit. You can opt out of those limits and get Rust's current behavior by settingmaxArrayLength: Infinity, maxObjectLength: Infinity.
I propose three additions:
- Add a
@Nmodifier to formatters to limit the number of collection entries displayed (example:format!("{coll:@10?}")), and expose it via.size_limit()/etc. to formatter implementations.
// In `core::fmt`
impl<'a> Formatter<'a> {
pub fn size_limit(&self) -> Option<u16> {
self.options.get_size_limit()
}
}
impl FormattingOptions {
pub fn size_limit(&mut self, value: Option<u16>) -> &mut Self;
pub fn get_size_limit(&self) -> Option<u16>;
}
You can also use @N$ (example: format!("{coll:@0$}", 10)), @name$ (example: let size = 10; format!("{coll:@size$")) and @* (example: format!("{:@*}", 10, coll)) to pass in a dynamic size maximum. The syntax is nearly identical to the precision specifier .N/.N$/.name$/.*. The value must be a u16.
The compiler side, I'm not familiar enough with the compiler to make a concrete proposal here.
-
Define a
.debug_{set,map,list}_sized(size: usize)to return aDebugSet/DebugMap/DebugListvariant that, when incomplete, displays something like.. N more entries ..instead of just..at the end. -
Change
.entries(iter)onDebugSet/DebugMap/DebugListto stop displaying after.size_limit()entries, and if any need ignored, set an internal flag so that.finish()behaves as if.finish_non_exhaustive(). And likewise, change.entry(value)to ignore values after.size_limit()calls and, instead, just set that same internal flag if that happens. This does not require any new methods, so I'll just explain the details of this with a hand-written diff against the main repo instead.
--- library/core/src/fmt/builders.rs
+++ library/core/src/fmt/builders.rs
@@@ -523,8 +523,17 @@@
struct DebugInner<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
+ size_remaining: Option<u32>,
+ is_incomplete: bool,
has_fields: bool,
}
impl<'a, 'b: 'a> DebugInner {
fn entry(&mut self, entry: &dyn fmt::Debug) {
self.result = self.result.and_then(|_| {
+ if let Some(remaining) = &mut self.size_remaining {
+ if *remaining == 0 {
+ self.is_incomplete = true;
+ return false;
+ }
+ *remaining -= 1;
+ }
@@@ -593,4 +602,5 @@@
pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
let result = fmt.write_str("{");
- DebugSet { inner: DebugInner { fmt, result, has_fields: false } }
+ let size_remaining = fmt.size_limit();
+ DebugSet { inner: DebugInner { fmt, result, size_remaining, is_incomplete: false, has_fields: false } }
}
# `DebugSet`
@@@ -688,10 +698,15 @@@
pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
where
D: fmt::Debug,
I: IntoIterator<Item = D>,
{
- for entry in entries {
- self.entry(&entry);
- }
+ if !self.is_incomplete {
+ for entry in entries {
+ self.entry(&entry);
+ if self.is_incomplete {
+ break;
+ }
+ }
+ }
self
}
# `DebugSet`
@@@ -770,1 +785,4 @@@
pub fn finish(&mut self) -> fmt::Result {
+ if self.inner.is_incomplete {
+ return self.finish_non_exhaustive();
+ }
@@@ -808,4 +826,5 @@@
pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
let result = fmt.write_str("[");
- DebugList { inner: DebugInner { fmt, result, has_fields: false } }
+ let size_remaining = fmt.size_limit();
+ DebugList { inner: DebugInner { fmt, result, size_remaining, is_incomplete: false, has_fields: false } }
}
# `DebugList`
@@@ -903,10 +922,15 @@@
pub fn entries<D, I>(&mut self, entries: I) -> &mut Self
where
D: fmt::Debug,
I: IntoIterator<Item = D>,
{
- for entry in entries {
- self.entry(&entry);
- }
+ if !self.is_incomplete {
+ for entry in entries {
+ self.entry(&entry);
+ if self.is_incomplete {
+ break;
+ }
+ }
+ }
self
}
# `DebugList`
@@@ -984,1 +1006,4 @@@
pub fn finish(&mut self) -> fmt::Result {
+ if self.inner.is_incomplete {
+ return self.finish_non_exhaustive();
+ }
@@@ -1018,13 +1045,16 @@@
pub struct DebugMap<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
result: fmt::Result,
+ size_remaining: Option<u32>,
+ is_incomplete: bool,
has_fields: bool,
has_key: bool,
// The state of newlines is tracked between keys and values
state: PadAdapterState,
}
pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
let result = fmt.write_str("{");
- DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() }
+ let size_remaining = fmt.size_limit();
+ DebugMap { fmt, result, size_remaining, is_incomplete: false, has_fields: false, has_key: false, state: Default::default() }
}
# `DebugMap`
@@@ -1056,1 +1086,4 @@@
pub fn entry(&mut self, key: &dyn fmt::Debug, value: &dyn fmt::Debug) -> &mut Self {
+ if self.is_incomplete {
+ return self;
+ }
@@@ -1093,7 +1126,15 @@@
pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut Self {
self.result = self.result.and_then(|_| {
assert!(
!self.has_key,
"attempted to begin a new map entry \
without completing the previous one"
);
+
+ if let Some(remaining) = &mut self.size_remaining {
+ if *remaining == 0 {
+ self.is_incomplete = true;
+ return;
+ }
+ *remaining -= 1;
+ }
@@@ 1292,11 +1333,16 @@@
pub fn entries<K, V, I>(&mut self, entries: I) -> &mut Self
where
K: fmt::Debug,
V: fmt::Debug,
I: IntoIterator<Item = (K, V)>,
{
- for (k, v) in entries {
- self.entry(&k, &v);
- }
+ if !self.is_incomplete {
+ for (k, v) in entries {
+ self.entry(&k, &v);
+ if self.is_incomplete {
+ break;
+ }
+ }
+ }
self
}
@@@ 1387,1 +1433,4 @@@
pub fn finish(&mut self) -> fmt::Result {
+ if inner.is_incomplete {
+ return self.finish_non_exhaustive();
+ }
- Add a
.default_size_limit(size)helper tocore::fmt::Formatterto set a default size limit when@nisn't provided, useful for custom collection types that expect to be filled with large amounts of data. The effective size limit used is the minimum of this and what's specified by the@nmodifier.
// In `core::fmt`
impl Formatter<'_> {
pub fn default_size_limit<'b>(&'b mut self, size: u32) -> Formatter<'b> {
let options = self.options();
if options.get_size_limit().is_none() {
options.size_limit(size);
}
self.with_options(options)
}
}
Alternatives
Doing nothing is possible. I already have something analogous to this in one of my own code bases:
impl std::fmt::Debug for Vector<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_list();
f.entries(&self.values[...self.values.len().min(30));
if self.values.len() > 128 {
f.finish_non_exhaustive()
} else {
f.finish()
}
}
}
Just adding the @n syntax (read: doing only 1) is, of course, an option.
I also considered proposing adding .fmt_{list,map,set}_limited(entries, max_size) that does similar, but found it to be both too clunky and not configurable enough. It'd be way easier to use if it could be controlled externally.
I considered the possibility of a recursion-aware formatter, but that's way too complicated for a simple ACP, and there's also way better ways to limit overall length.
Someone in that ACP issue brought up the idea of limiting the length of the output. This is actually complementary with that: sometimes, you just want to cut everything off (great for test output and quick-and-dirty stuff), and sometimes, you want to just cut a collection off while retaining everything else. This in theory could be done with a specialized fmt::Write wrapper, but there's also value in just adding something like !N/etc. (similar to @N/etc. for this and the existing .N/etc. for precision) to provide a precise byte length limit.