Skip to content

Commit

Permalink
Add Record::truncate for trimming based on len (nushell#11004)
Browse files Browse the repository at this point in the history
# Description
Compatible with `Vec::truncate` and `indexmap::IndexMap::truncate`

Found useful in nushell#10903 for `drop column`

# Tests + Formatting
Doctest with the relevant edge-cases
sholderbach authored Nov 8, 2023
1 parent 0f600bc commit cd75640
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crates/nu-protocol/src/value/record.rs
Original file line number Diff line number Diff line change
@@ -203,6 +203,30 @@ impl Record {
self.cols.truncate(retained);
}

/// Truncate record to the first `len` elements.
///
/// `len > self.len()` will be ignored
/// ```rust
/// use nu_protocol::{record, Value};
///
/// let mut rec = record!(
/// "a" => Value::test_nothing(),
/// "b" => Value::test_int(42),
/// "c" => Value::test_nothing(),
/// "d" => Value::test_int(42),
/// );
/// rec.truncate(42); // this is fine
/// assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "abcd");
/// rec.truncate(2); // truncate
/// assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "ab");
/// rec.truncate(0); // clear the record
/// assert_eq!(rec.len(), 0);
/// ```
pub fn truncate(&mut self, len: usize) {
self.cols.truncate(len);
self.vals.truncate(len);
}

pub fn columns(&self) -> Columns {
Columns {
iter: self.cols.iter(),

0 comments on commit cd75640

Please sign in to comment.