From cd75640a90d5166ee529a8c1c49eb9d2ab34253a Mon Sep 17 00:00:00 2001 From: Stefan Holderbach Date: Thu, 9 Nov 2023 00:00:20 +0100 Subject: [PATCH] Add `Record::truncate` for trimming based on len (#11004) # Description Compatible with `Vec::truncate` and `indexmap::IndexMap::truncate` Found useful in #10903 for `drop column` # Tests + Formatting Doctest with the relevant edge-cases --- crates/nu-protocol/src/value/record.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/nu-protocol/src/value/record.rs b/crates/nu-protocol/src/value/record.rs index 9297a7496752a..c3f4590b04497 100644 --- a/crates/nu-protocol/src/value/record.rs +++ b/crates/nu-protocol/src/value/record.rs @@ -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::(), "abcd"); + /// rec.truncate(2); // truncate + /// assert_eq!(rec.columns().map(String::as_str).collect::(), "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(),