Add a formatting specifier to limit the max length displayed of collections

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.

I propose three additions:

  1. Add a @N modifier 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.

  1. Define a .debug_{set,map,list}_sized(size: usize) to return a DebugSet/DebugMap/DebugList variant that, when incomplete, displays something like .. N more entries .. instead of just .. at the end.

  2. Change .entries(iter) on DebugSet/DebugMap/DebugList to 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();
+        }
  1. Add a .default_size_limit(size) helper to core::fmt::Formatter to set a default size limit when @n isn'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 @n modifier.
// 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.

2 Likes

I think adapters here seem like the way to go. The biggest reason those are less good is that derives don't naturally use them, but derives don't naturally use a new max-length specifier either, so this solution doesn't avoid that limitation.

Adding more stuff into format specifiers is pretty high impact.

2 Likes

I think special format specifiers would be bad design, because that information is passed to every type, but it doesn't make sense for all types. Adapters are the way to go.

For the same reason, I think the current design is broken: the format specifiers already don't apply to all types. This compiles but is wrong:

    println!("{:#.7}", "abc");

It would have been better if all the custom formatting options were done by adapters:

    println!("{}", PI.display().scientific().precision(7));

    // Compile error: no method `precision`.
    println!("{}", "abc".display().precision(7));
12 Likes

One place that specifiers do better is by affecting nested values as well. If I want to print the first 3 items of a matrix, I'm stuck with all of the elements of each orthogonal item for those 3 items.

5 Likes

Matrices can easily provide functionality to limit both rows and columns, today, with no special language feature:

println!("{}", matrix.display().max_rows(3).max_columns(3));

Sure, a matrix could do that, but any container-containing struct would need a custom adapter. Plus forwarding to any nested adapters that nested structs might want to provide.

1 Like