Skip to content

Commit

Permalink
Merge pull request #278 from cuviper/slice-new
Browse files Browse the repository at this point in the history
Add `Slice::new` and `new_mut` for empty slices
  • Loading branch information
cuviper committed Oct 27, 2023
2 parents 67e67dd + 0187071 commit 0d5ee80
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
16 changes: 13 additions & 3 deletions src/map/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct Slice<K, V> {
// and reference lifetimes are bound together in function signatures.
#[allow(unsafe_code)]
impl<K, V> Slice<K, V> {
pub(super) fn from_slice(entries: &[Bucket<K, V>]) -> &Self {
pub(super) const fn from_slice(entries: &[Bucket<K, V>]) -> &Self {
unsafe { &*(entries as *const [Bucket<K, V>] as *const Self) }
}

Expand All @@ -49,15 +49,25 @@ impl<K, V> Slice<K, V> {
self.into_boxed().into_vec()
}

/// Returns an empty slice.
pub const fn new<'a>() -> &'a Self {
Self::from_slice(&[])
}

/// Returns an empty mutable slice.
pub fn new_mut<'a>() -> &'a mut Self {
Self::from_mut_slice(&mut [])
}

/// Return the number of key-value pairs in the map slice.
#[inline]
pub fn len(&self) -> usize {
pub const fn len(&self) -> usize {
self.entries.len()
}

/// Returns true if the map slice contains no elements.
#[inline]
pub fn is_empty(&self) -> bool {
pub const fn is_empty(&self) -> bool {
self.entries.is_empty()
}

Expand Down
11 changes: 8 additions & 3 deletions src/set/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct Slice<T> {
// and reference lifetimes are bound together in function signatures.
#[allow(unsafe_code)]
impl<T> Slice<T> {
pub(super) fn from_slice(entries: &[Bucket<T>]) -> &Self {
pub(super) const fn from_slice(entries: &[Bucket<T>]) -> &Self {
unsafe { &*(entries as *const [Bucket<T>] as *const Self) }
}

Expand All @@ -42,13 +42,18 @@ impl<T> Slice<T> {
self.into_boxed().into_vec()
}

/// Returns an empty slice.
pub const fn new<'a>() -> &'a Self {
Self::from_slice(&[])
}

/// Return the number of elements in the set slice.
pub fn len(&self) -> usize {
pub const fn len(&self) -> usize {
self.entries.len()
}

/// Returns true if the set slice contains no elements.
pub fn is_empty(&self) -> bool {
pub const fn is_empty(&self) -> bool {
self.entries.is_empty()
}

Expand Down

0 comments on commit 0d5ee80

Please sign in to comment.