Skip to main content

OnceListCore

Struct OnceListCore 

Source
pub struct OnceListCore<T: ?Sized, A: Allocator = Global, C = NoCache> { /* private fields */ }
Expand description

§Usage

A simple example:

use once_list2::OnceList;

// Create a new empty list. Note that the variable is immutable.
let list = OnceList::<i32>::new();

// You can push values to the list without the need for mutability.
list.push(1);
list.push(2);

// Or you can push multiple values at once.
list.extend([3, 4, 5]);

// You can iterate over the list.
assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);

// Some methods are mutable only.
let mut list_mut = list;

// You can remove (take) a value from the list.
let removed = list_mut.remove(|&x| x % 2 == 0);
assert_eq!(removed, Some(2));
assert_eq!(list_mut.iter().copied().collect::<Vec<_>>(), vec![1, 3, 4, 5]);

§Caching modes (optional)

You can choose a mode depending on what you want to optimize:

  • No cache (default):

    • OnceList::<T>::new()
    • OnceList::<T, A>::new_in(alloc)
    • push_back(): O(n), len(): O(n)
  • Len cache (O(1) len()):

    • Type: once_list2::OnceListWithLen<T, A>
    • Constructors: OnceListWithLen::<T>::new() / OnceListWithLen::<T, A>::new_in(alloc)
  • Tail cache (fast repeated tail inserts):

    • Type: once_list2::OnceListWithTail<T, A>
    • Constructors: OnceListWithTail::<T>::new() / OnceListWithTail::<T, A>::new_in(alloc)
    • Note: This mode caches the next insertion slot and speeds up operations that need to find the tail insertion point (e.g. push_back() / extend()), but it does not make back() O(1).
  • Tail + len cache:

    • Type: once_list2::OnceListWithTailLen<T, A>
    • Constructors: OnceListWithTailLen::<T>::new() / OnceListWithTailLen::<T, A>::new_in(alloc)

These modes keep the same behavior guarantees (including the iterator observing newly pushed values).

§Unsized types support

You can use the unsized types like str, [u8] or dyn Display as the value type of the OnceList.

If you are using the stable rust compiler, you can only use the dyn Any type as the unsized type. (Strictly speaking, you can use ANY type as the unsized type, but you can’t do any actual operations like pushing, removing, etc.)

In the nightly compiler and with the nightly feature enabled, the additional methods like push_unsized and remove_unsized_as become available:

// This code only works with the nightly compiler and the `nightly` feature enabled.

use once_list2::OnceList;

// Creating a `OnceList` for `[i32]`, the unsized type.
let list = OnceList::<[i32]>::new();

list.push_unsized([1] /* A sized array type, `[i32; 1]`, can be coerced into [i32].*/);
list.push_unsized([2, 3] /* Same for `[i32; 2] type. */);

// The normal methods like `iter` are available because it returns a reference to the value.
assert_eq!(list.iter().nth(0).unwrap(), &[1]);
assert_eq!(list.iter().nth(1).unwrap(), &[2, 3]);

let mut list_mut = list;

// `remove_unsized_as` method allows you to check the unsized value type and remove it.
let removed: Option<[i32; 2]> = unsafe {
    list_mut.remove_unsized_as(|x| if x.len() == 2 {
        Some(x.try_into().unwrap())
    } else {
        None
    })
};
// The removed value is an array, not a slice!
assert_eq!(removed, Some([2, 3]));

§Note about docs

The method implementations live on OnceListCore. The user-facing type aliases like OnceList and OnceListWithTail point to this type.

Implementations§

Source§

impl<A: Allocator + Clone, M> OnceListCore<dyn Any, A, M>
where M: CacheMode<dyn Any, A>,

Source

pub fn push_any<T: Any>(&self, val: T) -> &T

Pushes an aribitrary value to the list, and returns the reference to that value.

use once_list2::OnceList;
use std::any::Any;

let list = OnceList::<dyn Any>::new();
list.push_any(1);
list.push_any("hello");

assert_eq!(list.iter().nth(0).unwrap().downcast_ref::<i32>(), Some(&1));
assert_eq!(list.iter().nth(1).unwrap().downcast_ref::<&str>(), Some(&"hello"));
Source§

impl<A: Allocator, M> OnceListCore<dyn Any, A, M>
where M: CacheMode<dyn Any, A>,

