no_std support
[anymap] / src / raw.rs
index dbd5e2cb120e2bf8700754ed87dfa925e7853da1..081edd4bd2845400f1f3ad00ea23e9d33167362c 100644 (file)
@@ -2,16 +2,20 @@
 //!
 //! All relevant details are in the `RawMap` struct.
 
-use std::any::TypeId;
-use std::borrow::Borrow;
+use core::any::{Any, TypeId};
+use core::borrow::Borrow;
+#[cfg(all(feature = "std", not(feature = "hashbrown")))]
 use std::collections::hash_map::{self, HashMap};
-use std::hash::Hash;
-use std::hash::{Hasher, BuildHasherDefault};
-#[cfg(test)]
-use std::mem;
-use std::ops::{Index, IndexMut};
+#[cfg(feature = "hashbrown")]
+use hashbrown::hash_map::{self, HashMap};
+#[cfg(not(feature = "std"))]
+use alloc::boxed::Box;
+use core::convert::TryInto;
+use core::hash::Hash;
+use core::hash::{Hasher, BuildHasherDefault};
+use core::ops::{Index, IndexMut};
 
-use any::{Any, UncheckedAnyExt};
+use crate::any::UncheckedAnyExt;
 
 #[derive(Default)]
 struct TypeIdHasher {
@@ -21,12 +25,13 @@ struct TypeIdHasher {
 impl Hasher for TypeIdHasher {
     #[inline]
     fn write(&mut self, bytes: &[u8]) {
-        // This expects to receive one and exactly one 64-bit value
-        assert!(bytes.len() == 8);
-        self.value = u64::from(bytes[0])       | u64::from(bytes[1]) << 8  |
-                     u64::from(bytes[2]) << 16 | u64::from(bytes[3]) << 24 |
-                     u64::from(bytes[4]) << 32 | u64::from(bytes[5]) << 40 |
-                     u64::from(bytes[6]) << 48 | u64::from(bytes[7]) << 56;
+        // This expects to receive exactly one 64-bit value, and there’s no realistic chance of
+        // that changing, but I don’t want to depend on something that isn’t expressly part of the
+        // contract for safety. But I’m OK with release builds putting everything in one bucket
+        // if it *did* change (and debug builds panicking).
+        debug_assert_eq!(bytes.len(), 8);
+        let _ = bytes.try_into()
+            .map(|array| self.value = u64::from_ne_bytes(array));
     }
 
     #[inline]
@@ -35,10 +40,13 @@ impl Hasher for TypeIdHasher {
 
 #[test]
 fn type_id_hasher() {
+    #[cfg(not(feature = "std"))]
+    use alloc::vec::Vec;
     fn verify_hashing_with(type_id: TypeId) {
         let mut hasher = TypeIdHasher::default();
         type_id.hash(&mut hasher);
-        assert_eq!(hasher.finish(), unsafe { mem::transmute::<TypeId, u64>(type_id) });
+        // SAFETY: u64 is valid for all bit patterns.
+        assert_eq!(hasher.finish(), unsafe { core::mem::transmute::<TypeId, u64>(type_id) });
     }
     // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
     verify_hashing_with(TypeId::of::<usize>());
@@ -56,7 +64,7 @@ fn type_id_hasher() {
 /// contents of an `Map`. However, because you will then be dealing with `Any` trait objects, it
 /// doesn’t tend to be so very useful. Still, if you need it, it’s here.
 #[derive(Debug)]
-pub struct RawMap<A: ?Sized + UncheckedAnyExt = Any> {
+pub struct RawMap<A: ?Sized + UncheckedAnyExt = dyn Any> {
     inner: HashMap<TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
 }
 
@@ -206,10 +214,11 @@ impl<A: ?Sized + UncheckedAnyExt> RawMap<A> {
     }
 
     /// Inserts a key-value pair from the map. If the key already had a value present in the map,
-    /// that value is returned. Otherwise, None is returned.
+    /// that value is returned. Otherwise, `None` is returned.
     ///
-    /// It is the caller’s responsibility to ensure that the key corresponds with the type ID of
-    /// the value. If they do not, memory safety may be violated.
+    /// # Safety
+    ///
+    /// `key` and the type ID of `value` must match, or *undefined behaviour* occurs.
     #[inline]
     pub unsafe fn insert(&mut self, key: TypeId, value: Box<A>) -> Option<Box<A>> {
         self.inner.insert(key, value)
@@ -258,12 +267,18 @@ impl<A: ?Sized + UncheckedAnyExt> IntoIterator for RawMap<A> {
 
 /// A view into a single occupied location in a `RawMap`.
 pub struct OccupiedEntry<'a, A: ?Sized + UncheckedAnyExt> {
+    #[cfg(all(feature = "std", not(feature = "hashbrown")))]
     inner: hash_map::OccupiedEntry<'a, TypeId, Box<A>>,
+    #[cfg(feature = "hashbrown")]
+    inner: hash_map::OccupiedEntry<'a, TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
 }
 
 /// A view into a single empty location in a `RawMap`.
 pub struct VacantEntry<'a, A: ?Sized + UncheckedAnyExt> {
+    #[cfg(all(feature = "std", not(feature = "hashbrown")))]
     inner: hash_map::VacantEntry<'a, TypeId, Box<A>>,
+    #[cfg(feature = "hashbrown")]
+    inner: hash_map::VacantEntry<'a, TypeId, Box<A>, BuildHasherDefault<TypeIdHasher>>,
 }
 
 /// A view into a single location in a `RawMap`, which may be vacant or occupied.
@@ -278,8 +293,9 @@ impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> {
     /// Ensures a value is in the entry by inserting the default if empty, and returns
     /// a mutable reference to the value in the entry.
     ///
-    /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
-    /// the type ID of `value`. If they do not, memory safety may be violated.
+    /// # Safety
+    ///
+    /// The type ID of `default` must match the entry’s key, or *undefined behaviour* occurs.
     #[inline]
     pub unsafe fn or_insert(self, default: Box<A>) -> &'a mut A {
         match self {
@@ -291,8 +307,10 @@ impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> {
     /// Ensures a value is in the entry by inserting the result of the default function if empty,
     /// and returns a mutable reference to the value in the entry.
     ///
-    /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
-    /// the type ID of `value`. If they do not, memory safety may be violated.
+    /// # Safety
+    ///
+    /// The type ID of the value returned by `default` must match the entry’s key,
+    /// or *undefined behaviour* occurs.
     #[inline]
     pub unsafe fn or_insert_with<F: FnOnce() -> Box<A>>(self, default: F) -> &'a mut A {
         match self {
@@ -324,8 +342,9 @@ impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> {
 
     /// Sets the value of the entry, and returns the entry's old value.
     ///
-    /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
-    /// the type ID of `value`. If they do not, memory safety may be violated.
+    /// # Safety
+    ///
+    /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
     #[inline]
     pub unsafe fn insert(&mut self, value: Box<A>) -> Box<A> {
         self.inner.insert(value)
@@ -340,10 +359,11 @@ impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> {
 
 impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> {
     /// Sets the value of the entry with the VacantEntry's key,
-    /// and returns a mutable reference to it
+    /// and returns a mutable reference to it.
+    ///
+    /// # Safety
     ///
-    /// It is the caller’s responsibility to ensure that the key of the entry corresponds with
-    /// the type ID of `value`. If they do not, memory safety may be violated.
+    /// The type ID of `value` must match the entry’s key, or *undefined behaviour* occurs.
     #[inline]
     pub unsafe fn insert(self, value: Box<A>) -> &'a mut A {
         &mut **self.inner.insert(value)