From fc647d516d1e613238f482da5f0ccb3591fb2d46 Mon Sep 17 00:00:00 2001 From: Robin Kock Date: Sun, 4 Sep 2022 15:19:47 +0200 Subject: [PATCH] Add push_last to Nested --- src/lib.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 695714c..9fbcc32 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -145,6 +145,33 @@ impl Nested { self.indices.push(len); } + /// Pushes to the last [`Collection`] in this [`Nested`]. + /// + /// # Panics + /// Panics when the [`Nested`] is empty, i.e. does not contain any [`Collection`]. + /// + /// # Examples + /// ``` + /// # use nested::Nested; + /// let mut n = Nested::::new(); + /// + /// n.push("123"); + /// + /// n.push("abc"); + /// n.push_last("def"); + /// + /// assert_eq!(n.iter().collect::>(), vec!["123", "abcdef"]); + /// ``` + pub fn push_last>>(&mut self, el: I) { + if self.indices.len() < 2 { + panic!("no collection to push to"); + } + + self.data.extend_from_slice(el.as_ref()); + let last_mut = self.indices.last_mut().expect("unreachable: index.len > 2"); + *last_mut = self.data.len(); + } + /// Removes the last element from a `Nested` and returns it, or None if it is empty. pub fn pop(&mut self) -> Option { if self.indices.len() > 1 {