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