Skip to content

Commit

Permalink
[eclipse-iceoryx#497] Introduce SlotMap::next_free_key
Browse files Browse the repository at this point in the history
  • Loading branch information
elfenpiff committed Nov 12, 2024
1 parent f71e100 commit dfcd2e3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
29 changes: 29 additions & 0 deletions iceoryx2-bb/container/src/slotmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ pub mod details {
}
}

pub(crate) unsafe fn next_free_key_impl(&self) -> Option<SlotMapKey> {
self.idx_to_data_next_free_index
.peek_impl()
.map(|v| SlotMapKey::new(*v))
}

pub(crate) fn len_impl(&self) -> usize {
self.len
}
Expand Down Expand Up @@ -386,6 +392,12 @@ pub mod details {
unsafe { self.remove_impl(key) }
}

/// Returns the [`SlotMapKey`] that will be used when the user calls
/// [`SlotMap::insert()`]. If the [`SlotMap`] is full it returns [`None`].
pub fn next_free_key(&self) -> Option<SlotMapKey> {
unsafe { self.next_free_key_impl() }
}

/// Returns the number of stored values.
pub fn len(&self) -> usize {
self.len_impl()
Expand Down Expand Up @@ -493,6 +505,17 @@ pub mod details {
self.remove_impl(key)
}

/// Returns the [`SlotMapKey`] that will be used when the user calls
/// [`SlotMap::insert()`]. If the [`SlotMap`] is full it returns [`None`].
///
/// # Safety
///
/// * [`RelocatableSlotMap::init()`] must be called once before
///
pub unsafe fn next_free_key(&self) -> Option<SlotMapKey> {
self.next_free_key_impl()
}

/// Returns the number of stored values.
pub fn len(&self) -> usize {
self.len_impl()
Expand Down Expand Up @@ -607,6 +630,12 @@ impl<T, const CAPACITY: usize> FixedSizeSlotMap<T, CAPACITY> {
unsafe { self.state.remove_impl(key) }
}

/// Returns the [`SlotMapKey`] that will be used when the user calls
/// [`SlotMap::insert()`]. If the [`SlotMap`] is full it returns [`None`].
pub fn next_free_key(&self) -> Option<SlotMapKey> {
unsafe { self.state.next_free_key_impl() }
}

/// Returns the number of stored values.
pub fn len(&self) -> usize {
self.state.len_impl()
Expand Down
27 changes: 27 additions & 0 deletions iceoryx2-bb/container/tests/slotmap_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,31 @@ mod slot_map {
assert_that!(*value, eq 5 * key.value() + 3);
}
}

#[test]
fn next_free_key_returns_key_used_for_insert() {
let mut sut = FixedSizeSut::new();
let mut keys = vec![];

for _ in 0..SUT_CAPACITY / 2 {
keys.push(sut.insert(0).unwrap());
}

let next_key = sut.next_free_key();
assert_that!(next_key, is_some);
assert_that!(sut.insert(0), eq next_key);
}

#[test]
fn next_free_key_returns_none_when_full() {
let mut sut = FixedSizeSut::new();
let mut keys = vec![];

for _ in 0..SUT_CAPACITY {
keys.push(sut.insert(0).unwrap());
}

let next_key = sut.next_free_key();
assert_that!(next_key, is_none);
}
}

0 comments on commit dfcd2e3

Please sign in to comment.