bcd5c231a4e0d75e156974b833835dd68657a179
[anymap] / src / lib.rs
1 //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type.
2
3 #![warn(missing_docs, unused_results)]
4
5 use std::any::TypeId;
6 use std::marker::PhantomData;
7
8 use raw::RawMap;
9 use any::{UncheckedAnyExt, IntoBox, Any};
10
11 macro_rules! impl_common_methods {
12 (
13 field: $t:ident.$field:ident;
14 new() => $new:expr;
15 with_capacity($with_capacity_arg:ident) => $with_capacity:expr;
16 ) => {
17 impl<A: ?Sized + UncheckedAnyExt> $t<A> {
18 /// Create an empty collection.
19 #[inline]
20 pub fn new() -> $t<A> {
21 $t {
22 $field: $new,
23 }
24 }
25
26 /// Creates an empty collection with the given initial capacity.
27 #[inline]
28 pub fn with_capacity($with_capacity_arg: usize) -> $t<A> {
29 $t {
30 $field: $with_capacity,
31 }
32 }
33
34 /// Returns the number of elements the collection can hold without reallocating.
35 #[inline]
36 pub fn capacity(&self) -> usize {
37 self.$field.capacity()
38 }
39
40 /// Reserves capacity for at least `additional` more elements to be inserted
41 /// in the collection. The collection may reserve more space to avoid
42 /// frequent reallocations.
43 ///
44 /// # Panics
45 ///
46 /// Panics if the new allocation size overflows `usize`.
47 #[inline]
48 pub fn reserve(&mut self, additional: usize) {
49 self.$field.reserve(additional)
50 }
51
52 /// Shrinks the capacity of the collection as much as possible. It will drop
53 /// down as much as possible while maintaining the internal rules
54 /// and possibly leaving some space in accordance with the resize policy.
55 #[inline]
56 pub fn shrink_to_fit(&mut self) {
57 self.$field.shrink_to_fit()
58 }
59
60 /// Returns the number of items in the collection.
61 #[inline]
62 pub fn len(&self) -> usize {
63 self.$field.len()
64 }
65
66 /// Returns true if there are no items in the collection.
67 #[inline]
68 pub fn is_empty(&self) -> bool {
69 self.$field.is_empty()
70 }
71
72 /// Removes all items from the collection. Keeps the allocated memory for reuse.
73 #[inline]
74 pub fn clear(&mut self) {
75 self.$field.clear()
76 }
77 }
78 }
79 }
80
81 pub mod any;
82 pub mod raw;
83
84 /// A collection containing zero or one values for any given type and allowing convenient,
85 /// type-safe access to those values.
86 ///
87 /// The type parameter `A` allows you to use a different value type; normally you will want it to
88 /// be `anymap::any::Any`, but there are other choices:
89 ///
90 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`.
91 /// - You can add on `+ Send` and/or `+ Sync` (e.g. `Map<Any + Send>`) to add those bounds.
92 ///
93 /// ```rust
94 /// # use anymap::AnyMap;
95 /// let mut data = AnyMap::new();
96 /// assert_eq!(data.get(), None::<&i32>);
97 /// data.insert(42i32);
98 /// assert_eq!(data.get(), Some(&42i32));
99 /// data.remove::<i32>();
100 /// assert_eq!(data.get::<i32>(), None);
101 ///
102 /// #[derive(Clone, PartialEq, Debug)]
103 /// struct Foo {
104 /// str: String,
105 /// }
106 ///
107 /// assert_eq!(data.get::<Foo>(), None);
108 /// data.insert(Foo { str: format!("foo") });
109 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
110 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
111 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
112 /// ```
113 ///
114 /// Values containing non-static references are not permitted.
115 #[derive(Debug)]
116 pub struct Map<A: ?Sized + UncheckedAnyExt = Any> {
117 raw: RawMap<A>,
118 }
119
120 // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box<A> that can.
121 impl<A: ?Sized + UncheckedAnyExt> Clone for Map<A> where Box<A>: Clone {
122 #[inline]
123 fn clone(&self) -> Map<A> {
124 Map {
125 raw: self.raw.clone(),
126 }
127 }
128 }
129
130 /// The most common type of `Map`: just using `Any`.
131 ///
132 /// Why is this a separate type alias rather than a default value for `Map<A>`? `Map::new()`
133 /// doesn’t seem to be happy to infer that it should go with the default value.
134 /// It’s a bit sad, really. Ah well, I guess this approach will do.
135 pub type AnyMap = Map<Any>;
136
137 impl_common_methods! {
138 field: Map.raw;
139 new() => RawMap::new();
140 with_capacity(capacity) => RawMap::with_capacity(capacity);
141 }
142
143 impl<A: ?Sized + UncheckedAnyExt> Map<A> {
144 /// Returns a reference to the value stored in the collection for the type `T`, if it exists.
145 #[inline]
146 pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
147 self.raw.get(&TypeId::of::<T>())
148 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
149 }
150
151 /// Returns a mutable reference to the value stored in the collection for the type `T`,
152 /// if it exists.
153 #[inline]
154 pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T> {
155 self.raw.get_mut(&TypeId::of::<T>())
156 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
157 }
158
159 /// Sets the value stored in the collection for the type `T`.
160 /// If the collection already had a value of type `T`, that value is returned.
161 /// Otherwise, `None` is returned.
162 #[inline]
163 pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
164 unsafe {
165 self.raw.insert(TypeId::of::<T>(), value.into_box())
166 .map(|any| *any.downcast_unchecked::<T>())
167 }
168 }
169
170 /// Removes the `T` value from the collection,
171 /// returning it if there was one or `None` if there was not.
172 #[inline]
173 pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
174 self.raw.remove(&TypeId::of::<T>())
175 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
176 }
177
178 /// Returns true if the collection contains a value of type `T`.
179 #[inline]
180 pub fn contains<T: IntoBox<A>>(&self) -> bool {
181 self.raw.contains_key(&TypeId::of::<T>())
182 }
183
184 /// Gets the entry for the given type in the collection for in-place manipulation
185 #[inline]
186 pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<A, T> {
187 match self.raw.entry(TypeId::of::<T>()) {
188 raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
189 inner: e,
190 type_: PhantomData,
191 }),
192 raw::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
193 inner: e,
194 type_: PhantomData,
195 }),
196 }
197 }
198 }
199
200 impl<A: ?Sized + UncheckedAnyExt> AsRef<RawMap<A>> for Map<A> {
201 #[inline]
202 fn as_ref(&self) -> &RawMap<A> {
203 &self.raw
204 }
205 }
206
207 impl<A: ?Sized + UncheckedAnyExt> AsMut<RawMap<A>> for Map<A> {
208 #[inline]
209 fn as_mut(&mut self) -> &mut RawMap<A> {
210 &mut self.raw
211 }
212 }
213
214 impl<A: ?Sized + UncheckedAnyExt> Into<RawMap<A>> for Map<A> {
215 #[inline]
216 fn into(self) -> RawMap<A> {
217 self.raw
218 }
219 }
220
221 /// A view into a single occupied location in an `Map`.
222 pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
223 inner: raw::OccupiedEntry<'a, A>,
224 type_: PhantomData<V>,
225 }
226
227 /// A view into a single empty location in an `Map`.
228 pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
229 inner: raw::VacantEntry<'a, A>,
230 type_: PhantomData<V>,
231 }
232
233 /// A view into a single location in an `Map`, which may be vacant or occupied.
234 pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> {
235 /// An occupied Entry
236 Occupied(OccupiedEntry<'a, A, V>),
237 /// A vacant Entry
238 Vacant(VacantEntry<'a, A, V>),
239 }
240
241 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> Entry<'a, A, V> {
242 /// Ensures a value is in the entry by inserting the default if empty, and returns
243 /// a mutable reference to the value in the entry.
244 #[inline]
245 pub fn or_insert(self, default: V) -> &'a mut V {
246 match self {
247 Entry::Occupied(inner) => inner.into_mut(),
248 Entry::Vacant(inner) => inner.insert(default),
249 }
250 }
251
252 /// Ensures a value is in the entry by inserting the result of the default function if empty,
253 /// and returns a mutable reference to the value in the entry.
254 #[inline]
255 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
256 match self {
257 Entry::Occupied(inner) => inner.into_mut(),
258 Entry::Vacant(inner) => inner.insert(default()),
259 }
260 }
261 }
262
263 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> OccupiedEntry<'a, A, V> {
264 /// Gets a reference to the value in the entry
265 #[inline]
266 pub fn get(&self) -> &V {
267 unsafe { self.inner.get().downcast_ref_unchecked() }
268 }
269
270 /// Gets a mutable reference to the value in the entry
271 #[inline]
272 pub fn get_mut(&mut self) -> &mut V {
273 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
274 }
275
276 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
277 /// with a lifetime bound to the collection itself
278 #[inline]
279 pub fn into_mut(self) -> &'a mut V {
280 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
281 }
282
283 /// Sets the value of the entry, and returns the entry's old value
284 #[inline]
285 pub fn insert(&mut self, value: V) -> V {
286 unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() }
287 }
288
289 /// Takes the value out of the entry, and returns it
290 #[inline]
291 pub fn remove(self) -> V {
292 unsafe { *self.inner.remove().downcast_unchecked() }
293 }
294 }
295
296 impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox<A>> VacantEntry<'a, A, V> {
297 /// Sets the value of the entry with the VacantEntry's key,
298 /// and returns a mutable reference to it
299 #[inline]
300 pub fn insert(self, value: V) -> &'a mut V {
301 unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() }
302 }
303 }
304
305 #[cfg(test)]
306 mod tests {
307 use {Map, AnyMap, Entry};
308 use any::{Any, CloneAny};
309
310 #[derive(Clone, Debug, PartialEq)] struct A(i32);
311 #[derive(Clone, Debug, PartialEq)] struct B(i32);
312 #[derive(Clone, Debug, PartialEq)] struct C(i32);
313 #[derive(Clone, Debug, PartialEq)] struct D(i32);
314 #[derive(Clone, Debug, PartialEq)] struct E(i32);
315 #[derive(Clone, Debug, PartialEq)] struct F(i32);
316 #[derive(Clone, Debug, PartialEq)] struct J(i32);
317
318 macro_rules! test_entry {
319 ($name:ident, $init:ty) => {
320 #[test]
321 fn $name() {
322 let mut map = <$init>::new();
323 assert_eq!(map.insert(A(10)), None);
324 assert_eq!(map.insert(B(20)), None);
325 assert_eq!(map.insert(C(30)), None);
326 assert_eq!(map.insert(D(40)), None);
327 assert_eq!(map.insert(E(50)), None);
328 assert_eq!(map.insert(F(60)), None);
329
330 // Existing key (insert)
331 match map.entry::<A>() {
332 Entry::Vacant(_) => unreachable!(),
333 Entry::Occupied(mut view) => {
334 assert_eq!(view.get(), &A(10));
335 assert_eq!(view.insert(A(100)), A(10));
336 }
337 }
338 assert_eq!(map.get::<A>().unwrap(), &A(100));
339 assert_eq!(map.len(), 6);
340
341
342 // Existing key (update)
343 match map.entry::<B>() {
344 Entry::Vacant(_) => unreachable!(),
345 Entry::Occupied(mut view) => {
346 let v = view.get_mut();
347 let new_v = B(v.0 * 10);
348 *v = new_v;
349 }
350 }
351 assert_eq!(map.get::<B>().unwrap(), &B(200));
352 assert_eq!(map.len(), 6);
353
354
355 // Existing key (remove)
356 match map.entry::<C>() {
357 Entry::Vacant(_) => unreachable!(),
358 Entry::Occupied(view) => {
359 assert_eq!(view.remove(), C(30));
360 }
361 }
362 assert_eq!(map.get::<C>(), None);
363 assert_eq!(map.len(), 5);
364
365
366 // Inexistent key (insert)
367 match map.entry::<J>() {
368 Entry::Occupied(_) => unreachable!(),
369 Entry::Vacant(view) => {
370 assert_eq!(*view.insert(J(1000)), J(1000));
371 }
372 }
373 assert_eq!(map.get::<J>().unwrap(), &J(1000));
374 assert_eq!(map.len(), 6);
375
376 // Entry.or_insert on existing key
377 map.entry::<B>().or_insert(B(71)).0 += 1;
378 assert_eq!(map.get::<B>().unwrap(), &B(201));
379 assert_eq!(map.len(), 6);
380
381 // Entry.or_insert on nonexisting key
382 map.entry::<C>().or_insert(C(300)).0 += 1;
383 assert_eq!(map.get::<C>().unwrap(), &C(301));
384 assert_eq!(map.len(), 7);
385 }
386 }
387 }
388
389 test_entry!(test_entry_any, AnyMap);
390 test_entry!(test_entry_cloneany, Map<CloneAny>);
391
392 #[test]
393 fn test_clone() {
394 let mut map: Map<CloneAny> = Map::new();
395 let _ = map.insert(A(1));
396 let _ = map.insert(B(2));
397 let _ = map.insert(D(3));
398 let _ = map.insert(E(4));
399 let _ = map.insert(F(5));
400 let _ = map.insert(J(6));
401 let map2 = map.clone();
402 assert_eq!(map2.len(), 6);
403 assert_eq!(map2.get::<A>(), Some(&A(1)));
404 assert_eq!(map2.get::<B>(), Some(&B(2)));
405 assert_eq!(map2.get::<C>(), None);
406 assert_eq!(map2.get::<D>(), Some(&D(3)));
407 assert_eq!(map2.get::<E>(), Some(&E(4)));
408 assert_eq!(map2.get::<F>(), Some(&F(5)));
409 assert_eq!(map2.get::<J>(), Some(&J(6)));
410 }
411
412 #[test]
413 fn test_varieties() {
414 fn assert_send<T: Send>() { }
415 fn assert_sync<T: Sync>() { }
416 fn assert_clone<T: Clone>() { }
417 fn assert_debug<T: ::std::fmt::Debug>() { }
418 assert_send::<Map<Any + Send>>();
419 assert_send::<Map<Any + Send + Sync>>();
420 assert_sync::<Map<Any + Sync>>();
421 assert_sync::<Map<Any + Send + Sync>>();
422 assert_debug::<Map<Any>>();
423 assert_debug::<Map<Any + Send>>();
424 assert_debug::<Map<Any + Sync>>();
425 assert_debug::<Map<Any + Send + Sync>>();
426 assert_send::<Map<CloneAny + Send>>();
427 assert_send::<Map<CloneAny + Send + Sync>>();
428 assert_sync::<Map<CloneAny + Sync>>();
429 assert_sync::<Map<CloneAny + Send + Sync>>();
430 assert_clone::<Map<CloneAny + Send>>();
431 assert_clone::<Map<CloneAny + Send + Sync>>();
432 assert_clone::<Map<CloneAny + Sync>>();
433 assert_clone::<Map<CloneAny + Send + Sync>>();
434 assert_debug::<Map<CloneAny>>();
435 assert_debug::<Map<CloneAny + Send>>();
436 assert_debug::<Map<CloneAny + Sync>>();
437 assert_debug::<Map<CloneAny + Send + Sync>>();
438 }
439 }