Source

pub fn find_by_type<T: Any>(&self) -> Option<&T>

Finds the first value in the list that is the same type as T, and returns the reference to that value.

use once_list2::OnceList;
use std::any::Any;

let list = OnceList::<dyn Any>::new();
list.push_any(1);
list.push_any("hello");

assert_eq!(list.find_by_type::<i32>(), Some(&1));
assert_eq!(list.find_by_type::<&str>(), Some(&"hello"));
assert_eq!(list.find_by_type::<Vec<u8>>(), None);
Source

pub fn remove_by_type<T: Any>(&mut self) -> Option<T>

Removes the first value in the list that is the same type as T, and returns the value.

use once_list2::OnceList;
use std::any::Any;

let mut list = OnceList::<dyn Any>::new();
list.push_any(1);
list.push_any("hello");

assert_eq!(list.remove_by_type::<i32>(), Some(1));

assert_eq!(list.len(), 1);
assert_eq!(list.iter().nth(0).unwrap().downcast_ref::<&str>(), Some(&"hello"));
Source§

impl<T: ?Sized> OnceListCore<T, Global, WithLen<T, Global>>

Source

pub fn new() -> Self

Source§

impl<T: ?Sized, A: Allocator> OnceListCore<T, A, WithLen<T, A>>

Source

pub fn new_in(alloc: A) -> Self

Source§

impl<T: ?Sized> OnceListCore<T, Global, WithTail<T, Global>>

Source

pub fn new() -> Self

Source§

impl<T: ?Sized, A: Allocator> OnceListCore<T, A, WithTail<T, A>>

Source

pub fn new_in(alloc: A) -> Self

Source§

impl<T: ?Sized> OnceListCore<T, Global, WithTailLen<T, Global>>

Source

pub fn new() -> Self

Source§

impl<T: ?Sized, A: Allocator> OnceListCore<T, A, WithTailLen<T, A>>

Source

pub fn new_in(alloc: A) -> Self

Source§

impl<T: ?Sized> OnceListCore<T, Global, NoCache>

Source

pub fn new() -> Self

Creates a new empty OnceList. This method does not allocate.

Source§

impl<T: ?Sized, A: Allocator> OnceListCore<T, A, NoCache>

Source

pub fn new_in(alloc: A) -> Self

Creates a new empty OnceList with the given allocator. This method does not allocate.

Source§

impl<T: ?Sized, A: Allocator, C> OnceListCore<T, A, C>

Source

pub fn len(&self) -> usize
where C: CacheMode<T, A>,

Returns the number of values in the list.

  • O(1) if the current cache mode caches length
  • O(n) otherwise
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

Source

pub fn contains(&self, val: &T) -> bool
where T: PartialEq,

Returns true if the list contains the value.

Source

pub fn front(&self) -> Option<&T>

Returns the front value, if it exists.

Source

pub fn front_mut(&mut self) -> Option<&mut T>

Returns a mutable reference to the front value, if it exists.

Source

pub fn back(&self) -> Option<&T>

Returns the back value, if it exists. This method is O(n).

Source

pub fn back_mut(&mut self) -> Option<&mut T>

Returns a mutable reference to the back value, if it exists. This method is O(n).

Source

pub fn first(&self) -> Option<&T>

Returns the front value, if it exists.

This is an alias of OnceListCore::front.

Source

pub fn first_mut(&mut self) -> Option<&mut T>

Returns a mutable reference to the front value, if it exists.

This is an alias of OnceListCore::front_mut.

Source

pub fn last(&self) -> Option<&T>

Returns the back value, if it exists.

This is an alias of OnceListCore::back.

Source

pub fn last_mut(&mut self) -> Option<&mut T>

Returns a mutable reference to the back value, if it exists.

This is an alias of OnceListCore::back_mut.

Source

pub fn iter(&self) -> Iter<'_, T, A>

Returns an iterator over the &T references in the list.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, T, A>

Returns an iterator over the &mut T references in the list.

Source

pub fn allocator(&self) -> &A

Returns an allocator of this struct.

Source§

impl<T: ?Sized, A: Allocator, C> OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source

pub fn clear(&mut self)

Clears the list, dropping all values.

Source§

impl<T: ?Sized, A: Allocator, C> OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source

