fixed-map 0.9.5

A fixed map where storage layout is calculated by a procedural macro.
Documentation
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
//! # PRIVATE API
//!
//! This API is private, for use only in the `derive(Key)` macro.
//! Usage for other purposes is not supported, and this API will
//! not abide by Semver stability guarantees.
//!
//! If you find that this API would be useful outside its
//! application in `fixed-map`, let us know.
//! We can factor it into its own crate.
//!
//! # Option Buckets
//!
//! Utility for working with [`Option`s][Option]
//! in cases where we want mutable access to the value within
//! and the [`Option`] itself (but not at the same time).
//!
//! Provides three types:
//! - [`SomeBucket`] allows accessing the value
//!   inside an [`Option`] known to be [`Some`] without `unwrap`
//! - [`NoneBucket`] allows optimally inserting a value
//!   into an [`Option`] known to be [`None`]
//! - [`OptionBucket`], an enum over the previous two,
//!   easily constructed from any `&mut Option`
//!
//! # Examples
//!
//! Safely implement [`Option::get_or_insert`]
//! ```
//! use fixed_map::option_bucket::OptionBucket;
//!
//! fn get_or_insert<T>(this: &mut Option<T>, value: T) -> &mut T {
//!     match OptionBucket::new(this) {
//!          OptionBucket::Some(some) => some.into_mut(),
//!          OptionBucket::None(none) => none.insert(value),
//!     }
//! }
//!
//! let mut x = None;
//! assert_eq!(get_or_insert(&mut x, 12), &12);
//! ```
//!
//! Safely implement entry API for [`Option`]
//! ```
//! use fixed_map::option_bucket::*;
//!
//! struct OccupiedEntry<'a, T> {
//!     inner: SomeBucket<'a, T>
//! }
//!
//! struct VacantEntry<'a, T> {
//!     inner: NoneBucket<'a, T>,
//! }
//!
//! enum Entry<'a, T> {
//!     Vacant(VacantEntry<'a, T>),
//!     Occupied(OccupiedEntry<'a, T>),
//! }
//!
//! impl<'a, T> VacantEntry<'a, T> {
//!     fn insert(self, value: T) -> &'a mut T {
//!         self.inner.insert(value)
//!     }
//! }
//!
//! impl<'a, T> OccupiedEntry<'a, T> {
//!     fn get(&self) -> &T {
//!         self.inner.as_ref()
//!     }
//!     fn get_mut(&mut self) -> &mut T {
//!         self.inner.as_mut()
//!     }
//!     fn into_mut(self) -> &'a mut T {
//!         self.inner.into_mut()
//!     }
//!     fn insert(&mut self, value: T) -> T {
//!         self.inner.replace(value)
//!     }
//!     fn remove(self) -> T {
//!         self.inner.take()
//!     }
//! }
//!
//! fn option_entry<T>(this: &mut Option<T>) -> Entry<'_, T> {
//!     match OptionBucket::new(this) {
//!         OptionBucket::Some(inner) => Entry::Occupied(OccupiedEntry { inner }),
//!         OptionBucket::None(inner) => Entry::Vacant(VacantEntry { inner }),
//!     }
//! }
//! ```

#![allow(unsafe_code)]
// `clippy::pedantic` exceptions
#![allow(clippy::should_implement_trait, clippy::must_use_candidate)]

use core::mem;

use crate::map::{OccupiedEntry, VacantEntry};

#[cfg(test)]
mod tests;

/// Abstraction for an [`&mut Option`][Option] that's known to be [`Some`].
///
/// # Size
///
/// `SomeOption` is the size of two pointers, making it
/// twice the size of `&mut Option`. One points to the
/// value inside, and the other points to the `Option` itself.
pub struct SomeBucket<'a, T> {
    outer: &'a mut Option<T>,
}

impl<'a, T> SomeBucket<'a, T> {
    /// Creates a new [`SomeBucket`], without checking that
    /// the input [`Option`] is `Some`.
    ///
    /// It's recommended to use [`SomeBucket::new`] or
    /// [`OptionBucket::new`] instead.
    ///
    /// # Safety
    ///
    /// Caller must guarantee that `opt` is NOT `None`.
    #[inline]
    pub unsafe fn new_unchecked(opt: &'a mut Option<T>) -> Self {
        debug_assert!(
            opt.is_some(),
            "Undefined Behavior: `None` value passed to `SomeBucket::new_unchecked`."
        );

        SomeBucket { outer: opt }
    }

