From 6171b1c0b5905a18e8e731f15cbf55c41b89b736 Mon Sep 17 00:00:00 2001 From: SalsaGal Date: Fri, 2 Feb 2024 14:54:06 +1100 Subject: [PATCH 1/2] Implement Extend trait --- src/lib.rs | 8 ++++++++ tests/slab.rs | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 7fc6f1a..914f2d6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1200,6 +1200,14 @@ impl Slab { } } +impl Extend for Slab { + fn extend>(&mut self, iter: I) { + for value in iter.into_iter() { + self.insert(value); + } + } +} + impl ops::Index for Slab { type Output = T; diff --git a/tests/slab.rs b/tests/slab.rs index 4799c1d..64e5661 100644 --- a/tests/slab.rs +++ b/tests/slab.rs @@ -76,6 +76,14 @@ fn insert_with_vacant_entry() { assert_eq!(123, slab[key]); } +#[test] +fn extend() { + let mut slab = Slab::with_capacity(5); + slab.extend(1..9); + assert_eq!(slab[5], 6); + assert_eq!(slab.len(), 8); +} + #[test] fn get_vacant_entry_without_using() { let mut slab = Slab::::with_capacity(1); From bb68fb412fd1ecf6b3646db9df667b3ac3ed75d4 Mon Sep 17 00:00:00 2001 From: SalsaGal Date: Sat, 3 Feb 2024 10:31:26 +1100 Subject: [PATCH 2/2] Replace implenting Extend for a simple function This function now returns Vec for the keys too. --- src/lib.rs | 23 +++++++++++++++-------- tests/slab.rs | 8 -------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 914f2d6..92da94e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -969,6 +969,21 @@ impl Slab { key } + /// Insert values in the slab from an iterator. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::with_capacity(5); + /// slab.extend(1..9); + /// assert_eq!(slab[5], 6); + /// assert_eq!(slab.len(), 8); + /// ``` + pub fn extend>(&mut self, iter: I) -> Vec { + iter.into_iter().map(|x| self.insert(x)).collect() + } + /// Returns the key of the next vacant entry. /// /// This function returns the key of the vacant entry which will be used @@ -1200,14 +1215,6 @@ impl Slab { } } -impl Extend for Slab { - fn extend>(&mut self, iter: I) { - for value in iter.into_iter() { - self.insert(value); - } - } -} - impl ops::Index for Slab { type Output = T; diff --git a/tests/slab.rs b/tests/slab.rs index 64e5661..4799c1d 100644 --- a/tests/slab.rs +++ b/tests/slab.rs @@ -76,14 +76,6 @@ fn insert_with_vacant_entry() { assert_eq!(123, slab[key]); } -#[test] -fn extend() { - let mut slab = Slab::with_capacity(5); - slab.extend(1..9); - assert_eq!(slab[5], 6); - assert_eq!(slab.len(), 8); -} - #[test] fn get_vacant_entry_without_using() { let mut slab = Slab::::with_capacity(1);