1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
#![warn(clippy::pedantic)]
use std::{
collections::HashSet,
fmt::Debug,
hash::{BuildHasher, Hash, RandomState},
marker::PhantomData,
mem::ManuallyDrop,
};
use mut_guard::MutGuard;
use value_wrapper::ValueWrapper;
pub mod iter;
mod mut_guard;
mod value_wrapper;
#[cfg(feature = "iter_mut")]
pub use gat_lending_iterator::LendingIterator;
/// A trait for extracting the key for an [`ExtractMap`].
///
/// This is relied on for correctness in the same way as [`Hash`] and [`Eq`] are and
/// is purely designed for directly referencing a field with no interior mutability or
/// static return type, the documentation on [`HashSet`] should be followed for this key type.
pub trait ExtractKey<K: Hash + Eq> {
fn extract_key(&self) -> &K;
}
/// A hash map for memory efficent storage of value types which contain their own keys.
///
/// This is achieved by the `V` type deriving the [`ExtractKey`] trait for their `K` type,
/// and is backed by a `HashSet<Wrap<K>, V, S>`, meaning this library only uses unsafe code
/// for performance reasons.
///
/// The default hashing algorithm is the same as the standard library's [`HashSet`], [`RandomState`],
/// although your own hasher can be provided via [`ExtractMap::with_hasher`] and it's similar methods.
#[cfg_attr(feature = "typesize", derive(typesize::TypeSize))]
pub struct ExtractMap<K, V, S = RandomState> {
inner: HashSet<ValueWrapper<K, V>, S>,
}
impl<K, V> Default for ExtractMap<K, V, RandomState> {
fn default() -> Self {
Self::new()
}
}
impl<K, V> ExtractMap<K, V, RandomState> {
/// Creates a new, empty [`ExtractMap`] with the [`RandomState`] hasher.
#[must_use]
pub fn new() -> Self {
Self::with_hasher(RandomState::new())
}
/// Creates a new [`ExtractMap`] with the [`RandomState`] hasher and preallocated capacity.
///
/// # Examples
/// ```
/// use extract_map::{ExtractMap, ExtractKey};
///
/// struct User {
/// id: u64,
/// name: &'static str,
/// }
///
/// impl ExtractKey<u64> for User {
/// fn extract_key(&self) -> &u64 {
/// &self.id
/// }
/// }
///
/// let map = ExtractMap::<u64, User>::with_capacity(5);
///
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 5);
/// ```
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_and_hasher(capacity, RandomState::new())
}
}
impl<K, V, S> ExtractMap<K, V, S> {
/// Creates a new, empty [`ExtractMap`] with the provided hasher.
#[must_use]
pub fn with_hasher(hasher: S) -> Self {
Self {
inner: HashSet::with_hasher(hasher),
}
}
/// Creates a new [`ExtractMap`] with the provided hasher and preallocated capacity.
///
/// # Examples
/// ```
/// use extract_map::{ExtractMap, ExtractKey};
///
/// struct User {
/// id: u64,
/// name: &'static str,
/// }
///
/// impl ExtractKey<u64> for User {
/// fn extract_key(&self) -> &u64 {
/// &self.id
/// }
/// }
///
/// let map = ExtractMap::<u64, User>::with_capacity_and_hasher(5, std::hash::RandomState::new());
///
/// assert!(map.is_empty());
/// assert!(map.capacity() >= 5);
/// ```
#[must_use]
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
Self {
inner: HashSet::with_capacity_and_hasher(capacity, hasher),
}
}
}
impl<K, V, S> ExtractMap<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K>,
S: BuildHasher,
{
/// Inserts a value into the [`ExtractMap`].
///
/// This extracts the key from the value using the [`ExtractKey`] trait, and therefore does not need a key to be provided.
///
/// # Examples
/// ```
/// use extract_map::{ExtractMap, ExtractKey};
///
/// struct User {
/// id: u64,
/// name: &'static str,
/// }
///
/// impl ExtractKey<u64> for User {
/// fn extract_key(&self) -> &u64 {
/// &self.id
/// }
/// }
///
/// let mut map = ExtractMap::new();
/// map.insert(User { id: 1, name: "Daisy" });
/// map.insert(User { id: 2, name: "Elliott" });
///
/// assert_eq!(map.len(), 2);
/// ```
pub fn insert(&mut self, value: V) -> Option<V> {
self.inner
.replace(ValueWrapper(value, PhantomData))
.map(|v| v.0)
}
/// Removes a value from the [`ExtractMap`].
///
/// # Examples
/// ```
/// use extract_map::{ExtractMap, ExtractKey};
///
/// #[derive(Debug, Clone, PartialEq)]
/// struct User {
/// id: u64,
/// name: &'static str,
/// }
///
/// impl ExtractKey<u64> for User {
/// fn extract_key(&self) -> &u64 {
/// &self.id
/// }
/// }
///
/// let user = User { id: 1, name: "Daisy" };
/// let mut map = ExtractMap::new();
/// map.insert(user.clone());
///
/// assert_eq!(map.remove(&1), Some(user));
/// assert!(map.is_empty())
/// ```
pub fn remove(&mut self, key: &K) -> Option<V> {
self.inner.take(key).map(|v| v.0)
}
/// Checks if a value is in the [`ExtractMap`].
#[must_use]
pub fn contains_key(&self, key: &K) -> bool {
self.inner.contains(key)
}
/// Retrieves a value from the [`ExtractMap`].
#[must_use]
pub fn get(&self, key: &K) -> Option<&V> {
self.inner.get(key).map(|v| &v.0)
}
/// Retrieves a mutable guard to a value in the [`ExtractMap`].
///
/// This guard is required as the current implementation takes the value out
/// of the map and reinserts on Drop to allow mutation of the key field.
#[must_use]
pub fn get_mut<'a>(&'a mut self, key: &K) -> Option<MutGuard<'a, K, V, S>> {
let value = self.inner.take(key)?;
Some(MutGuard {
value: ManuallyDrop::new(value.0),
map: self,
})
}
}
impl<K, V, S> ExtractMap<K, V, S> {
#[must_use]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Retrieves an iterator over the borrowed values.
///
/// If you need an iterator over the keys and values, simply use [`ExtractKey`].
///
/// Use [`IntoIterator::into_iter`] for an iterator over owned values.
pub fn iter(&self) -> iter::Iter<'_, K, V> {
self.into_iter()
}
}
#[cfg(feature = "iter_mut")]
impl<K, V, S> ExtractMap<K, V, S>
where
K: Hash + Eq + Clone,
V: ExtractKey<K>,
S: BuildHasher,
{
/// Retrieves a [`LendingIterator`] over mutable borrowed values.
///
/// This cannot implement [`Iterator`], so uses the `gat_lending_iterator` crate and has the
/// performance cost of allocating a [`Vec`] of the keys cloned, so if possible should be avoided.
///
/// To use, [`LendingIterator`] must be in scope, therefore this crate re-exports it.
#[allow(clippy::iter_not_returning_iterator)]
pub fn iter_mut(&mut self) -> iter::IterMut<'_, K, V, S> {
iter::IterMut::new(self)
}
}
impl<K, V: Clone, S: Clone> Clone for ExtractMap<K, V, S> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self { inner }
}
}
impl<K, V, S> Debug for ExtractMap<K, V, S>
where
K: Debug + Hash + Eq,
V: Debug + ExtractKey<K>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entries(self.iter().map(|v| (v.extract_key(), v)))
.finish()
}
}
impl<K, V, S> PartialEq for ExtractMap<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K> + PartialEq,
S: BuildHasher,
{
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}
self.iter().all(|v| {
let k = v.extract_key();
other.get(k).is_some_and(|other_v| {
let other_k = other_v.extract_key();
k == other_k && v == other_v
})
})
}
}
impl<K, V, S> FromIterator<V> for ExtractMap<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K>,
S: BuildHasher + Default,
{
fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
let inner = iter
.into_iter()
.map(|item| ValueWrapper(item, PhantomData))
.collect();
Self { inner }
}
}
impl<K, V, S> Extend<V> for ExtractMap<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K>,
S: BuildHasher,
{
fn extend<T: IntoIterator<Item = V>>(&mut self, iter: T) {
for item in iter {
self.insert(item);
}
}
}
/// Deserializes an [`ExtractMap`] from either a sequence or a map.
///
/// This uses [`serde::Deserializer::deserialize_any`], so may fail for formats which are not self-describing.
///
/// # Example
/// ```
/// use extract_map::{ExtractMap, ExtractKey};
///
/// #[derive(Debug, PartialEq, serde::Deserialize)]
/// struct User {
/// id: u64,
/// name: &'static str,
/// }
///
/// impl ExtractKey<u64> for User {
/// fn extract_key(&self) -> &u64 {
/// &self.id
/// }
/// }
///
/// let map_json = r#"{"0": {"id": 0, "name": "Elliott"}, "1": {"id": 1, "name": "Daisy"}}"#;
/// let seq_json = r#"[{"id": 0, "name": "Elliott"}, {"id": 1, "name": "Daisy"}]"#;
///
/// let map: ExtractMap<u64, User> = serde_json::from_str(map_json).unwrap();
/// let seq: ExtractMap<u64, User> = serde_json::from_str(seq_json).unwrap();
///
/// assert_eq!(map, seq);
/// ```
#[cfg(feature = "serde")]
impl<'de, K, V, S> serde::Deserialize<'de> for ExtractMap<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K> + serde::Deserialize<'de>,
S: BuildHasher + Default,
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::{DeserializeSeed, Error, IgnoredAny, MapAccess, SeqAccess};
struct SeqMapAdapter<M>(M);
impl<'de, M, E> SeqAccess<'de> for SeqMapAdapter<M>
where
E: Error,
M: MapAccess<'de, Error = E>,
{
type Error = E;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: DeserializeSeed<'de>,
{
self.0
.next_entry_seed(PhantomData::<IgnoredAny>, seed)
.map(|o| o.map(|(_, v)| v))
}
}
struct Visitor<K, V, S>(PhantomData<(K, V, S)>);
impl<'de, K, V, S> serde::de::Visitor<'de> for Visitor<K, V, S>
where
K: Hash + Eq,
V: ExtractKey<K> + serde::Deserialize<'de>,
S: BuildHasher + Default,
{
type Value = ExtractMap<K, V, S>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a sequence")
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
self.visit_seq(SeqMapAdapter(map))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut map = ExtractMap::with_capacity_and_hasher(
seq.size_hint().unwrap_or_default(),
S::default(),
);
while let Some(elem) = seq.next_element()? {
map.insert(elem);
}
Ok(map)
}
}
deserializer.deserialize_any(Visitor(PhantomData))
}
}
/// Serializes an [`ExtractMap`] into a sequence of the values.
#[cfg(feature = "serde")]
impl<K, V: serde::Serialize, H> serde::Serialize for ExtractMap<K, V, H> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self)
}
}
/// A serialize method to serialize a [`ExtractMap`] to a map instead of a sequence.
///
/// This should be used via serde's `serialize_with` field attribute.
///
/// # Errors
/// Errors if the underlying key or value serialisation fails.
#[cfg(feature = "serde")]
pub fn serialize_as_map<K, V, H, S>(map: &ExtractMap<K, V, H>, ser: S) -> Result<S::Ok, S::Error>
where
K: serde::Serialize + Hash + Eq,
V: serde::Serialize + ExtractKey<K>,
S: serde::Serializer,
{
ser.collect_map(map.iter().map(|v| (v.extract_key(), v)))
}