    /// Creates a new [`SomeBucket`]. Returns `Some(SomeBucket<T>)`
    /// if `opt` is [`Some`], otherwise returns `None`.
    ///
    /// For an unchecked version, see [`SomeBucket::new_unchecked`].
    #[inline]
    pub fn new(opt: &'a mut Option<T>) -> Option<Self> {
        if opt.is_some() {
            // SAFETY: If conditional ensures that `opt` is `Some`
            unsafe { Some(Self::new_unchecked(opt)) }
        } else {
            None
        }
    }

    /// Converts from `&Option<T>::Some` to `&T`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut text: Option<String> = Some("Hello, world!".to_string());
    /// let some = SomeBucket::new(&mut text).unwrap();
    ///
    /// let hello: &str = &some.as_ref()[..5];
    /// let length: usize = some.as_ref().len();
    /// assert_eq!(hello, "Hello");
    /// assert_eq!(length, 13);
    /// ```
    #[inline]
    pub fn as_ref(&self) -> &T {
        // SAFETY: `outer` is guaranteed to be `Some`
        // by the invariants of `new_unchecked`
        unsafe { self.outer.as_ref().unwrap_unchecked() }
    }

    /// Converts from `&mut Option<T>::Some` to `&mut T`,
    /// with the lifetime of this `SomeBucket`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut text: Option<String> = Some("Hello, world!".to_string());
    /// let mut some = SomeBucket::new(&mut text).unwrap();
    ///
    /// some.as_mut().push_str(" Happy to be here.");
    /// assert_eq!(some.as_ref(), "Hello, world! Happy to be here.");
    /// ```
    #[inline]
    pub fn as_mut(&mut self) -> &mut T {
        // SAFETY: `outer` is guaranteed to be `Some`
        // by the invariants of `new_unchecked`
        unsafe { self.outer.as_mut().unwrap_unchecked() }
    }

    /// Converts from `&mut Option<T>::Some` to `&mut T`,
    /// with the lifetime of the original reference,
    /// consuming this `SomeBucket`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut text: Option<String> = Some("Hello, world!".to_string());
    /// let some = SomeBucket::new(&mut text).unwrap();
    ///
    /// some.into_mut().push_str(" Happy to be here.");
    /// assert_eq!(&text.unwrap(), "Hello, world! Happy to be here.");
    /// ```
    ///
    /// ```compile_fail
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut text: Option<String> = Some("Hello, world!".to_string());
    /// let some = SomeBucket::new(&mut text).unwrap();
    ///
    /// some.into_mut().push_str(" Happy to be here.");
    /// // can not longer use `some`
    /// some.as_ref();
    /// ```
    #[inline]
    pub fn into_mut(self) -> &'a mut T {
        // SAFETY: `outer` is guaranteed to be `Some`
        // by the invariants of `new_unchecked`
        unsafe { self.outer.as_mut().unwrap_unchecked() }
    }

    /// Sets the value in the `Option<T>::Some`, and returns
    /// the old value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut x = Some(2);
    /// let mut some = SomeBucket::new(&mut x).unwrap();
    ///
    /// let old = some.replace(5);
    /// assert_eq!(old, 2);
    /// assert_eq!(x, Some(5));
    /// ```
    #[inline]
    pub fn replace(&mut self, value: T) -> T {
        mem::replace(self.as_mut(), value)
    }

    /// Takes the value out of the option, leaving a `None` in its place,
    /// and consuming this `SomeBucket`.
    ///
    /// ```
    /// # use fixed_map::option_bucket::SomeBucket;
    ///
    /// let mut x = Some(vec![1, 2]);
    /// let some = SomeBucket::new(&mut x).unwrap();
    ///
    /// let y = some.take();
    /// assert_eq!(x, None);
    /// assert_eq!(y, vec![1, 2]);
    /// ```
    #[inline]
    pub fn take(self) -> T {
        // SAFETY: `outer` is guaranteed to be `Some`
        // by the invariants of `new_unchecked`
        unsafe { self.outer.take().unwrap_unchecked() }
    }
}

impl<'a, K, V> OccupiedEntry<'a, K, V> for SomeBucket<'a, V>
where
    K: Default,
{
    #[inline]
    fn key(&self) -> K {
        K::default()
    }

    #[inline]
    fn get(&self) -> &V {
        SomeBucket::as_ref(self)
    }

    #[inline]
    fn get_mut(&mut self) -> &mut V {
        SomeBucket::as_mut(self)
    }

    #[inline]
    fn into_mut(self) -> &'a mut V {
        SomeBucket::into_mut(self)
    }

    #[inline]
    fn insert(&mut self, value: V) -> V {
        SomeBucket::replace(self, value)
    }

    #[inline]
    fn remove(self) -> V {
        SomeBucket::take(self)
    }
}

