OnceList

Struct OnceList 

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

A single linked list which behaves like std::cell::OnceCell, but for multiple values.

§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]);

§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]));

Implementations§

Source§

impl<T: ?Sized> OnceList<T, Global>

Source

pub fn new() -> Self

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

Source§

impl<T: ?Sized, A: Allocator> OnceList<T, A>

Source

pub fn new_in(alloc: A) -> Self

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

Source

pub fn len(&self) -> usize

Returns the number of values in the list. This method is O(n).

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 first(&self) -> Option<&T>

Returns a first value, if it exists.

Source

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

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

Source

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

Returns a last value, if it exists. This method is O(n).

Source

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

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

Source

pub fn iter(&self) -> impl Iterator<Item = &T>

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

Source

pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T>

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

Source

pub fn clear(&mut self)

Clears the list, dropping all values.

Source

pub fn allocator(&self) -> &A

Returns an allocator of this struct.

Source§

impl<T: ?Sized, A: Allocator> OnceList<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> OnceList<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> OnceList<T, A>

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> OnceList<T, A>

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.

Source§

impl<A: Allocator + Clone> OnceList<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> OnceList<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"));

Trait Implementations§

Source§

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

Source§

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

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> Debug for OnceList<T, A>

Source§

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

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

impl<T: ?Sized> Default for OnceList<T, Global>

Source§

fn default() -> Self

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

impl<T, A: Allocator + Clone> Extend<T> for OnceList<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 OnceList<T, Global>

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> Hash for OnceList<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<T, A: Allocator> IntoIterator for OnceList<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> PartialEq for OnceList<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> Eq for OnceList<T, A>

Auto Trait Implementations§

§

impl<T, A = Global> !Freeze for OnceList<T, A>

§

impl<T, A = Global> !RefUnwindSafe for OnceList<T, A>

§

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

§

impl<T, A = Global> !Sync for OnceList<T, A>

§

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

§

impl<T, A> UnwindSafe for OnceList<T, A>
where A: 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.