Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 71 additions & 2 deletions rs/nervous_system/string/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Debug;
use std::fmt::{self, Debug, Write};

/// Returns a possibly modified version of `s` that fits within the specified bounds (in terms of
/// the number of UTF-8 characters).
Expand Down Expand Up @@ -37,8 +37,77 @@ pub fn clamp_string_len(s: &str, max_len: usize) -> String {
)
}

/// Formats object, but limits the output size.
///
/// Unlike clamp_string_len, does not include the tail (when truncating).
pub fn clamp_debug_len(object: &impl Debug, max_len: usize) -> String {
clamp_string_len(&format!("{object:#?}"), max_len)
let mut buf = LimitedWriter::new(max_len);
// write! returns Err if the writer returns Err, which LimitedWriter does
// once the limit is hit. We intentionally ignore this "error".
let _ignore_err = write!(buf, "{object:#?}");

if buf.truncated {
// Replace the last 3 chars with "..." to indicate truncation,
// or just append if the string is very short.
let s = &mut buf.buffer;
if s.len() >= 3 {
s.truncate(s.len() - 3);
s.push_str("...");
} else {
s.push_str("...");
}
Comment on lines +53 to +58
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .truncate() works on bytes and it panics if the new_len lies on the char boundary. I don't think it's likely, but we shouldn't panic for debugging.

BTW, for the following suggestion, the simplification to move .push_str("..."); out is just nitpicking. I'm fine with either way.

Suggested change
if s.len() >= 3 {
s.truncate(s.len() - 3);
s.push_str("...");
} else {
s.push_str("...");
}
if s.len() >= 3 {
for _ in 0..3 {
s.pop();
}
}
s.push_str("...");

}

buf.buffer
}

/// A `fmt::Write` implementation that stops accepting characters after a limit.
struct LimitedWriter {
buffer: String,
remaining: usize,
truncated: bool,
}

impl LimitedWriter {
fn new(max_len: usize) -> Self {
Self {
buffer: String::with_capacity(max_len.min(1024)),
remaining: max_len,
truncated: false,
}
}
}

impl fmt::Write for LimitedWriter {
fn write_str(&mut self, s: &str) -> fmt::Result {
if self.remaining == 0 {
self.truncated = true;
return Err(fmt::Error);
}

let chars_available = self.remaining;
let mut char_count = 0;
let byte_limit = s
.char_indices()
.take_while(|(_, _)| {
char_count += 1;
char_count <= chars_available
})
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);

if byte_limit < s.len() {
self.buffer.push_str(&s[..byte_limit]);
self.remaining = 0;
self.truncated = true;
Err(fmt::Error)
} else {
self.buffer.push_str(s);
self.remaining -= char_count;
Ok(())
}
}
}

#[cfg(test)]
Expand Down
27 changes: 27 additions & 0 deletions rs/nervous_system/string/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,30 @@ fn test_clamp_debug_len() {

assert_eq!(&clamp_debug_len(&S { i: 42 }, 100), "S {\n i: 42,\n}");
}

#[test]
fn test_clamp_debug_len_truncation() {
#[allow(unused)]
#[derive(Debug)]
struct S {
i: i32,
}

// Truncation: the full debug output is "S {\n i: 42,\n}" (16 chars).
// With max_len=10, we get 10 chars with the last 3 replaced by "...".
assert_eq!(&clamp_debug_len(&S { i: 42 }, 10), "S {\n ...");

// Very small limit.
assert_eq!(&clamp_debug_len(&S { i: 42 }, 3), "...");
}

#[test]
fn test_clamp_debug_len_large_object() {
// Verify that clamp_debug_len doesn't format the entire object
// when truncating. We can't easily prove this in a unit test, but
// we can verify the output is correct for a large-ish object.
let big_vec: Vec<i32> = (0..10_000).collect();
let result = clamp_debug_len(&big_vec, 50);
assert!(result.len() <= 50, "result len: {}", result.len());
assert!(result.ends_with("..."), "result: {result}");
}
Loading