/// Abstraction for an [`&mut Option`][Option] that's known to be `None`.
///
/// # Size
///
/// `NoneBucket` is the same size as `&mut Option`
pub struct NoneBucket<'a, T> {
    outer: &'a mut Option<T>,
}

impl<'a, T> NoneBucket<'a, T> {
    /// Creates a new [`NoneBucket`], without checking that
    /// the input [`Option`] is `None`.
    ///
    /// It's recommended to use [`NoneBucket::new`] or
    /// [`OptionBucket::new`] instead.
    ///
    /// # Safety
    ///
    /// Caller must guarantee that `opt` is NOT [`Some`].
    #[inline]
    pub unsafe fn new_unchecked(opt: &'a mut Option<T>) -> Self {
        debug_assert!(
            opt.is_none(),
            "Undefined Behavior: `Some` value passed to `NoneBucket::new_unchecked`."
        );

        NoneBucket { outer: opt }
    }

    /// Creates a new [`NoneBucket`]. Returns `Some(NoneBucket<T>)`
    /// if `opt` is [`None`], otherwise returns `None`.
    ///
    /// For an unchecked version, see [`NoneBucket::new_unchecked`].
    #[inline]
    pub fn new(opt: &'a mut Option<T>) -> Option<Self> {
        if opt.is_none() {
            // SAFETY: if conditional ensures that `opt` is `None`
            unsafe { Some(Self::new_unchecked(opt)) }
        } else {
            None
        }
    }

    /// Inserts value into the option, then returns a mutable reference to it.
    ///
    /// This is practically identical to [`Option::insert`], but avoids
    /// operations handling [`drop`]ping the old value
    /// (since we know there was no old value).
    /// ```
    /// # use fixed_map::option_bucket::NoneBucket;
    ///
    /// let mut opt = None;
    /// let mut none = NoneBucket::new(&mut opt).unwrap();
    /// let val = none.insert(1);
    /// assert_eq!(*val, 1);
    /// *val = 3;
    /// assert_eq!(opt.unwrap(), 3);
    /// ```
    #[inline]
    pub fn insert(self, value: T) -> &'a mut T {
        // SAFETY: `outer` is `None`, so there is no old value to `drop`
        unsafe {
            let outer: *mut Option<T> = self.outer;
            outer.write(Some(value));
        }

        // SAFETY: the code above just filled the option
        unsafe { self.outer.as_mut().unwrap_unchecked() }
    }
}

impl<'a, K, V> VacantEntry<'a, K, V> for NoneBucket<'a, V>
where
    K: Default,
{
    #[inline]
    fn key(&self) -> K {
        K::default()
    }

    #[inline]
    fn insert(self, value: V) -> &'a mut V {
        NoneBucket::insert(self, value)
    }
}

/// Recommended entry for getting a [`SomeBucket`] or
/// [`NoneBucket`]. Infallibly convertible from any
/// [`&mut Option`][Option].
pub enum OptionBucket<'a, T> {
    /// An option known to be `Some`.
    Some(SomeBucket<'a, T>),
    /// An option known to be `None`.
    None(NoneBucket<'a, T>),
}

impl<'a, T> OptionBucket<'a, T> {
    /// Create an `OptionBucket` from an `&mut Option`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed_map::option_bucket::OptionBucket;
    ///
    /// let mut none: Option<i32> = None;
    /// let none_bucket = OptionBucket::new(&mut none);
    /// assert!(matches!(none_bucket, OptionBucket::None(_)));
    ///
    /// let mut some: Option<i32> = Some(12);
    /// let some_bucket = OptionBucket::new(&mut some);
    /// assert!(matches!(some_bucket, OptionBucket::Some(_)));
    /// ```
    #[inline]
    pub fn new(opt: &'a mut Option<T>) -> Self {
        if opt.is_some() {
            // SAFETY: if conditional ensures that `opt` is `Some`
            unsafe { OptionBucket::Some(SomeBucket::new_unchecked(opt)) }
        } else {
            // SAFETY: if conditional ensures that `opt` is `None`
            unsafe { OptionBucket::None(NoneBucket::new_unchecked(opt)) }
        }
    }
}