pub fn remove_into_box<P>(&mut self, pred: P) -> Option<Box<T, A>>
where P: FnMut(&T) -> bool,

Available on crate feature nightly only.

Removes the first value in the list that matches the predicate, and returns the value as a boxed value.

This method supports the unsized value type T as well.

Note that even though this method returns a boxed value, the box is something re-allcoated. So this method might not be efficient as you expect.

Source

pub unsafe fn remove_unsized_as<P, U>(&mut self, pred: P) -> Option<U>
where P: FnMut(&T) -> Option<&U>,

Available on crate feature nightly only.

Removes the first value in the list that matches the predicate, and returns the value.

The predicate function pred should return Some(&U) if the value is found, and the returned reference &U must be the same address as the value given in the pred.

§Safety

This method is unsafe because it requires the predicate to return a reference to the same address as the value.

Source§

impl<T: ?Sized, A: Allocator + Clone, C> OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source

pub fn push_unsized<U: Unsize<T>>(&self, val: U) -> &U

Available on crate feature nightly only.

An unsized version of the OnceList::push method.

You can push a sized value to the list. For exaple, you can push [i32; 3] to the list of [i32].

Source§

impl<T, A: Allocator, C> OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source

pub fn pop_front(&mut self) -> Option<T>

Removes the front value from the list, and returns it.

This method is O(1).

Source

pub fn remove<P>(&mut self, pred: P) -> Option<T>
where P: FnMut(&T) -> bool,

Find a first value in the list matches the predicate, remove that item from the list, and then returns that value.

Source§

impl<T, A: Allocator + Clone, C> OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source

pub fn push_back(&self, val: T) -> &T

Appends a value to the back of the list, and returns the reference to that value.

Note that this method takes &self, not &mut self.

Source

pub fn push(&self, val: T) -> &T

Appends a value to the list, and returns the reference to that value.

Note that this method takes &self, not &mut self.

Source

pub fn extend<U: IntoIterator<Item = T>>(&self, iter: U)

An almost same method with the std::iter::Extend::extend, though this method takes &self instead of &mut self.

Trait Implementations§

Source§

impl<T: Clone + ?Sized, A: Clone + Allocator, C: Clone> Clone for OnceListCore<T, A, C>

Source§

fn clone(&self) -> OnceListCore<T, A, C>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: ?Sized + Debug, A: Allocator, C> Debug for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: ?Sized, A: Allocator + Default, C: Default> Default for OnceListCore<T, A, C>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T, A: Allocator + Clone, C> Extend<T> for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source§

fn extend<U: IntoIterator<Item = T>>(&mut self, iter: U)

Due to the definition of the Extend trait, this method takes &mut self. Use the OnceList::extend method instead if you want to use &self.

Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<T> FromIterator<T> for OnceListCore<T, Global, NoCache>

Source§

fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self

Creates a value from an iterator. Read more
Source§

impl<T: ?Sized + Hash, A: Allocator, C> Hash for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a, T: ?Sized, A: Allocator, C> IntoIterator for &'a OnceListCore<T, A, C>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T, A>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T: ?Sized, A: Allocator, C> IntoIterator for &'a mut OnceListCore<T, A, C>

Source§

type Item = &'a mut T

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T, A>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T, A: Allocator, C> IntoIterator for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T, A>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T: ?Sized + PartialEq, A: Allocator, C> PartialEq for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: ?Sized + Eq, A: Allocator, C> Eq for OnceListCore<T, A, C>
where C: CacheMode<T, A>,

Auto Trait Implementations§

§

impl<T, A = Global, C = NoCache> !Freeze for OnceListCore<T, A, C>

§

impl<T, A = Global, C = NoCache> !RefUnwindSafe for OnceListCore<T, A, C>

§

impl<T, A, C> Send for OnceListCore<T, A, C>
where A: Send, C: Send, T: Send + ?Sized,

§

impl<T, A = Global, C = NoCache> !Sync for OnceListCore<T, A, C>

§

impl<T, A, C> Unpin for OnceListCore<T, A, C>
where A: Unpin, C: Unpin, T: ?Sized,

§

impl<T, A, C> UnwindSafe for OnceListCore<T, A, C>
where A: UnwindSafe, C: UnwindSafe, T: UnwindSafe + ?Sized,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.