From 839a6bc6e842b2ae6bbaf4b945ff6f2fbbca1785 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Sat, 11 Jun 2016 09:30:24 +1000 Subject: [PATCH 01/16] Remove superfluous Clone bound on Entry methods. Thanks to @Kimundi for pointing this out. I presume (without checking) that they got added along with the CloneAny stuff by accident. Closes #26. --- src/lib.rs | 127 ++++++++++++++++++++++++++++------------------------- 1 file changed, 67 insertions(+), 60 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7619367..5f21a94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -233,7 +233,7 @@ pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> { Vacant(VacantEntry<'a, A, V>), } -impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox + Clone> Entry<'a, A, V> { +impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> Entry<'a, A, V> { /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. pub fn or_insert(self, default: V) -> &'a mut V { @@ -337,73 +337,80 @@ mod tests { #[derive(Clone, Debug, PartialEq)] struct F(i32); #[derive(Clone, Debug, PartialEq)] struct J(i32); - #[test] - fn test_entry() { - let mut map: AnyMap = AnyMap::new(); - assert_eq!(map.insert(A(10)), None); - assert_eq!(map.insert(B(20)), None); - assert_eq!(map.insert(C(30)), None); - assert_eq!(map.insert(D(40)), None); - assert_eq!(map.insert(E(50)), None); - assert_eq!(map.insert(F(60)), None); - - // Existing key (insert) - match map.entry::() { - Entry::Vacant(_) => unreachable!(), - Entry::Occupied(mut view) => { - assert_eq!(view.get(), &A(10)); - assert_eq!(view.insert(A(100)), A(10)); - } - } - assert_eq!(map.get::().unwrap(), &A(100)); - assert_eq!(map.len(), 6); - - - // Existing key (update) - match map.entry::() { - Entry::Vacant(_) => unreachable!(), - Entry::Occupied(mut view) => { - let v = view.get_mut(); - let new_v = B(v.0 * 10); - *v = new_v; - } - } - assert_eq!(map.get::().unwrap(), &B(200)); - assert_eq!(map.len(), 6); + macro_rules! test_entry { + ($name:ident, $init:ty) => { + #[test] + fn $name() { + let mut map = <$init>::new(); + assert_eq!(map.insert(A(10)), None); + assert_eq!(map.insert(B(20)), None); + assert_eq!(map.insert(C(30)), None); + assert_eq!(map.insert(D(40)), None); + assert_eq!(map.insert(E(50)), None); + assert_eq!(map.insert(F(60)), None); + + // Existing key (insert) + match map.entry::() { + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(mut view) => { + assert_eq!(view.get(), &A(10)); + assert_eq!(view.insert(A(100)), A(10)); + } + } + assert_eq!(map.get::().unwrap(), &A(100)); + assert_eq!(map.len(), 6); + + + // Existing key (update) + match map.entry::() { + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(mut view) => { + let v = view.get_mut(); + let new_v = B(v.0 * 10); + *v = new_v; + } + } + assert_eq!(map.get::().unwrap(), &B(200)); + assert_eq!(map.len(), 6); - // Existing key (remove) - match map.entry::() { - Entry::Vacant(_) => unreachable!(), - Entry::Occupied(view) => { - assert_eq!(view.remove(), C(30)); - } - } - assert_eq!(map.get::(), None); - assert_eq!(map.len(), 5); + // Existing key (remove) + match map.entry::() { + Entry::Vacant(_) => unreachable!(), + Entry::Occupied(view) => { + assert_eq!(view.remove(), C(30)); + } + } + assert_eq!(map.get::(), None); + assert_eq!(map.len(), 5); - // Inexistent key (insert) - match map.entry::() { - Entry::Occupied(_) => unreachable!(), - Entry::Vacant(view) => { - assert_eq!(*view.insert(J(1000)), J(1000)); + // Inexistent key (insert) + match map.entry::() { + Entry::Occupied(_) => unreachable!(), + Entry::Vacant(view) => { + assert_eq!(*view.insert(J(1000)), J(1000)); + } + } + assert_eq!(map.get::().unwrap(), &J(1000)); + assert_eq!(map.len(), 6); + + // Entry.or_insert on existing key + map.entry::().or_insert(B(71)).0 += 1; + assert_eq!(map.get::().unwrap(), &B(201)); + assert_eq!(map.len(), 6); + + // Entry.or_insert on nonexisting key + map.entry::().or_insert(C(300)).0 += 1; + assert_eq!(map.get::().unwrap(), &C(301)); + assert_eq!(map.len(), 7); } } - assert_eq!(map.get::().unwrap(), &J(1000)); - assert_eq!(map.len(), 6); - - // Entry.or_insert on existing key - map.entry::().or_insert(B(71)).0 += 1; - assert_eq!(map.get::().unwrap(), &B(201)); - assert_eq!(map.len(), 6); - - // Entry.or_insert on nonexisting key - map.entry::().or_insert(C(300)).0 += 1; - assert_eq!(map.get::().unwrap(), &C(301)); - assert_eq!(map.len(), 7); } + test_entry!(test_entry_any, AnyMap); + test_entry!(test_entry_cloneany, Map); + #[test] fn test_clone() { let mut map: Map = Map::new(); -- 2.50.1 From 0c3026f7dec56e013478d896e1a088d10bdc0411 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Sat, 11 Jun 2016 10:06:13 +1000 Subject: [PATCH 02/16] Add more benchmarking Including a rustc/llvm pathalogical case. --- src/lib.rs | 124 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 94 insertions(+), 30 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5f21a94..15a21bc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -289,39 +289,103 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> VacantEntry<'a, A, V> { } } -#[cfg(feature = "bench")] -#[bench] -fn bench_insertion(b: &mut ::test::Bencher) { - b.iter(|| { - let mut data = AnyMap::new(); - for _ in 0..100 { +#[cfg(all(feature = "bench", test))] +mod bench { + use AnyMap; + use test::Bencher; + + #[bench] + fn insertion(b: &mut Bencher) { + b.iter(|| { + let mut data = AnyMap::new(); + for _ in 0..100 { + let _ = data.insert(42); + } + }) + } + + #[bench] + fn get_missing(b: &mut Bencher) { + b.iter(|| { + let data = AnyMap::new(); + for _ in 0..100 { + assert_eq!(data.get(), None::<&i32>); + } + }) + } + + #[bench] + fn get_present(b: &mut Bencher) { + b.iter(|| { + let mut data = AnyMap::new(); let _ = data.insert(42); - } - }) -} + // These inner loops are a feeble attempt to drown the other factors. + for _ in 0..100 { + assert_eq!(data.get(), Some(&42)); + } + }) + } -#[cfg(feature = "bench")] -#[bench] -fn bench_get_missing(b: &mut ::test::Bencher) { - b.iter(|| { - let data = AnyMap::new(); - for _ in 0..100 { - assert_eq!(data.get(), None::<&i32>); - } - }) -} + macro_rules! big_benchmarks { + ($name:ident, $($T:ident)*) => ( + #[bench] + fn $name(b: &mut Bencher) { + $( + #[derive(Debug, PartialEq)] + struct $T(&'static str); + + impl Default for $T { + fn default() -> $T { + $T(stringify!($T)) + } + } + )* + + b.iter(|| { + let mut data = AnyMap::new(); + $( + assert_eq!(data.insert($T::default()), None::<$T>); + )* + $( + assert_eq!(data.get(), Some(&$T::default())); + )* + }) + } + ); + } -#[cfg(feature = "bench")] -#[bench] -fn bench_get_present(b: &mut ::test::Bencher) { - b.iter(|| { - let mut data = AnyMap::new(); - let _ = data.insert(42); - // These inner loops are a feeble attempt to drown the other factors. - for _ in 0..100 { - assert_eq!(data.get(), Some(&42)); - } - }) + // Pathalogical rustc/llvm case here. This takes *absurdly* long to compile (it adds something + // like 100 seconds), peaking at over 1GB of RAM (though -Z time-passes doesn’t pick up on + // that, as it’s in the middle of the “llvm modules passes [0]” that it happens and it’s all + // freed at the end of that pass) and adding over 700KB to the final build. (3KB per type is + // more than I expected, reasonably or unreasonably.) TODO determine why and get it fixed. + // + // Selected rustc -Z time-passes output, with and without this block: + // + // - item-bodies checking: 0.4 seconds without, 5.2 seconds with; + // - borrow checking: 0.1 seconds without, 11 seconds with; + // - llvm module passes [0]: 2.5 seconds without, 49 seconds with; + // - codegen passes [0]: 0.6 seconds without, 11.2 seconds with. + // + // Very not good. + big_benchmarks! { + insert_and_get_on_260_types, + A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0 Q0 R0 S0 T0 U0 V0 W0 X0 Y0 Z0 + A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1 Q1 R1 S1 T1 U1 V1 W1 X1 Y1 Z1 + A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2 Q2 R2 S2 T2 U2 V2 W2 X2 Y2 Z2 + A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3 Q3 R3 S3 T3 U3 V3 W3 X3 Y3 Z3 + A4 B4 C4 D4 E4 F4 G4 H4 I4 J4 K4 L4 M4 N4 O4 P4 Q4 R4 S4 T4 U4 V4 W4 X4 Y4 Z4 + A5 B5 C5 D5 E5 F5 G5 H5 I5 J5 K5 L5 M5 N5 O5 P5 Q5 R5 S5 T5 U5 V5 W5 X5 Y5 Z5 + A6 B6 C6 D6 E6 F6 G6 H6 I6 J6 K6 L6 M6 N6 O6 P6 Q6 R6 S6 T6 U6 V6 W6 X6 Y6 Z6 + A7 B7 C7 D7 E7 F7 G7 H7 I7 J7 K7 L7 M7 N7 O7 P7 Q7 R7 S7 T7 U7 V7 W7 X7 Y7 Z7 + A8 B8 C8 D8 E8 F8 G8 H8 I8 J8 K8 L8 M8 N8 O8 P8 Q8 R8 S8 T8 U8 V8 W8 X8 Y8 Z8 + A9 B9 C9 D9 E9 F9 G9 H9 I9 J9 K9 L9 M9 N9 O9 P9 Q9 R9 S9 T9 U9 V9 W9 X9 Y9 Z9 + } + + big_benchmarks! { + insert_and_get_on_26_types, + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z + } } #[cfg(test)] -- 2.50.1 From c52281b376938163f91f351f84877346381cec82 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Sat, 11 Jun 2016 10:46:30 +1000 Subject: [PATCH 03/16] Use raw pointers for downcasting, not TraitObject This mirrors a change in mopa. --- src/any.rs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/any.rs b/src/any.rs index 87028fb..4120e6a 100644 --- a/src/any.rs +++ b/src/any.rs @@ -3,7 +3,6 @@ //! This stuff is all based on `std::any`, but goes a little further, with `CloneAny` being a //! cloneable `Any` and with the `Send` and `Sync` bounds possible on both `Any` and `CloneAny`. -use std::mem; use std::fmt; use std::any::Any as StdAny; @@ -88,17 +87,6 @@ macro_rules! impl_clone { } } -#[cfg(feature = "unstable")] -use std::raw::TraitObject; - -#[cfg(not(feature = "unstable"))] -#[repr(C)] -#[derive(Copy, Clone)] -struct TraitObject { - pub data: *mut (), - pub vtable: *mut (), -} - #[allow(missing_docs)] // Bogus warning (it’s not public outside the crate), ☹ pub trait UncheckedAnyExt: Any { unsafe fn downcast_ref_unchecked(&self) -> &T; @@ -123,15 +111,15 @@ macro_rules! implement { impl UncheckedAnyExt for $base $(+ $bounds)* { unsafe fn downcast_ref_unchecked(&self) -> &T { - mem::transmute(mem::transmute::<_, TraitObject>(self).data) + &*(self as *const Self as *const T) } unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { - mem::transmute(mem::transmute::<_, TraitObject>(self).data) + &mut *(self as *mut Self as *mut T) } unsafe fn downcast_unchecked(self: Box) -> Box { - mem::transmute(mem::transmute::<_, TraitObject>(self).data) + Box::from_raw(Box::into_raw(self) as *mut T) } } -- 2.50.1 From ec57ec49be65359fe10b09b9d2130e7a9481020b Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Sat, 11 Jun 2016 13:28:30 +1000 Subject: [PATCH 04/16] Reduce the work for rustc in the benchmarks. MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit This *does* mean that they no longer function as tests, which was deliberate, but rustc is just too slow with the assertions in there as well. If I care, I can make variants of it that actually test. For now, I’m sufficiently happy with it. --- src/lib.rs | 29 ++++++----------------------- 1 file changed, 6 insertions(+), 23 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 15a21bc..d2b85aa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -293,6 +293,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> VacantEntry<'a, A, V> { mod bench { use AnyMap; use test::Bencher; + use test::black_box; #[bench] fn insertion(b: &mut Bencher) { @@ -331,43 +332,25 @@ mod bench { #[bench] fn $name(b: &mut Bencher) { $( - #[derive(Debug, PartialEq)] struct $T(&'static str); - - impl Default for $T { - fn default() -> $T { - $T(stringify!($T)) - } - } )* b.iter(|| { let mut data = AnyMap::new(); $( - assert_eq!(data.insert($T::default()), None::<$T>); + let _ = black_box(data.insert($T(stringify!($T)))); )* $( - assert_eq!(data.get(), Some(&$T::default())); + let _ = black_box(data.get::<$T>()); )* }) } ); } - // Pathalogical rustc/llvm case here. This takes *absurdly* long to compile (it adds something - // like 100 seconds), peaking at over 1GB of RAM (though -Z time-passes doesn’t pick up on - // that, as it’s in the middle of the “llvm modules passes [0]” that it happens and it’s all - // freed at the end of that pass) and adding over 700KB to the final build. (3KB per type is - // more than I expected, reasonably or unreasonably.) TODO determine why and get it fixed. - // - // Selected rustc -Z time-passes output, with and without this block: - // - // - item-bodies checking: 0.4 seconds without, 5.2 seconds with; - // - borrow checking: 0.1 seconds without, 11 seconds with; - // - llvm module passes [0]: 2.5 seconds without, 49 seconds with; - // - codegen passes [0]: 0.6 seconds without, 11.2 seconds with. - // - // Very not good. + // Caution: if the macro does too much (e.g. assertions) this goes from being slow to being + // *really* slow (like add a minute for each assertion on it) and memory-hungry (like, adding + // several hundred megabytes to the peak for each assertion). big_benchmarks! { insert_and_get_on_260_types, A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0 Q0 R0 S0 T0 U0 V0 W0 X0 Y0 Z0 -- 2.50.1 From b549457d628fb178f6d700d85800f3ab63482d63 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Sat, 11 Jun 2016 13:30:33 +1000 Subject: [PATCH 05/16] Put in a bunch of #[inline] attributes on fns. MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Somewhere along the path I didn’t mark some functions as `#[inline]` which they should probably be. Small but visible benchmark improvements, but within ε so low confidence. --- src/any.rs | 10 ++++++++++ src/lib.rs | 17 +++++++++++++++++ src/raw.rs | 19 +++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/src/any.rs b/src/any.rs index 4120e6a..976f768 100644 --- a/src/any.rs +++ b/src/any.rs @@ -22,18 +22,22 @@ pub trait CloneToAny { } impl CloneToAny for T { + #[inline] fn clone_to_any(&self) -> Box { Box::new(self.clone()) } + #[inline] fn clone_to_any_send(&self) -> Box where Self: Send { Box::new(self.clone()) } + #[inline] fn clone_to_any_sync(&self) -> Box where Self: Sync { Box::new(self.clone()) } + #[inline] fn clone_to_any_send_sync(&self) -> Box where Self: Send + Sync { Box::new(self.clone()) } @@ -80,6 +84,7 @@ macro_rules! define { macro_rules! impl_clone { ($t:ty, $method:ident) => { impl Clone for Box<$t> { + #[inline] fn clone(&self) -> Box<$t> { (**self).$method() } @@ -104,26 +109,31 @@ pub trait IntoBox: Any { macro_rules! implement { ($base:ident, $(+ $bounds:ident)*) => { impl fmt::Debug for $base $(+ $bounds)* { + #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(stringify!($base $(+ $bounds)*)) } } impl UncheckedAnyExt for $base $(+ $bounds)* { + #[inline] unsafe fn downcast_ref_unchecked(&self) -> &T { &*(self as *const Self as *const T) } + #[inline] unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { &mut *(self as *mut Self as *mut T) } + #[inline] unsafe fn downcast_unchecked(self: Box) -> Box { Box::from_raw(Box::into_raw(self) as *mut T) } } impl IntoBox<$base $(+ $bounds)*> for T { + #[inline] fn into_box(self) -> Box<$base $(+ $bounds)*> { Box::new(self) } diff --git a/src/lib.rs b/src/lib.rs index d2b85aa..d41c335 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,6 +123,7 @@ pub struct Map { // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box that can. impl Clone for Map where Box: Clone { + #[inline] fn clone(&self) -> Map { Map { raw: self.raw.clone(), @@ -145,6 +146,7 @@ impl_common_methods! { impl Map { /// Returns a reference to the value stored in the collection for the type `T`, if it exists. + #[inline] pub fn get>(&self) -> Option<&T> { self.raw.get(&TypeId::of::()) .map(|any| unsafe { any.downcast_ref_unchecked::() }) @@ -152,6 +154,7 @@ impl Map { /// Returns a mutable reference to the value stored in the collection for the type `T`, /// if it exists. + #[inline] pub fn get_mut>(&mut self) -> Option<&mut T> { self.raw.get_mut(&TypeId::of::()) .map(|any| unsafe { any.downcast_mut_unchecked::() }) @@ -160,6 +163,7 @@ impl Map { /// 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. + #[inline] pub fn insert>(&mut self, value: T) -> Option { unsafe { self.raw.insert(TypeId::of::(), value.into_box()) @@ -169,6 +173,7 @@ impl Map { /// Removes the `T` value from the collection, /// returning it if there was one or `None` if there was not. + #[inline] pub fn remove>(&mut self) -> Option { self.raw.remove(&TypeId::of::()) .map(|any| *unsafe { any.downcast_unchecked::() }) @@ -181,6 +186,7 @@ impl Map { } /// Gets the entry for the given type in the collection for in-place manipulation + #[inline] pub fn entry>(&mut self) -> Entry { match self.raw.entry(TypeId::of::()) { raw::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { @@ -196,18 +202,21 @@ impl Map { } impl AsRef> for Map { + #[inline] fn as_ref(&self) -> &RawMap { &self.raw } } impl AsMut> for Map { + #[inline] fn as_mut(&mut self) -> &mut RawMap { &mut self.raw } } impl Into> for Map { + #[inline] fn into(self) -> RawMap { self.raw } @@ -236,6 +245,7 @@ pub enum Entry<'a, A: ?Sized + UncheckedAnyExt, V: 'a> { impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> Entry<'a, A, V> { /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. + #[inline] pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(inner) => inner.into_mut(), @@ -245,6 +255,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> Entry<'a, A, V> { /// 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. + #[inline] pub fn or_insert_with V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(inner) => inner.into_mut(), @@ -255,27 +266,32 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> Entry<'a, A, V> { impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> OccupiedEntry<'a, A, V> { /// Gets a reference to the value in the entry + #[inline] pub fn get(&self) -> &V { unsafe { self.inner.get().downcast_ref_unchecked() } } /// Gets a mutable reference to the value in the entry + #[inline] pub fn get_mut(&mut self) -> &mut V { unsafe { self.inner.get_mut().downcast_mut_unchecked() } } /// Converts the OccupiedEntry into a mutable reference to the value in the entry /// with a lifetime bound to the collection itself + #[inline] pub fn into_mut(self) -> &'a mut V { unsafe { self.inner.into_mut().downcast_mut_unchecked() } } /// Sets the value of the entry, and returns the entry's old value + #[inline] pub fn insert(&mut self, value: V) -> V { unsafe { *self.inner.insert(value.into_box()).downcast_unchecked() } } /// Takes the value out of the entry, and returns it + #[inline] pub fn remove(self) -> V { unsafe { *self.inner.remove().downcast_unchecked() } } @@ -284,6 +300,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> OccupiedEntry<'a, A, V> { impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> VacantEntry<'a, A, V> { /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it + #[inline] pub fn insert(self, value: V) -> &'a mut V { unsafe { self.inner.insert(value.into_box()).downcast_mut_unchecked() } } diff --git a/src/raw.rs b/src/raw.rs index 3645429..7d53783 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -61,6 +61,7 @@ pub struct RawMap { // #[derive(Clone)] would want A to implement Clone, but in reality it’s only Box that can. impl Clone for RawMap where Box: Clone { + #[inline] fn clone(&self) -> RawMap { RawMap { inner: self.inner.clone(), @@ -69,6 +70,7 @@ impl Clone for RawMap where Box: Clone { } impl Default for RawMap { + #[inline] fn default() -> RawMap { RawMap::new() } @@ -167,6 +169,7 @@ impl RawMap { } /// Gets the entry for the given type in the collection for in-place manipulation. + #[inline] pub fn entry(&mut self, key: TypeId) -> Entry { match self.inner.entry(key) { hash_map::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry { @@ -182,6 +185,7 @@ impl RawMap { /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. + #[inline] pub fn get(&self, k: &Q) -> Option<&A> where TypeId: Borrow, Q: Hash + Eq { self.inner.get(k).map(|x| &**x) @@ -191,6 +195,7 @@ impl RawMap { /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. + #[inline] pub fn contains_key(&self, k: &Q) -> bool where TypeId: Borrow, Q: Hash + Eq { self.inner.contains_key(k) @@ -200,6 +205,7 @@ impl RawMap { /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. + #[inline] pub fn get_mut(&mut self, k: &Q) -> Option<&mut A> where TypeId: Borrow, Q: Hash + Eq { self.inner.get_mut(k).map(|x| &mut **x) @@ -210,6 +216,7 @@ impl RawMap { /// /// 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. + #[inline] pub unsafe fn insert(&mut self, key: TypeId, value: Box) -> Option> { self.inner.insert(key, value) } @@ -219,6 +226,7 @@ impl RawMap { /// /// The key may be any borrowed form of the map's key type, but `Hash` and `Eq` on the borrowed /// form *must* match those for the key type. + #[inline] pub fn remove(&mut self, k: &Q) -> Option> where TypeId: Borrow, Q: Hash + Eq { self.inner.remove(k) @@ -229,12 +237,14 @@ impl RawMap { impl Index for RawMap where TypeId: Borrow, Q: Eq + Hash { type Output = A; + #[inline] fn index(&self, index: Q) -> &A { self.get(&index).expect("no entry found for key") } } impl IndexMut for RawMap where TypeId: Borrow, Q: Eq + Hash { + #[inline] fn index_mut(&mut self, index: Q) -> &mut A { self.get_mut(&index).expect("no entry found for key") } @@ -244,6 +254,7 @@ impl IntoIterator for RawMap { type Item = Box; type IntoIter = IntoIter; + #[inline] fn into_iter(self) -> IntoIter { IntoIter { inner: self.inner.into_iter(), @@ -275,6 +286,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> { /// /// 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. + #[inline] pub unsafe fn or_insert(self, default: Box) -> &'a mut A { match self { Entry::Occupied(inner) => inner.into_mut(), @@ -287,6 +299,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> { /// /// 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. + #[inline] pub unsafe fn or_insert_with Box>(self, default: F) -> &'a mut A { match self { Entry::Occupied(inner) => inner.into_mut(), @@ -297,17 +310,20 @@ impl<'a, A: ?Sized + UncheckedAnyExt> Entry<'a, A> { impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> { /// Gets a reference to the value in the entry. + #[inline] pub fn get(&self) -> &A { &**self.inner.get() } /// Gets a mutable reference to the value in the entry. + #[inline] pub fn get_mut(&mut self) -> &mut A { &mut **self.inner.get_mut() } /// Converts the OccupiedEntry into a mutable reference to the value in the entry /// with a lifetime bound to the collection itself. + #[inline] pub fn into_mut(self) -> &'a mut A { &mut **self.inner.into_mut() } @@ -316,11 +332,13 @@ impl<'a, A: ?Sized + UncheckedAnyExt> OccupiedEntry<'a, A> { /// /// 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. + #[inline] pub unsafe fn insert(&mut self, value: Box) -> Box { self.inner.insert(value) } /// Takes the value out of the entry, and returns it. + #[inline] pub fn remove(self) -> Box { self.inner.remove() } @@ -332,6 +350,7 @@ impl<'a, A: ?Sized + UncheckedAnyExt> VacantEntry<'a, A> { /// /// 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. + #[inline] pub unsafe fn insert(self, value: Box) -> &'a mut A { &mut **self.inner.insert(value) } -- 2.50.1 From 34028c35e70de959ec61758db88dfc84f75764cf Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 18:10:55 +0530 Subject: [PATCH 06/16] Make clippy happy. --- src/raw.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/raw.rs b/src/raw.rs index 7d53783..17c3869 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -7,6 +7,7 @@ use std::borrow::Borrow; 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}; use std::ptr; @@ -24,7 +25,7 @@ impl Hasher for TypeIdHasher { // This expects to receive one and exactly one 64-bit value debug_assert!(bytes.len() == 8); unsafe { - ptr::copy_nonoverlapping(mem::transmute(&bytes[0]), &mut self.value, 1) + ptr::copy_nonoverlapping(&bytes[0] as *const u8 as *const u64, &mut self.value, 1) } } -- 2.50.1 From 2173c81567778443b90c786db8db82d94158e512 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 18:13:13 +0530 Subject: [PATCH 07/16] 0.12.1 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 66eb637..39c6b77 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "anymap" -version = "0.12.0" +version = "0.12.1" authors = ["Chris Morgan "] description = "A safe and convenient store for one value of each type" #documentation = "http://www.rust-ci.org/chris-morgan/anymap/doc/anymap/index.html" -- 2.50.1 From 1374cacb410abd763f5ff6d4644b8f01b2330f3c Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 21:25:44 +0530 Subject: [PATCH 08/16] Remove obsolete rust-ci docs uploading We use docs.rs these days. No manual work in it, either. Yay! --- .travis.yml | 9 --------- Cargo.toml | 2 +- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index a2f12a9..2883852 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,15 +3,6 @@ rust: - nightly - beta - stable -env: - global: - - secure: nR+DJRUQ9v03nNZMpMu1tGKLKBAqdQsTIAr8ffdl+DUEh3b2jvQ+vLLNFLPjsloqhoOXo7cWO7qVpiE4ZOq2lNDURQjdiZGFjh/Y5+xKy2BqFdV7qQ1JoBzsMyx28tQTYz0mtBsACiCYKKb+ddNX5hpwrsjp8cS7htZktA5kbiU= script: - if [[ "$(rustc --version)" =~ -(dev|nightly) ]]; then cargo test --features bench; else ! cargo test --features bench; fi - cargo test - - cargo doc -after_script: - - ln -s target/doc doc - - curl -v http://www.rust-ci.org/artifacts/put?t=$RUSTCI_TOKEN > ./upload-docs - - cat ./upload-docs - - sh ./upload-docs diff --git a/Cargo.toml b/Cargo.toml index 39c6b77..f68b6dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "anymap" version = "0.12.1" authors = ["Chris Morgan "] description = "A safe and convenient store for one value of each type" -#documentation = "http://www.rust-ci.org/chris-morgan/anymap/doc/anymap/index.html" +documentation = "https://docs.rs/anymap" #homepage = "https://github.com/chris-morgan/anymap" repository = "https://github.com/chris-morgan/anymap" readme = "README.md" -- 2.50.1 From eae3d2231258af3b26c7e067e30452c39544b21d Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 21:28:07 +0530 Subject: [PATCH 09/16] Add a changelog. --- CHANGELOG.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a0fe8f6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,44 @@ +# 1.0.0 (unreleased) + +Nothing yet. I don’t plan for there to be any real changes from 0.12.1; +it should be just a bit of housecleaning and a version bump. + +# 0.12.1 (2017-01-20) + +- Remove superfluous Clone bound on Entry methods (#26) +- Consistent application of `#[inline]` where it should be +- Fix bad performance (see 724f94758def9f71ad27ff49e47e908a431c2728 for details) + +# 0.12.0 (2016-03-05) + +- Ungate `drain` iterator (stable from Rust 1.6.0) +- Ungate efficient hashing (stable from Rust 1.7.0) +- Remove `unstable` Cargo feature (in favour of a `bench` feature for benchmarking) + +# 0.11.2 (2016-01-22) + +- Rust warning updates only + +# 0.11.1 (2015-06-24) + +- Unstable Rust compatibility updates + +# 0.11.0 (2015-06-10) + +- Support concurrent maps (`Send + Sync` bound) +- Rename `nightly` feature to `unstable` +- Implement `Debug` for `Map` and `RawMap` +- Replace `clone` Cargo feature with arcane DST magicks + +# Older releases (from the initial code on 2014-06-12 to 0.10.3 on 2015-04-18) + +I’m not giving a changelog for these artefacts of ancient history. +If you really care you can look through the Git history easily enough. +Most of the releases were just compensating for changes to the language +(that being before Rust 1.0; yes, this crate has been around for a while). + +I do think that [`src/lib.rs` in the first commit] is a work of art, +a thing of great beauty worth looking at; its simplicity is delightful, +and it doesn’t even need to contain any unsafe code. + +[`src/lib.rs` in the first commit]: https://github.com/chris-morgan/anymap/tree/a294948f57dee47bb284d6a3ae1b8f61a902a03c/src/lib.rs -- 2.50.1 From b3811cf0d1bdab6154534eda1903c930885749ec Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 21:31:56 +0530 Subject: [PATCH 10/16] Remove the `bench` Cargo feature as superfluous MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit A better pattern is to put benchmarks in the `benches` directory; that way, `cargo test` won’t pick them up by default, and so it won’t fail on the stable and beta channels. --- .travis.yml | 3 +- CHANGELOG.md | 7 +++- Cargo.toml | 3 -- benches/bench.rs | 85 +++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 86 ------------------------------------------------ 5 files changed, 93 insertions(+), 91 deletions(-) create mode 100644 benches/bench.rs diff --git a/.travis.yml b/.travis.yml index 2883852..0b06902 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,5 +4,6 @@ rust: - beta - stable script: - - if [[ "$(rustc --version)" =~ -(dev|nightly) ]]; then cargo test --features bench; else ! cargo test --features bench; fi + - if [[ "$(rustc --version)" =~ -(dev|nightly) ]]; then cargo bench; fi - cargo test + - cargo test --release diff --git a/CHANGELOG.md b/CHANGELOG.md index a0fe8f6..9a968dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ # 1.0.0 (unreleased) -Nothing yet. I don’t plan for there to be any real changes from 0.12.1; +- Remove `bench` Cargo feature (by shifting benchmarks out of `src/lib.rs` into + `benches/bench.rs`; it still won’t run on anything but nightly, but that + don’t signify). Technically a [breaking-change], but it was something for + development only, so I’m not in the slightest bit concerned by it. + +I don’t plan for there to be any real changes from 0.12.1; it should be just a bit of housecleaning and a version bump. # 0.12.1 (2017-01-20) diff --git a/Cargo.toml b/Cargo.toml index f68b6dc..746399b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,3 @@ repository = "https://github.com/chris-morgan/anymap" readme = "README.md" keywords = ["container", "data-structure", "map"] license = "MIT/Apache-2.0" - -[features] -bench = [] diff --git a/benches/bench.rs b/benches/bench.rs new file mode 100644 index 0000000..e4c655d --- /dev/null +++ b/benches/bench.rs @@ -0,0 +1,85 @@ +#![feature(test)] + +extern crate anymap; + +extern crate test; + +use anymap::AnyMap; + +use test::Bencher; +use test::black_box; + +#[bench] +fn insertion(b: &mut Bencher) { + b.iter(|| { + let mut data = AnyMap::new(); + for _ in 0..100 { + let _ = data.insert(42); + } + }) +} + +#[bench] +fn get_missing(b: &mut Bencher) { + b.iter(|| { + let data = AnyMap::new(); + for _ in 0..100 { + assert_eq!(data.get(), None::<&i32>); + } + }) +} + +#[bench] +fn get_present(b: &mut Bencher) { + b.iter(|| { + let mut data = AnyMap::new(); + let _ = data.insert(42); + // These inner loops are a feeble attempt to drown the other factors. + for _ in 0..100 { + assert_eq!(data.get(), Some(&42)); + } + }) +} + +macro_rules! big_benchmarks { + ($name:ident, $($T:ident)*) => ( + #[bench] + fn $name(b: &mut Bencher) { + $( + struct $T(&'static str); + )* + + b.iter(|| { + let mut data = AnyMap::new(); + $( + let _ = black_box(data.insert($T(stringify!($T)))); + )* + $( + let _ = black_box(data.get::<$T>()); + )* + }) + } + ); +} + +// Caution: if the macro does too much (e.g. assertions) this goes from being slow to being +// *really* slow (like add a minute for each assertion on it) and memory-hungry (like, adding +// several hundred megabytes to the peak for each assertion). +big_benchmarks! { + insert_and_get_on_260_types, + A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0 Q0 R0 S0 T0 U0 V0 W0 X0 Y0 Z0 + A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1 Q1 R1 S1 T1 U1 V1 W1 X1 Y1 Z1 + A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2 Q2 R2 S2 T2 U2 V2 W2 X2 Y2 Z2 + A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3 Q3 R3 S3 T3 U3 V3 W3 X3 Y3 Z3 + A4 B4 C4 D4 E4 F4 G4 H4 I4 J4 K4 L4 M4 N4 O4 P4 Q4 R4 S4 T4 U4 V4 W4 X4 Y4 Z4 + A5 B5 C5 D5 E5 F5 G5 H5 I5 J5 K5 L5 M5 N5 O5 P5 Q5 R5 S5 T5 U5 V5 W5 X5 Y5 Z5 + A6 B6 C6 D6 E6 F6 G6 H6 I6 J6 K6 L6 M6 N6 O6 P6 Q6 R6 S6 T6 U6 V6 W6 X6 Y6 Z6 + A7 B7 C7 D7 E7 F7 G7 H7 I7 J7 K7 L7 M7 N7 O7 P7 Q7 R7 S7 T7 U7 V7 W7 X7 Y7 Z7 + A8 B8 C8 D8 E8 F8 G8 H8 I8 J8 K8 L8 M8 N8 O8 P8 Q8 R8 S8 T8 U8 V8 W8 X8 Y8 Z8 + A9 B9 C9 D9 E9 F9 G9 H9 I9 J9 K9 L9 M9 N9 O9 P9 Q9 R9 S9 T9 U9 V9 W9 X9 Y9 Z9 +} + +big_benchmarks! { + insert_and_get_on_26_types, + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +} diff --git a/src/lib.rs b/src/lib.rs index d41c335..bcd5c23 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,11 +1,7 @@ //! This crate provides the `AnyMap` type, a safe and convenient store for one value of each type. -#![cfg_attr(all(feature = "bench", test), feature(test))] #![warn(missing_docs, unused_results)] -#[cfg(all(feature = "bench", test))] -extern crate test; - use std::any::TypeId; use std::marker::PhantomData; @@ -306,88 +302,6 @@ impl<'a, A: ?Sized + UncheckedAnyExt, V: IntoBox> VacantEntry<'a, A, V> { } } -#[cfg(all(feature = "bench", test))] -mod bench { - use AnyMap; - use test::Bencher; - use test::black_box; - - #[bench] - fn insertion(b: &mut Bencher) { - b.iter(|| { - let mut data = AnyMap::new(); - for _ in 0..100 { - let _ = data.insert(42); - } - }) - } - - #[bench] - fn get_missing(b: &mut Bencher) { - b.iter(|| { - let data = AnyMap::new(); - for _ in 0..100 { - assert_eq!(data.get(), None::<&i32>); - } - }) - } - - #[bench] - fn get_present(b: &mut Bencher) { - b.iter(|| { - let mut data = AnyMap::new(); - let _ = data.insert(42); - // These inner loops are a feeble attempt to drown the other factors. - for _ in 0..100 { - assert_eq!(data.get(), Some(&42)); - } - }) - } - - macro_rules! big_benchmarks { - ($name:ident, $($T:ident)*) => ( - #[bench] - fn $name(b: &mut Bencher) { - $( - struct $T(&'static str); - )* - - b.iter(|| { - let mut data = AnyMap::new(); - $( - let _ = black_box(data.insert($T(stringify!($T)))); - )* - $( - let _ = black_box(data.get::<$T>()); - )* - }) - } - ); - } - - // Caution: if the macro does too much (e.g. assertions) this goes from being slow to being - // *really* slow (like add a minute for each assertion on it) and memory-hungry (like, adding - // several hundred megabytes to the peak for each assertion). - big_benchmarks! { - insert_and_get_on_260_types, - A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0 Q0 R0 S0 T0 U0 V0 W0 X0 Y0 Z0 - A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1 Q1 R1 S1 T1 U1 V1 W1 X1 Y1 Z1 - A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2 Q2 R2 S2 T2 U2 V2 W2 X2 Y2 Z2 - A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3 Q3 R3 S3 T3 U3 V3 W3 X3 Y3 Z3 - A4 B4 C4 D4 E4 F4 G4 H4 I4 J4 K4 L4 M4 N4 O4 P4 Q4 R4 S4 T4 U4 V4 W4 X4 Y4 Z4 - A5 B5 C5 D5 E5 F5 G5 H5 I5 J5 K5 L5 M5 N5 O5 P5 Q5 R5 S5 T5 U5 V5 W5 X5 Y5 Z5 - A6 B6 C6 D6 E6 F6 G6 H6 I6 J6 K6 L6 M6 N6 O6 P6 Q6 R6 S6 T6 U6 V6 W6 X6 Y6 Z6 - A7 B7 C7 D7 E7 F7 G7 H7 I7 J7 K7 L7 M7 N7 O7 P7 Q7 R7 S7 T7 U7 V7 W7 X7 Y7 Z7 - A8 B8 C8 D8 E8 F8 G8 H8 I8 J8 K8 L8 M8 N8 O8 P8 Q8 R8 S8 T8 U8 V8 W8 X8 Y8 Z8 - A9 B9 C9 D9 E9 F9 G9 H9 I9 J9 K9 L9 M9 N9 O9 P9 Q9 R9 S9 T9 U9 V9 W9 X9 Y9 Z9 - } - - big_benchmarks! { - insert_and_get_on_26_types, - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - } -} - #[cfg(test)] mod tests { use {Map, AnyMap, Entry}; -- 2.50.1 From 9e3715152fe22ffc31378e89ae7c9d555ddcf5a3 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Fri, 20 Jan 2017 21:33:45 +0530 Subject: [PATCH 11/16] Remove an obsolete note from the README --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index e1c65ac..775052e 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,6 @@ Instructions Cargo all the way: it is `anymap` on crates.io. -For users of the nightly instead of the beta of rustc there are a couple of things behind the `unstable` feature like a `drain` method on the `RawAnyMap` and a more efficient hashing technique which makes lookup in the map a tad faster. - Author ------ -- 2.50.1 From f5e887ef634cfcd5c354307ba105c616f4222c3d Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Mon, 23 Jan 2017 22:37:10 +0530 Subject: [PATCH 12/16] Add a note about unsafety. --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 775052e..629a8e3 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,26 @@ Instructions Cargo all the way: it is `anymap` on crates.io. +Unsafe code in this library +--------------------------- + +This library uses a fair bit of unsafe code for several reasons: + +- To support Any and CloneAny, unsafe code is required (because of how the `downcast` methods are defined in `impl Any` rather than being trait methods; I think this is kind of a historical detail of the structure of `std::any::Any`); if you wanted to ditch `Clone` support this unsafety could be removed. + +- In the interests of performance, skipping various checks that are unnecessary because of the invariants of the data structure (no need to check the type ID when it’s been statically ensured by being used as the hash map key) and simplifying hashing (type IDs are already good hashes, no need to mangle them through SipHash). + +It’s not possible to remove all unsafety from this library without also removing some of the functionality. Still, at the cost of the `CloneAny` functionality, the raw interface and maybe the concurrency support, you can definitely remove all unsafe code. Here’s how you could do it: + +- Remove the genericness of it all; +- Merge `anymap::raw` into the normal interface, flattening it; +- Change things like `.map(|any| unsafe { any.downcast_unchecked() })` to `.and_then(|any| any.downcast())` (performance cost: one extra superfluous type ID comparison, indirect); +- Ditch the `TypeIdHasher` since transmuting a `TypeId` is right out (cost: SIP mangling of a u64 on every access). + +Yeah, the performance costs of going safe are quite small. The more serious matters are the loss of `Clone` and maybe `Send + Sync`. + +But frankly, if you wanted to do all this it’d be easier and faster to write it from scratch. The core of the library is actually really simple and perfectly safe, as can be seen in [`src/lib.rs` in the first commit](https://github.com/chris-morgan/anymap/tree/a294948f57dee47bb284d6a3ae1b8f61a902a03c/src/lib.rs) (note that that code won’t run without a few syntactic alterations; it was from well before Rust 1.0 and has things like `Any:'static` where now we have `Any + 'static`). + Author ------ -- 2.50.1 From 0850f5ec36b14904ae452ffdfa0a2ae0ba05c854 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Mon, 2 Oct 2017 14:32:51 +1100 Subject: [PATCH 13/16] Implement Default on Map MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit It was implemented on RawMap, and I’m not sure quite why it wasn’t implemented on Map. I can’t think of any reason *not* to, though, so we might as well. Closes #30. Thanks to Maxwell Koo for the fix. --- CHANGELOG.md | 2 ++ src/lib.rs | 13 +++++++++++++ src/raw.rs | 7 ------- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a968dc..9691d8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ don’t signify). Technically a [breaking-change], but it was something for development only, so I’m not in the slightest bit concerned by it. +- Implement `Default` on `Map` (not just on `RawMap`) + I don’t plan for there to be any real changes from 0.12.1; it should be just a bit of housecleaning and a version bump. diff --git a/src/lib.rs b/src/lib.rs index bcd5c23..de03fb6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,13 @@ macro_rules! impl_common_methods { self.$field.clear() } } + + impl Default for $t { + #[inline] + fn default() -> $t { + $t::new() + } + } } } @@ -389,6 +396,12 @@ mod tests { test_entry!(test_entry_any, AnyMap); test_entry!(test_entry_cloneany, Map); + #[test] + fn test_default() { + let map: AnyMap = Default::default(); + assert_eq!(map.len(), 0); + } + #[test] fn test_clone() { let mut map: Map = Map::new(); diff --git a/src/raw.rs b/src/raw.rs index 17c3869..07dccf8 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -70,13 +70,6 @@ impl Clone for RawMap where Box: Clone { } } -impl Default for RawMap { - #[inline] - fn default() -> RawMap { - RawMap::new() - } -} - impl_common_methods! { field: RawMap.inner; new() => HashMap::with_hasher(Default::default()); -- 2.50.1 From 479d756c992af132c6ba45248c65dc230c5986cf Mon Sep 17 00:00:00 2001 From: Marcel Hellwig Date: Tue, 13 Nov 2018 08:33:44 +0100 Subject: [PATCH 14/16] removed unsafe code in favor of explicit assert --- src/raw.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/raw.rs b/src/raw.rs index 07dccf8..dbd5e2c 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -10,7 +10,6 @@ use std::hash::{Hasher, BuildHasherDefault}; #[cfg(test)] use std::mem; use std::ops::{Index, IndexMut}; -use std::ptr; use any::{Any, UncheckedAnyExt}; @@ -23,10 +22,11 @@ impl Hasher for TypeIdHasher { #[inline] fn write(&mut self, bytes: &[u8]) { // This expects to receive one and exactly one 64-bit value - debug_assert!(bytes.len() == 8); - unsafe { - ptr::copy_nonoverlapping(&bytes[0] as *const u8 as *const u64, &mut self.value, 1) - } + 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; } #[inline] -- 2.50.1 From 8abad057b08ea7f67d0f5aef40283b03146e2443 Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Wed, 26 Jan 2022 00:12:16 +1100 Subject: [PATCH 15/16] Revert "removed unsafe code in favor of explicit assert" MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit This reverts commit 479d756c992af132c6ba45248c65dc230c5986cf. There’s nothing wrong with this patch, but I had never pulled this commit to my local repository and had completely forgotten about it, and today removed the unsafe code in a *different* direction that I like better (`bytes.try_into().map(|bytes| u64::from_ne_bytes(bytes))`), so reverting it so I can cleanly rebase is just easier for me! --- src/raw.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/raw.rs b/src/raw.rs index dbd5e2c..07dccf8 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -10,6 +10,7 @@ use std::hash::{Hasher, BuildHasherDefault}; #[cfg(test)] use std::mem; use std::ops::{Index, IndexMut}; +use std::ptr; use any::{Any, UncheckedAnyExt}; @@ -22,11 +23,10 @@ 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; + debug_assert!(bytes.len() == 8); + unsafe { + ptr::copy_nonoverlapping(&bytes[0] as *const u8 as *const u64, &mut self.value, 1) + } } #[inline] -- 2.50.1 From 8ebb2d7e04d86d09614f578342e4765276372e7b Mon Sep 17 00:00:00 2001 From: Chris Morgan Date: Tue, 25 Jan 2022 12:40:30 +1100 Subject: [PATCH 16/16] Add the BlueOak-1.0.0 license MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit I prefer to use BlueOak-1.0.0 now; It wasn’t around back in 2017. There are a number of commits in this repository not made by me, all from before Rust 1.0.0: • f1710353a039c1d5e95d15bb54effd7cab8e047f (Robert Straw; trivial: matching std enum namespacing breakage) • de091453093fb5139de71b085411d2fad1a52275 (Robert Straw; trivial: std enum namespacing breakage) • 2e37f0d1aebbd0c56acd0de7b46d14cd71d3e134 (Jonathan Reem; added AnyMap::contains, which had become obvious for Rust collection parity) • 8b30c87fe6cf514544d8bc68989631daac8aeec1 (tivek; trivial: Rust syntax change in integer literal inference) • c9d196be5f40fb0c6e53c65fa072aea60de8c3f1 (Jonathan Reem; trivial: version bump) • 330bc5aa1e4b1644a19b3751ee3b65c849447005 (Jonathan Reem; not creative and largely no longer present: introduced Cargo support, tweaked Makefile) • a9b1e31b7062e42248347805cbee662efe0eb713 (Tomas Sedovic; nigh-trivial and no longer present: Collection and Mutable trait implementations) • eecc4a4b758ae743486cfe4254cefd136f829391 (Jonathan Reem; trivial: Rust syntax change) • d51aff506409d7ffa2de275cd4e3029a88de1e2a (Jonathan Reem; trivial: rustc lint change) • 56113c63b028e7d215f1c16cf90d9c5d902df477 (Jonathan Reem; trivial: Rust syntax change) All but one of these are definitely trivial, obvious, and in the context of the project and ecosystem not creative works (⅌ copyright doctrine definition); or else no longer present. The one arguable exception is 2e37f0d1aebbd0c56acd0de7b46d14cd71d3e134, adding AnyMap::contains, since I hadn’t added a contains method; but its *definition* is trivial with only one possible implementation, and subsequent to that time I did go through and check for parity with HashMap methods, to say nothing of the code having changed shape quite a bit since then too. Therefore I’m content to consider it immaterial for relicensing. --- CHANGELOG.md | 2 + COPYING | 17 +++++ COPYRIGHT | 3 - Cargo.toml | 2 +- LICENSE-APACHE | 201 ------------------------------------------------- LICENSE-MIT | 25 ------ README.md | 16 ++-- 7 files changed, 27 insertions(+), 239 deletions(-) create mode 100644 COPYING delete mode 100644 COPYRIGHT delete mode 100644 LICENSE-APACHE delete mode 100644 LICENSE-MIT diff --git a/CHANGELOG.md b/CHANGELOG.md index 9691d8e..04b57ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # 1.0.0 (unreleased) +- Relicensed from MIT/Apache-2.0 to BlueOak-1.0.0/MIT/Apache-2.0. + - Remove `bench` Cargo feature (by shifting benchmarks out of `src/lib.rs` into `benches/bench.rs`; it still won’t run on anything but nightly, but that don’t signify). Technically a [breaking-change], but it was something for diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d8060a4 --- /dev/null +++ b/COPYING @@ -0,0 +1,17 @@ +Copyright © 2014–2022 Chris Morgan + +This project is distributed under the terms of three different licenses, +at your choice: + +- Blue Oak Model License 1.0.0: https://blueoakcouncil.org/license/1.0.0 +- MIT License: https://opensource.org/licenses/MIT +- Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0 + +If you do not have particular cause to select the MIT or the Apache-2.0 +license, Chris Morgan recommends that you select BlueOak-1.0.0, which is +better and simpler than both MIT and Apache-2.0, which are only offered +due to their greater recognition and their conventional use in the Rust +ecosystem. (BlueOak-1.0.0 was only published in March 2019.) + +When using this code, ensure you comply with the terms of at least one of +these licenses. diff --git a/COPYRIGHT b/COPYRIGHT deleted file mode 100644 index 55c8f9f..0000000 --- a/COPYRIGHT +++ /dev/null @@ -1,3 +0,0 @@ -This project is dual-licensed under the terms of the MIT and Apache (version 2.0) licenses. - -Copyright (c) 2014 Chris Morgan and the Teepee project developers diff --git a/Cargo.toml b/Cargo.toml index 746399b..166549a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,4 +8,4 @@ documentation = "https://docs.rs/anymap" repository = "https://github.com/chris-morgan/anymap" readme = "README.md" keywords = ["container", "data-structure", "map"] -license = "MIT/Apache-2.0" +license = "BlueOak-1.0.0 OR MIT OR Apache-2.0" diff --git a/LICENSE-APACHE b/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT deleted file mode 100644 index 6866f31..0000000 --- a/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2014 Chris Morgan and the Teepee project developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 629a8e3..358c262 100644 --- a/README.md +++ b/README.md @@ -38,14 +38,12 @@ Yeah, the performance costs of going safe are quite small. The more serious matt But frankly, if you wanted to do all this it’d be easier and faster to write it from scratch. The core of the library is actually really simple and perfectly safe, as can be seen in [`src/lib.rs` in the first commit](https://github.com/chris-morgan/anymap/tree/a294948f57dee47bb284d6a3ae1b8f61a902a03c/src/lib.rs) (note that that code won’t run without a few syntactic alterations; it was from well before Rust 1.0 and has things like `Any:'static` where now we have `Any + 'static`). -Author ------- +## Colophon -[Chris Morgan](http://chrismorgan.info/) ([chris-morgan](https://github.com/chris-morgan)) is the primary author and maintainer of AnyMap. +**Authorship:** [Chris Morgan](https://chrismorgan.info/) is the author and maintainer of this library. -License -------- - -This library is distributed under similar terms to Rust: dual licensed under the MIT license and the Apache license (version 2.0). - -See LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details. +**Licensing:** this library is distributed under the terms of the +[Blue Oak Model License 1.0.0](https://blueoakcouncil.org/license/1.0.0), the +[MIT License](https://opensource.org/licenses/MIT) and the +[Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0), at your choice. +See [COPYING](COPYING) for details. -- 2.50.1