1.0.0-beta.2
[anymap] / src / lib.rs
1 //! This crate provides a safe and convenient store for one value of each type.
2 //!
3 //! Your starting point is [`Map`]. It has an example.
4 //!
5 //! # Cargo features
6 //!
7 //! This crate has two independent features, each of which provides an implementation providing
8 //! types `Map`, `AnyMap`, `OccupiedEntry`, `VacantEntry`, `Entry` and `RawMap`:
9 //!
10 #![cfg_attr(feature = "std", doc = " - **std** (default, *enabled* in this build):")]
11 #![cfg_attr(not(feature = "std"), doc = " - **std** (default, *disabled* in this build):")]
12 //! an implementation using `std::collections::hash_map`, placed in the crate root
13 //! (e.g. `anymap::AnyMap`).
14 //!
15 #![cfg_attr(feature = "hashbrown", doc = " - **hashbrown** (optional; *enabled* in this build):")]
16 #![cfg_attr(not(feature = "hashbrown"), doc = " - **hashbrown** (optional; *disabled* in this build):")]
17 //! an implementation using `alloc` and `hashbrown::hash_map`, placed in a module `hashbrown`
18 //! (e.g. `anymap::hashbrown::AnyMap`).
19
20 #![warn(missing_docs, unused_results)]
21
22 #![cfg_attr(not(feature = "std"), no_std)]
23
24 use core::convert::TryInto;
25 use core::hash::Hasher;
26
27 #[cfg(not(feature = "std"))]
28 extern crate alloc;
29
30 pub use crate::any::CloneAny;
31
32 mod any;
33
34 #[cfg(any(feature = "std", feature = "hashbrown"))]
35 macro_rules! everything {
36 ($example_init:literal, $($parent:ident)::+ $(, $entry_generics:ty)?) => {
37 use core::any::{Any, TypeId};
38 use core::hash::BuildHasherDefault;
39 use core::marker::PhantomData;
40
41 #[cfg(not(feature = "std"))]
42 use alloc::boxed::Box;
43
44 use ::$($parent)::+::hash_map::{self, HashMap};
45
46 use crate::any::{Downcast, IntoBox};
47
48 /// Raw access to the underlying `HashMap`.
49 ///
50 /// This alias is provided for convenience because of the ugly third generic parameter.
51 pub type RawMap<A> = HashMap<TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>;
52
53 /// A collection containing zero or one values for any given type and allowing convenient,
54 /// type-safe access to those values.
55 ///
56 /// The type parameter `A` allows you to use a different value type; normally you will want
57 /// it to be `core::any::Any` (also known as `std::any::Any`), but there are other choices:
58 ///
59 /// - If you want the entire map to be cloneable, use `CloneAny` instead of `Any`; with
60 /// that, you can only add types that implement `Clone` to the map.
61 /// - You can add on `+ Send` or `+ Send + Sync` (e.g. `Map<dyn Any + Send>`) to add those
62 /// auto traits.
63 ///
64 /// Cumulatively, there are thus six forms of map:
65 ///
66 /// - <code>[Map]&lt;dyn [core::any::Any]&gt;</code>,
67 /// also spelled [`AnyMap`] for convenience.
68 /// - <code>[Map]&lt;dyn [core::any::Any] + Send&gt;</code>
69 /// - <code>[Map]&lt;dyn [core::any::Any] + Send + Sync&gt;</code>
70 /// - <code>[Map]&lt;dyn [CloneAny]&gt;</code>
71 /// - <code>[Map]&lt;dyn [CloneAny] + Send&gt;</code>
72 /// - <code>[Map]&lt;dyn [CloneAny] + Send + Sync&gt;</code>
73 ///
74 /// ## Example
75 ///
76 /// (Here using the [`AnyMap`] convenience alias; the first line could use
77 /// <code>[anymap::Map][Map]::&lt;[core::any::Any]&gt;::new()</code> instead if desired.)
78 ///
79 /// ```rust
80 #[doc = $example_init]
81 /// assert_eq!(data.get(), None::<&i32>);
82 /// data.insert(42i32);
83 /// assert_eq!(data.get(), Some(&42i32));
84 /// data.remove::<i32>();
85 /// assert_eq!(data.get::<i32>(), None);
86 ///
87 /// #[derive(Clone, PartialEq, Debug)]
88 /// struct Foo {
89 /// str: String,
90 /// }
91 ///
92 /// assert_eq!(data.get::<Foo>(), None);
93 /// data.insert(Foo { str: format!("foo") });
94 /// assert_eq!(data.get(), Some(&Foo { str: format!("foo") }));
95 /// data.get_mut::<Foo>().map(|foo| foo.str.push('t'));
96 /// assert_eq!(&*data.get::<Foo>().unwrap().str, "foot");
97 /// ```
98 ///
99 /// Values containing non-static references are not permitted.
100 #[derive(Debug)]
101 pub struct Map<A: ?Sized + Downcast = dyn Any> {
102 raw: RawMap<A>,
103 }
104
105 // #[derive(Clone)] would want A to implement Clone, but in reality only Box<A> can.
106 impl<A: ?Sized + Downcast> Clone for Map<A> where Box<A>: Clone {
107 #[inline]
108 fn clone(&self) -> Map<A> {
109 Map {
110 raw: self.raw.clone(),
111 }
112 }
113 }
114
115 /// The most common type of `Map`: just using `Any`; <code>[Map]&lt;dyn [Any]&gt;</code>.
116 ///
117 /// Why is this a separate type alias rather than a default value for `Map<A>`?
118 /// `Map::new()` doesn’t seem to be happy to infer that it should go with the default
119 /// value. It’s a bit sad, really. Ah well, I guess this approach will do.
120 pub type AnyMap = Map<dyn Any>;
121
122 impl<A: ?Sized + Downcast> Default for Map<A> {
123 #[inline]
124 fn default() -> Map<A> {
125 Map::new()
126 }
127 }
128
129 impl<A: ?Sized + Downcast> Map<A> {
130 /// Create an empty collection.
131 #[inline]
132 pub fn new() -> Map<A> {
133 Map {
134 raw: RawMap::with_hasher(Default::default()),
135 }
136 }
137
138 /// Creates an empty collection with the given initial capacity.
139 #[inline]
140 pub fn with_capacity(capacity: usize) -> Map<A> {
141 Map {
142 raw: RawMap::with_capacity_and_hasher(capacity, Default::default()),
143 }
144 }
145
146 /// Returns the number of elements the collection can hold without reallocating.
147 #[inline]
148 pub fn capacity(&self) -> usize {
149 self.raw.capacity()
150 }
151
152 /// Reserves capacity for at least `additional` more elements to be inserted
153 /// in the collection. The collection may reserve more space to avoid
154 /// frequent reallocations.
155 ///
156 /// # Panics
157 ///
158 /// Panics if the new allocation size overflows `usize`.
159 #[inline]
160 pub fn reserve(&mut self, additional: usize) {
161 self.raw.reserve(additional)
162 }
163
164 /// Shrinks the capacity of the collection as much as possible. It will drop
165 /// down as much as possible while maintaining the internal rules
166 /// and possibly leaving some space in accordance with the resize policy.
167 #[inline]
168 pub fn shrink_to_fit(&mut self) {
169 self.raw.shrink_to_fit()
170 }
171
172 // Additional stable methods (as of 1.60.0-nightly) that could be added:
173 // try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> (1.57.0)
174 // shrink_to(&mut self, min_capacity: usize) (1.56.0)
175
176 /// Returns the number of items in the collection.
177 #[inline]
178 pub fn len(&self) -> usize {
179 self.raw.len()
180 }
181
182 /// Returns true if there are no items in the collection.
183 #[inline]
184 pub fn is_empty(&self) -> bool {
185 self.raw.is_empty()
186 }
187
188 /// Removes all items from the collection. Keeps the allocated memory for reuse.
189 #[inline]
190 pub fn clear(&mut self) {
191 self.raw.clear()
192 }
193
194 /// Returns a reference to the value stored in the collection for the type `T`,
195 /// if it exists.
196 #[inline]
197 pub fn get<T: IntoBox<A>>(&self) -> Option<&T> {
198 self.raw.get(&TypeId::of::<T>())
199 .map(|any| unsafe { any.downcast_ref_unchecked::<T>() })
200 }
201
202 /// Returns a mutable reference to the value stored in the collection for the type `T`,
203 /// if it exists.
204 #[inline]
205 pub fn get_mut<T: IntoBox<A>>(&mut self) -> Option<&mut T> {
206 self.raw.get_mut(&TypeId::of::<T>())
207 .map(|any| unsafe { any.downcast_mut_unchecked::<T>() })
208 }
209
210 /// Sets the value stored in the collection for the type `T`.
211 /// If the collection already had a value of type `T`, that value is returned.
212 /// Otherwise, `None` is returned.
213 #[inline]
214 pub fn insert<T: IntoBox<A>>(&mut self, value: T) -> Option<T> {
215 self.raw.insert(TypeId::of::<T>(), value.into_box())
216 .map(|any| unsafe { *any.downcast_unchecked::<T>() })
217 }
218
219 // rustc 1.60.0-nightly has another method try_insert that would be nice when stable.
220
221 /// Removes the `T` value from the collection,
222 /// returning it if there was one or `None` if there was not.
223 #[inline]
224 pub fn remove<T: IntoBox<A>>(&mut self) -> Option<T> {
225 self.raw.remove(&TypeId::of::<T>())
226 .map(|any| *unsafe { any.downcast_unchecked::<T>() })
227 }
228
229 /// Returns true if the collection contains a value of type `T`.
230 #[inline]
231 pub fn contains<T: IntoBox<A>>(&self) -> bool {
232 self.raw.contains_key(&TypeId::of::<T>())
233 }
234
235 /// Gets the entry for the given type in the collection for in-place manipulation
236 #[inline]
237 pub fn entry<T: IntoBox<A>>(&mut self) -> Entry<A, T> {
238 match self.raw.entry(TypeId::of::<T>()) {
239 hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
240 inner: e,
241 type_: PhantomData,
242 }),
243 hash_map::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
244 inner: e,
245 type_: PhantomData,
246 }),
247 }
248 }
249
250 /// Get access to the raw hash map that backs this.
251 ///
252 /// This will seldom be useful, but it’s conceivable that you could wish to iterate
253 /// over all the items in the collection, and this lets you do that.
254 #[inline]
255 pub fn as_raw(&self) -> &RawMap<A> {
256 &self.raw
257 }
258
259 /// Get mutable access to the raw hash map that backs this.
260 ///
261 /// This will seldom be useful, but it’s conceivable that you could wish to iterate
262 /// over all the items in the collection mutably, or drain or something, or *possibly*
263 /// even batch insert, and this lets you do that.
264 ///
265 /// # Safety
266 ///
267 /// If you insert any values to the raw map, the key (a `TypeId`) must match the
268 /// value’s type, or *undefined behaviour* will occur when you access those values.
269 ///
270 /// (*Removing* entries is perfectly safe.)
271 #[inline]
272 pub unsafe fn as_raw_mut(&mut self) -> &mut RawMap<A> {
273 &mut self.raw
274 }
275
276 /// Convert this into the raw hash map that backs this.
277 ///
278 /// This will seldom be useful, but it’s conceivable that you could wish to consume all
279 /// the items in the collection and do *something* with some or all of them, and this
280 /// lets you do that, without the `unsafe` that `.as_raw_mut().drain()` would require.
281 #[inline]
282 pub fn into_raw(self) -> RawMap<A> {
283 self.raw
284 }
285
286 /// Construct a map from a collection of raw values.
287 ///
288 /// You know what? I can’t immediately think of any legitimate use for this, especially
289 /// because of the requirement of the `BuildHasherDefault<TypeIdHasher>` generic in the
290 /// map.
291 ///
292 /// Perhaps this will be most practical as `unsafe { Map::from_raw(iter.collect()) }`,
293 /// `iter` being an iterator over `(TypeId, Box<A>)` pairs. Eh, this method provides
294 /// symmetry with `into_raw`, so I don’t care if literally no one ever uses it. I’m not
295 /// even going to write a test for it, it’s so trivial.
296 ///
297 /// # Safety
298 ///
299 /// For all entries in the raw map, the key (a `TypeId`) must match the value’s type,
300 /// or *undefined behaviour* will occur when you access that entry.
301 #[inline]
302 pub unsafe fn from_raw(raw: RawMap<A>) -> Map<A> {
303 Self { raw }
304 }
305 }
306
307 impl<A: ?Sized + Downcast> Extend<Box<A>> for Map<A> {
308 #[inline]
309 fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T) {
310 for item in iter {
311 let _ = self.raw.insert(Downcast::type_id(&*item), item);
312 }
313 }
314 }
315
316 /// A view into a single occupied location in an `Map`.
317 pub struct OccupiedEntry<'a, A: ?Sized + Downcast, V: 'a> {
318 inner: hash_map::OccupiedEntry<'a, TypeId, Box<A>, $($entry_generics)?>,
319 type_: PhantomData<V>,
320 }
321
322 /// A view into a single empty location in an `Map`.
323 pub struct VacantEntry<'a, A: ?Sized + Downcast, V: 'a> {
324 inner: hash_map::VacantEntry<'a, TypeId, Box<A>, $($entry_generics)?>,
325 type_: PhantomData<V>,
326 }
327
328 /// A view into a single location in an `Map`, which may be vacant or occupied.
329 pub enum Entry<'a, A: ?Sized + Downcast, V: 'a> {
330 /// An occupied Entry
331 Occupied(OccupiedEntry<'a, A, V>),
332 /// A vacant Entry
333 Vacant(VacantEntry<'a, A, V>),
334 }
335
336 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> Entry<'a, A, V> {
337 /// Ensures a value is in the entry by inserting the default if empty, and returns
338 /// a mutable reference to the value in the entry.
339 #[inline]
340 pub fn or_insert(self, default: V) -> &'a mut V {
341 match self {
342 Entry::Occupied(inner) => inner.into_mut(),
343 Entry::Vacant(inner) => inner.insert(default),
344 }
345 }
346
347 /// Ensures a value is in the entry by inserting the result of the default function if
348 /// empty, and returns a mutable reference to the value in the entry.
349 #[inline]
350 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
351 match self {
352 Entry::Occupied(inner) => inner.into_mut(),
353 Entry::Vacant(inner) => inner.insert(default()),
354 }
355 }
356
357 /// Ensures a value is in the entry by inserting the default value if empty,
358 /// and returns a mutable reference to the value in the entry.
359 #[inline]
360 pub fn or_default(self) -> &'a mut V where V: Default {
361 match self {
362 Entry::Occupied(inner) => inner.into_mut(),
363 Entry::Vacant(inner) => inner.insert(Default::default()),
364 }
365 }
366
367 /// Provides in-place mutable access to an occupied entry before any potential inserts
368 /// into the map.
369 #[inline]
370 pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Self {
371 match self {
372 Entry::Occupied(mut inner) => {
373 f(inner.get_mut());
374 Entry::Occupied(inner)
375 },
376 Entry::Vacant(inner) => Entry::Vacant(inner),
377 }
378 }
379
380 // Additional stable methods (as of 1.60.0-nightly) that could be added:
381 // insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> (1.59.0)
382 }
383
384 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> OccupiedEntry<'a, A, V> {
385 /// Gets a reference to the value in the entry
386 #[inline]
387 pub fn get(&self) -> &V {
388 unsafe { self.inner.get().downcast_ref_unchecked() }
389 }
390
391 /// Gets a mutable reference to the value in the entry
392 #[inline]
393 pub fn get_mut(&mut self) -> &mut V {
394 unsafe { self.inner.get_mut().downcast_mut_unchecked() }
395 }
396
397 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
398 /// with a lifetime bound to the collection itself
399 #[inline]
400 pub fn into_mut(self) -> &'a mut V {
401 unsafe { self.inner.into_mut().downcast_mut_unchecked() }
402 }
403
404 /// Sets the value of the entry, and returns the entry's old value
405 #[inline]
406 pub fn insert(&mut self, value: V) -> V {
407 unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() }
408 }
409
410 /// Takes the value out of the entry, and returns it
411 #[inline]
412 pub fn remove(self) -> V {
413 unsafe { *self.inner.remove().downcast_unchecked() }
414 }
415 }
416
417 impl<'a, A: ?Sized + Downcast, V: IntoBox<A>> VacantEntry<'a, A, V> {
418 /// Sets the value of the entry with the VacantEntry's key,
419 /// and returns a mutable reference to it
420 #[inline]
421 pub fn insert(self, value: V) -> &'a mut V {
422 unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() }
423 }
424 }
425
426 #[cfg(test)]
427 mod tests {
428 use crate::CloneAny;
429 use super::*;
430
431 #[derive(Clone, Debug, PartialEq)] struct A(i32);
432 #[derive(Clone, Debug, PartialEq)] struct B(i32);
433 #[derive(Clone, Debug, PartialEq)] struct C(i32);
434 #[derive(Clone, Debug, PartialEq)] struct D(i32);
435 #[derive(Clone, Debug, PartialEq)] struct E(i32);
436 #[derive(Clone, Debug, PartialEq)] struct F(i32);
437 #[derive(Clone, Debug, PartialEq)] struct J(i32);
438
439 macro_rules! test_entry {
440 ($name:ident, $init:ty) => {
441 #[test]
442 fn $name() {
443 let mut map = <$init>::new();
444 assert_eq!(map.insert(A(10)), None);
445 assert_eq!(map.insert(B(20)), None);
446 assert_eq!(map.insert(C(30)), None);
447 assert_eq!(map.insert(D(40)), None);
448 assert_eq!(map.insert(E(50)), None);
449 assert_eq!(map.insert(F(60)), None);
450
451 // Existing key (insert)
452 match map.entry::<A>() {
453 Entry::Vacant(_) => unreachable!(),
454 Entry::Occupied(mut view) => {
455 assert_eq!(view.get(), &A(10));
456 assert_eq!(view.insert(A(100)), A(10));
457 }
458 }
459 assert_eq!(map.get::<A>().unwrap(), &A(100));
460 assert_eq!(map.len(), 6);
461
462
463 // Existing key (update)
464 match map.entry::<B>() {
465 Entry::Vacant(_) => unreachable!(),
466 Entry::Occupied(mut view) => {
467 let v = view.get_mut();
468 let new_v = B(v.0 * 10);
469 *v = new_v;
470 }
471 }
472 assert_eq!(map.get::<B>().unwrap(), &B(200));
473 assert_eq!(map.len(), 6);
474
475
476 // Existing key (remove)
477 match map.entry::<C>() {
478 Entry::Vacant(_) => unreachable!(),
479 Entry::Occupied(view) => {
480 assert_eq!(view.remove(), C(30));
481 }
482 }
483 assert_eq!(map.get::<C>(), None);
484 assert_eq!(map.len(), 5);
485
486
487 // Inexistent key (insert)
488 match map.entry::<J>() {
489 Entry::Occupied(_) => unreachable!(),
490 Entry::Vacant(view) => {
491 assert_eq!(*view.insert(J(1000)), J(1000));
492 }
493 }
494 assert_eq!(map.get::<J>().unwrap(), &J(1000));
495 assert_eq!(map.len(), 6);
496
497 // Entry.or_insert on existing key
498 map.entry::<B>().or_insert(B(71)).0 += 1;
499 assert_eq!(map.get::<B>().unwrap(), &B(201));
500 assert_eq!(map.len(), 6);
501
502 // Entry.or_insert on nonexisting key
503 map.entry::<C>().or_insert(C(300)).0 += 1;
504 assert_eq!(map.get::<C>().unwrap(), &C(301));
505 assert_eq!(map.len(), 7);
506 }
507 }
508 }
509
510 test_entry!(test_entry_any, AnyMap);
511 test_entry!(test_entry_cloneany, Map<dyn CloneAny>);
512
513 #[test]
514 fn test_default() {
515 let map: AnyMap = Default::default();
516 assert_eq!(map.len(), 0);
517 }
518
519 #[test]
520 fn test_clone() {
521 let mut map: Map<dyn CloneAny> = Map::new();
522 let _ = map.insert(A(1));
523 let _ = map.insert(B(2));
524 let _ = map.insert(D(3));
525 let _ = map.insert(E(4));
526 let _ = map.insert(F(5));
527 let _ = map.insert(J(6));
528 let map2 = map.clone();
529 assert_eq!(map2.len(), 6);
530 assert_eq!(map2.get::<A>(), Some(&A(1)));
531 assert_eq!(map2.get::<B>(), Some(&B(2)));
532 assert_eq!(map2.get::<C>(), None);
533 assert_eq!(map2.get::<D>(), Some(&D(3)));
534 assert_eq!(map2.get::<E>(), Some(&E(4)));
535 assert_eq!(map2.get::<F>(), Some(&F(5)));
536 assert_eq!(map2.get::<J>(), Some(&J(6)));
537 }
538
539 #[test]
540 fn test_varieties() {
541 fn assert_send<T: Send>() { }
542 fn assert_sync<T: Sync>() { }
543 fn assert_clone<T: Clone>() { }
544 fn assert_debug<T: ::core::fmt::Debug>() { }
545 assert_send::<Map<dyn Any + Send>>();
546 assert_send::<Map<dyn Any + Send + Sync>>();
547 assert_sync::<Map<dyn Any + Send + Sync>>();
548 assert_debug::<Map<dyn Any>>();
549 assert_debug::<Map<dyn Any + Send>>();
550 assert_debug::<Map<dyn Any + Send + Sync>>();
551 assert_send::<Map<dyn CloneAny + Send>>();
552 assert_send::<Map<dyn CloneAny + Send + Sync>>();
553 assert_sync::<Map<dyn CloneAny + Send + Sync>>();
554 assert_clone::<Map<dyn CloneAny + Send>>();
555 assert_clone::<Map<dyn CloneAny + Send + Sync>>();
556 assert_clone::<Map<dyn CloneAny + Send + Sync>>();
557 assert_debug::<Map<dyn CloneAny>>();
558 assert_debug::<Map<dyn CloneAny + Send>>();
559 assert_debug::<Map<dyn CloneAny + Send + Sync>>();
560 }
561
562 #[test]
563 fn test_extend() {
564 let mut map = AnyMap::new();
565 // (vec![] for 1.36.0 compatibility; more recently, you should use [] instead.)
566 #[cfg(not(feature = "std"))]
567 use alloc::vec;
568 map.extend(vec![Box::new(123) as Box<dyn Any>, Box::new(456), Box::new(true)]);
569 assert_eq!(map.get(), Some(&456));
570 assert_eq!(map.get::<bool>(), Some(&true));
571 assert!(map.get::<Box<dyn Any>>().is_none());
572 }
573 }
574 };
575 }
576
577 #[cfg(feature = "std")]
578 everything!(
579 "let mut data = anymap::AnyMap::new();",
580 std::collections
581 );
582
583 #[cfg(feature = "hashbrown")]
584 /// AnyMap backed by `hashbrown`.
585 ///
586 /// This depends on the `hashbrown` Cargo feature being enabled.
587 pub mod hashbrown {
588 use crate::TypeIdHasher;
589 #[cfg(doc)]
590 use crate::any::CloneAny;
591
592 everything!(
593 "let mut data = anymap::hashbrown::AnyMap::new();",
594 hashbrown,
595 BuildHasherDefault<TypeIdHasher>
596 );
597 }
598
599 /// A hasher designed to eke a little more speed out, given `TypeId`’s known characteristics.
600 ///
601 /// Specifically, this is a no-op hasher that expects to be fed a u64’s worth of
602 /// randomly-distributed bits. It works well for `TypeId` (eliminating start-up time, so that my
603 /// get_missing benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
604 /// that my insert_and_get_on_260_types benchmark is ~12μs instead of ~21.5μs), but will
605 /// panic in debug mode and always emit zeros in release mode for any other sorts of inputs, so
606 /// yeah, don’t use it! 😀
607 #[derive(Default)]
608 pub struct TypeIdHasher {
609 value: u64,
610 }
611
612 impl Hasher for TypeIdHasher {
613 #[inline]
614 fn write(&mut self, bytes: &[u8]) {
615 // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
616 // that changing, but I don’t want to depend on something that isn’t expressly part of the
617 // contract for safety. But I’m OK with release builds putting everything in one bucket
618 // if it *did* change (and debug builds panicking).
619 debug_assert_eq!(bytes.len(), 8);
620 let _ = bytes.try_into()
621 .map(|array| self.value = u64::from_ne_bytes(array));
622 }
623
624 #[inline]
625 fn finish(&self) -> u64 { self.value }
626 }
627
628 #[test]
629 fn type_id_hasher() {
630 #[cfg(not(feature = "std"))]
631 use alloc::vec::Vec;
632 use core::hash::Hash;
633 use core::any::TypeId;
634 fn verify_hashing_with(type_id: TypeId) {
635 let mut hasher = TypeIdHasher::default();
636 type_id.hash(&mut hasher);
637 // SAFETY: u64 is valid for all bit patterns.
638 assert_eq!(hasher.finish(), unsafe { core::mem::transmute::<TypeId, u64>(type_id) });
639 }
640 // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
641 verify_hashing_with(TypeId::of::<usize>());
642 verify_hashing_with(TypeId::of::<()>());
643 verify_hashing_with(TypeId::of::<str>());
644 verify_hashing_with(TypeId::of::<&str>());
645 verify_hashing_with(TypeId::of::<Vec<u8>>());
646 }