Struct Map

Source
pub struct Map<A: ?Sized + Downcast = dyn Any> { /* private fields */ }
Expand description

A collection containing zero or one values for any given type and allowing convenient, type-safe access to those values.

The type parameter A allows you to use a different value type; normally you will want it to be core::any::Any (also known as std::any::Any), but there are other choices:

  • If you want the entire map to be cloneable, use CloneAny instead of Any; with that, you can only add types that implement Clone to the map.
  • You can add on + Send or + Send + Sync (e.g. Map<dyn Any + Send>) to add those auto traits.

Cumulatively, there are thus six forms of map:

§Example

(Here using the AnyMap convenience alias; the first line could use anymap3::Map::<core::any::Any>::new() instead if desired.)

let mut data = anymap3::AnyMap::new();
assert_eq!(data.get(), None::<&i32>);
data.insert(42i32);
assert_eq!(data.get(), Some(&42i32));
data.remove::<i32>();
assert_eq!(data.get::<i32>(), None);

#[derive(Clone, PartialEq, Debug)]
struct Foo {
    str: String,
}

assert_eq!(data.get::<Foo>(), None);
data.insert(Foo { str: format!("foo") });
assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");

Values containing non-static references are not permitted.

Implementations§

Source§

impl<A: ?Sized + Downcast> Map<A>

Source

pub fn new() -> Map<A>

Create an empty collection.

Source

pub fn with_capacity(capacity: usize) -> Map<A>

Creates an empty collection with the given initial capacity.

Source

pub fn capacity(&self) -> usize

Returns the number of elements the collection can hold without reallocating.

Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the collection. The collection may reserve more space to avoid frequent reallocations.

§Panics

Panics if the new allocation size overflows usize.

Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the collection as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.

Source

pub fn len(&self) -> usize

Returns the number of items in the collection.

Source

pub fn is_empty(&self) -> bool

Returns true if there are no items in the collection.

Source

pub fn clear(&mut self)

Removes all items from the collection. Keeps the allocated memory for reuse.

Source

pub fn get<T: IntoBox<A>>(&self) -> Option<&T>

Returns a reference to the value stored in the collection for the type T, if it exists.

Source

pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T>

Returns a mutable reference to the value stored in the collection for the type T, if it exists.

Source

pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T>

Sets the value stored in the collection for the type T. If the collection already had a value of type T, that value is returned. Otherwise, None is returned.

Source

pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T>

Removes the T value from the collection, returning it if there was one or None if there was not.

Source

pub fn contains<T: IntoBox<A>>(&self) -> bool

Returns true if the collection contains a value of type T.

Source

pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<'_, A, T>

Gets the entry for the given type in the collection for in-place manipulation

Source

pub fn as_raw(&self) -> &RawMap<A>

Get access to the raw hash map that backs this.

This will seldom be useful, but it’s conceivable that you could wish to iterate over all the items in the collection, and this lets you do that.

Source

pub unsafe fn as_raw_mut(&mut self) -> &mut RawMap<A>

Get mutable access to the raw hash map that backs this.

This will seldom be useful, but it’s conceivable that you could wish to iterate over all the items in the collection mutably, or drain or something, or possibly even batch insert, and this lets you do that.

§Safety

If you insert any values to the raw map, the key (a TypeId) must match the value’s type, or undefined behaviour will occur when you access those values.

(Removing entries is perfectly safe.)

Source

pub fn into_raw(self) -> RawMap<A>

Convert this into the raw hash map that backs this.

This will seldom be useful, but it’s conceivable that you could wish to consume all the items in the collection and do something with some or all of them, and this lets you do that, without the unsafe that .as_raw_mut().drain() would require.

Source

pub unsafe fn from_raw(raw: RawMap<A>) -> Map<A>

Construct a map from a collection of raw values.

You know what? I can’t immediately think of any legitimate use for this, especially because of the requirement of the BuildHasherDefault<TypeIdHasher> generic in the map.

Perhaps this will be most practical as unsafe { Map::from_raw(iter.collect()) }, iter being an iterator over (TypeId, Box<A>) pairs. Eh, this method provides symmetry with into_raw, so I don’t care if literally no one ever uses it. I’m not even going to write a test for it, it’s so trivial.

§Safety

For all entries in the raw map, the key (a TypeId) must match the value’s type, or undefined behaviour will occur when you access that entry.

Trait Implementations§

Source§

impl<A: ?Sized + Downcast> Clone for Map<A>
where Box<A>: Clone,

Source§

fn clone(&self) -> Map<A>

Returns a copy 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<A: Debug + ?Sized + Downcast> Debug for Map<A>

Source§

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

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

impl<A: ?Sized + Downcast> Default for Map<A>

Source§

fn default() -> Map<A>

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

impl<A: ?Sized + Downcast> Extend<Box<A>> for Map<A>

Source§

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

Extends a collection with the contents of an iterator. Read more
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

Auto Trait Implementations§

§

impl<A> Freeze for Map<A>
where A: ?Sized,

§

impl<A> RefUnwindSafe for Map<A>
where A: RefUnwindSafe + ?Sized,

§

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

§

impl<A> Sync for Map<A>
where A: Sync + ?Sized,

§

impl<A> Unpin for Map<A>
where A: ?Sized,

§

impl<A> UnwindSafe for Map<A>
where A: 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.
Source§

impl<T> CloneAny for T
where T: Any + Clone,