1
1
//! This file is a port of only the necessary features from <https://github.com/chris-morgan/anymap> version 1.0.0-beta.2 for use within rust-analyzer.
2
+ //!
2
3
//! Copyright © 2014–2022 Chris Morgan.
3
4
//! COPYING: <https://github.com/chris-morgan/anymap/blob/master/COPYING>
4
5
//! Note that the license is changed from Blue Oak Model 1.0.0 or MIT or Apache-2.0 to MIT OR Apache-2.0
20
21
21
22
use core:: hash:: Hasher ;
22
23
23
- /// A hasher designed to eke a little more speed out, given `TypeId`’ s known characteristics.
24
+ /// A hasher designed to eke a little more speed out, given `TypeId`' s known characteristics.
24
25
///
25
- /// Specifically, this is a no-op hasher that expects to be fed a u64’ s worth of
26
+ /// Specifically, this is a no-op hasher that expects to be fed a u64' s worth of
26
27
/// randomly-distributed bits. It works well for `TypeId` (eliminating start-up time, so that my
27
- /// get_missing benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
28
- /// that my insert_and_get_on_260_types benchmark is ~12μs instead of ~21.5μs), but will
28
+ /// ` get_missing` benchmark is ~30ns rather than ~900ns, and being a good deal faster after that, so
29
+ /// that my ` insert_and_get_on_260_types` benchmark is ~12μs instead of ~21.5μs), but will
29
30
/// panic in debug mode and always emit zeros in release mode for any other sorts of inputs, so
30
- /// yeah, don’ t use it! 😀
31
+ /// yeah, don' t use it! 😀
31
32
#[ derive( Default ) ]
32
33
pub struct TypeIdHasher {
33
34
value : u64 ,
@@ -36,9 +37,9 @@ pub struct TypeIdHasher {
36
37
impl Hasher for TypeIdHasher {
37
38
#[ inline]
38
39
fn write ( & mut self , bytes : & [ u8 ] ) {
39
- // This expects to receive exactly one 64-bit value, and there’ s no realistic chance of
40
- // that changing, but I don’ t want to depend on something that isn’ t expressly part of the
41
- // contract for safety. But I’ m OK with release builds putting everything in one bucket
40
+ // This expects to receive exactly one 64-bit value, and there' s no realistic chance of
41
+ // that changing, but I don' t want to depend on something that isn' t expressly part of the
42
+ // contract for safety. But I' m OK with release builds putting everything in one bucket
42
43
// if it *did* change (and debug builds panicking).
43
44
debug_assert_eq ! ( bytes. len( ) , 8 ) ;
44
45
let _ = bytes. try_into ( ) . map ( |array| self . value = u64:: from_ne_bytes ( array) ) ;
@@ -59,7 +60,7 @@ use ::std::collections::hash_map;
59
60
/// Raw access to the underlying `HashMap`.
60
61
///
61
62
/// This alias is provided for convenience because of the ugly third generic parameter.
62
- #[ allow ( clippy:: disallowed_types) ] // Uses a custom hasher
63
+ #[ expect ( clippy:: disallowed_types, reason = " Uses a custom hasher" ) ]
63
64
pub type RawMap < A > = hash_map:: HashMap < TypeId , Box < A > , BuildHasherDefault < TypeIdHasher > > ;
64
65
65
66
/// A collection containing zero or one values for any given type and allowing convenient,
@@ -73,19 +74,20 @@ pub type RawMap<A> = hash_map::HashMap<TypeId, Box<A>, BuildHasherDefault<TypeId
73
74
///
74
75
/// Cumulatively, there are thus six forms of map:
75
76
///
76
- /// - <code> [Map]< dyn [core::any::Any]></code> ,
77
+ /// - ` [Map]< dyn [core::any::Any]>` ,
77
78
/// also spelled [`AnyMap`] for convenience.
78
- /// - <code> [Map]< dyn [core::any::Any] + Send></code>
79
- /// - <code> [Map]< dyn [core::any::Any] + Send + Sync></code>
79
+ /// - ` [Map]< dyn [core::any::Any] + Send>`
80
+ /// - ` [Map]< dyn [core::any::Any] + Send + Sync>`
80
81
///
81
82
/// ## Example
82
83
///
83
- /// (Here using the [`AnyMap`] convenience alias; the first line could use
84
- /// <code>[anymap::Map][Map]::<[core::any::Any]>::new()</code> instead if desired.)
84
+ /// (Here, the [`AnyMap`] convenience alias is used;
85
+ /// the first line could use `[anymap::Map][Map]::<[core::any::Any]>::new()`
86
+ /// instead if desired.)
85
87
///
86
88
/// ```
87
89
/// # use stdx::anymap;
88
- # [ doc = " let mut data = anymap::AnyMap::new();" ]
90
+ /// let mut data = anymap::AnyMap::new();
89
91
/// assert_eq!(data.get(), None::<&i32>);
90
92
/// ```
91
93
///
@@ -95,11 +97,11 @@ pub struct Map<A: ?Sized + Downcast = dyn Any> {
95
97
raw : RawMap < A > ,
96
98
}
97
99
98
- /// The most common type of `Map`: just using `Any`; <code> [Map]< dyn [Any]></code> .
100
+ /// The most common type of `Map`: just using `Any`; ` [Map]< dyn [Any]>` .
99
101
///
100
102
/// Why is this a separate type alias rather than a default value for `Map<A>`?
101
- /// `Map::new()` doesn’ t seem to be happy to infer that it should go with the default
102
- /// value. It’ s a bit sad, really. Ah well, I guess this approach will do.
103
+ /// `Map::new()` doesn' t seem to be happy to infer that it should go with the default
104
+ /// value. It' s a bit sad, really. Ah well, I guess this approach will do.
103
105
pub type AnyMap = Map < dyn Any > ;
104
106
105
107
impl < A : ?Sized + Downcast > Default for Map < A > {
@@ -113,6 +115,7 @@ impl<A: ?Sized + Downcast> Map<A> {
113
115
/// Returns a reference to the value stored in the collection for the type `T`,
114
116
/// if it exists.
115
117
#[ inline]
118
+ #[ must_use]
116
119
pub fn get < T : IntoBox < A > > ( & self ) -> Option < & T > {
117
120
self . raw . get ( & TypeId :: of :: < T > ( ) ) . map ( |any| unsafe { any. downcast_ref_unchecked :: < T > ( ) } )
118
121
}
@@ -132,51 +135,52 @@ impl<A: ?Sized + Downcast> Map<A> {
132
135
}
133
136
134
137
/// A view into a single occupied location in an `Map`.
135
- pub struct OccupiedEntry < ' a , A : ?Sized + Downcast , V : ' a > {
136
- inner : hash_map:: OccupiedEntry < ' a , TypeId , Box < A > > ,
138
+ pub struct OccupiedEntry < ' map , A : ?Sized + Downcast , V : ' map > {
139
+ inner : hash_map:: OccupiedEntry < ' map , TypeId , Box < A > > ,
137
140
type_ : PhantomData < V > ,
138
141
}
139
142
140
143
/// A view into a single empty location in an `Map`.
141
- pub struct VacantEntry < ' a , A : ?Sized + Downcast , V : ' a > {
142
- inner : hash_map:: VacantEntry < ' a , TypeId , Box < A > > ,
144
+ pub struct VacantEntry < ' map , A : ?Sized + Downcast , V : ' map > {
145
+ inner : hash_map:: VacantEntry < ' map , TypeId , Box < A > > ,
143
146
type_ : PhantomData < V > ,
144
147
}
145
148
146
149
/// A view into a single location in an `Map`, which may be vacant or occupied.
147
- pub enum Entry < ' a , A : ?Sized + Downcast , V > {
150
+ pub enum Entry < ' map , A : ?Sized + Downcast , V > {
148
151
/// An occupied Entry
149
- Occupied ( OccupiedEntry < ' a , A , V > ) ,
152
+ Occupied ( OccupiedEntry < ' map , A , V > ) ,
150
153
/// A vacant Entry
151
- Vacant ( VacantEntry < ' a , A , V > ) ,
154
+ Vacant ( VacantEntry < ' map , A , V > ) ,
152
155
}
153
156
154
- impl < ' a , A : ?Sized + Downcast , V : IntoBox < A > > Entry < ' a , A , V > {
157
+ impl < ' map , A : ?Sized + Downcast , V : IntoBox < A > > Entry < ' map , A , V > {
155
158
/// Ensures a value is in the entry by inserting the result of the default function if
156
159
/// empty, and returns a mutable reference to the value in the entry.
157
160
#[ inline]
158
- pub fn or_insert_with < F : FnOnce ( ) -> V > ( self , default : F ) -> & ' a mut V {
161
+ pub fn or_insert_with < F : FnOnce ( ) -> V > ( self , default : F ) -> & ' map mut V {
159
162
match self {
160
163
Entry :: Occupied ( inner) => inner. into_mut ( ) ,
161
164
Entry :: Vacant ( inner) => inner. insert ( default ( ) ) ,
162
165
}
163
166
}
164
167
}
165
168
166
- impl < ' a , A : ?Sized + Downcast , V : IntoBox < A > > OccupiedEntry < ' a , A , V > {
167
- /// Converts the OccupiedEntry into a mutable reference to the value in the entry
169
+ impl < ' map , A : ?Sized + Downcast , V : IntoBox < A > > OccupiedEntry < ' map , A , V > {
170
+ /// Converts the ` OccupiedEntry` into a mutable reference to the value in the entry
168
171
/// with a lifetime bound to the collection itself
169
172
#[ inline]
170
- pub fn into_mut ( self ) -> & ' a mut V {
173
+ #[ must_use]
174
+ pub fn into_mut ( self ) -> & ' map mut V {
171
175
unsafe { self . inner . into_mut ( ) . downcast_mut_unchecked ( ) }
172
176
}
173
177
}
174
178
175
- impl < ' a , A : ?Sized + Downcast , V : IntoBox < A > > VacantEntry < ' a , A , V > {
176
- /// Sets the value of the entry with the VacantEntry's key,
179
+ impl < ' map , A : ?Sized + Downcast , V : IntoBox < A > > VacantEntry < ' map , A , V > {
180
+ /// Sets the value of the entry with the ` VacantEntry` 's key,
177
181
/// and returns a mutable reference to it
178
182
#[ inline]
179
- pub fn insert ( self , value : V ) -> & ' a mut V {
183
+ pub fn insert ( self , value : V ) -> & ' map mut V {
180
184
unsafe { self . inner . insert ( value. into_box ( ) ) . downcast_mut_unchecked ( ) }
181
185
}
182
186
}
@@ -201,14 +205,13 @@ mod tests {
201
205
#[ test]
202
206
fn type_id_hasher ( ) {
203
207
use core:: any:: TypeId ;
204
- use core:: hash:: Hash ;
208
+ use core:: hash:: Hash as _ ;
205
209
fn verify_hashing_with ( type_id : TypeId ) {
206
210
let mut hasher = TypeIdHasher :: default ( ) ;
207
211
type_id. hash ( & mut hasher) ;
208
- // SAFETY: u64 is valid for all bit patterns.
209
- let _ = hasher. finish ( ) ;
212
+ _ = hasher. finish ( ) ;
210
213
}
211
- // Pick a variety of types, just to demonstrate it’ s all sane. Normal, zero-sized, unsized, &c.
214
+ // Pick a variety of types, just to demonstrate it' s all sane. Normal, zero-sized, unsized, &c.
212
215
verify_hashing_with ( TypeId :: of :: < usize > ( ) ) ;
213
216
verify_hashing_with ( TypeId :: of :: < ( ) > ( ) ) ;
214
217
verify_hashing_with ( TypeId :: of :: < str > ( ) ) ;
@@ -220,34 +223,34 @@ mod tests {
220
223
/// Methods for downcasting from an `Any`-like trait object.
221
224
///
222
225
/// This should only be implemented on trait objects for subtraits of `Any`, though you can
223
- /// implement it for other types and it’ ll work fine, so long as your implementation is correct.
226
+ /// implement it for other types and it' ll work fine, so long as your implementation is correct.
224
227
pub trait Downcast {
225
228
/// Gets the `TypeId` of `self`.
226
229
fn type_id ( & self ) -> TypeId ;
227
230
228
231
// Note the bound through these downcast methods is 'static, rather than the inexpressible
229
232
// concept of Self-but-as-a-trait (where Self is `dyn Trait`). This is sufficient, exceeding
230
- // TypeId’ s requirements. Sure, you *can* do CloneAny.downcast_unchecked::<NotClone>() and the
231
- // type system won’ t protect you, but that doesn’ t introduce any unsafety: the method is
233
+ // TypeId' s requirements. Sure, you *can* do CloneAny.downcast_unchecked::<NotClone>() and the
234
+ // type system won' t protect you, but that doesn' t introduce any unsafety: the method is
232
235
// already unsafe because you can specify the wrong type, and if this were exposing safe
233
236
// downcasting, CloneAny.downcast::<NotClone>() would just return an error, which is just as
234
237
// correct.
235
238
//
236
- // Now in theory we could also add T: ?Sized, but that doesn’ t play nicely with the common
237
- // implementation, so I’ m doing without it.
239
+ // Now in theory we could also add T: ?Sized, but that doesn' t play nicely with the common
240
+ // implementation, so I' m doing without it.
238
241
239
242
/// Downcast from `&Any` to `&T`, without checking the type matches.
240
243
///
241
244
/// # Safety
242
245
///
243
- /// The caller must ensure that `T` matches the trait object, on pain of *undefined behaviour *.
246
+ /// The caller must ensure that `T` matches the trait object, on pain of *undefined behavior *.
244
247
unsafe fn downcast_ref_unchecked < T : ' static > ( & self ) -> & T ;
245
248
246
249
/// Downcast from `&mut Any` to `&mut T`, without checking the type matches.
247
250
///
248
251
/// # Safety
249
252
///
250
- /// The caller must ensure that `T` matches the trait object, on pain of *undefined behaviour *.
253
+ /// The caller must ensure that `T` matches the trait object, on pain of *undefined behavior *.
251
254
unsafe fn downcast_mut_unchecked < T : ' static > ( & mut self ) -> & mut T ;
252
255
}
253
256
@@ -267,12 +270,12 @@ macro_rules! implement {
267
270
268
271
#[ inline]
269
272
unsafe fn downcast_ref_unchecked<T : ' static >( & self ) -> & T {
270
- unsafe { & * ( self as * const Self as * const T ) }
273
+ unsafe { & * std :: ptr :: from_ref :: < Self > ( self ) . cast :: < T > ( ) }
271
274
}
272
275
273
276
#[ inline]
274
277
unsafe fn downcast_mut_unchecked<T : ' static >( & mut self ) -> & mut T {
275
- unsafe { & mut * ( self as * mut Self as * mut T ) }
278
+ unsafe { & mut * std :: ptr :: from_mut :: < Self > ( self ) . cast :: < T > ( ) }
276
279
}
277
280
}
278
281
0 commit comments