mahf 0.1.0

A framework for modular construction and evaluation of metaheuristics.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! A reimplementation of the entry API of [`HashMap::entry`], but for [`StateRegistry`].
//!
//! [`HashMap::entry`]: std::collections::HashMap::entry
//! [`StateRegistry`]: crate::StateRegistry

use std::{
    any::TypeId,
    cell::{Ref, RefCell, RefMut},
    collections::hash_map,
    marker::PhantomData,
    ops::DerefMut,
};

use better_any::TidExt;

use crate::CustomState;

/// Entry for [`StateMap`].
///
/// [`StateMap`]: crate::state::registry::StateMap
pub type HashMapEntry<'a, 'b> = hash_map::Entry<'a, TypeId, RefCell<Box<dyn CustomState<'b>>>>;

/// A view into a single entry in a state registry, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`StateRegistry`].
///
/// [`entry`]: crate::StateRegistry::entry
/// [`StateRegistry`]: crate::StateRegistry
pub enum Entry<'a, 'b, T> {
    /// An occupied entry.
    Occupied(OccupiedEntry<'a, 'b, T>),
    /// A vacant entry.
    Vacant(VacantEntry<'a, 'b, T>),
}

impl<'a, 'b, T> Entry<'a, 'b, T>
where
    T: CustomState<'b>,
{
    pub(crate) fn new(entry: HashMapEntry<'a, 'b>) -> Self {
        match entry {
            HashMapEntry::Occupied(entry) => Self::Occupied(OccupiedEntry {
                base: entry,
                marker: PhantomData,
            }),
            HashMapEntry::Vacant(entry) => Self::Vacant(VacantEntry {
                base: entry,
                marker: PhantomData,
            }),
        }
    }

    /// Provides in-place mutable access to an occupied entry before any
    /// potential inserts into the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::StateRegistry;
    /// # #[derive(Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// registry.entry::<A>()
    ///    .and_modify(|mut a| { a.0 += 1 })
    ///    .or_insert(A(42));
    /// assert_eq!(registry.get_value::<A>(), 42);
    ///
    /// registry.entry::<A>()
    ///    .and_modify(|mut a| { a.0 += 1 })
    ///    .or_insert(A(42));
    /// assert_eq!(registry.get_value::<A>(), 43);
    /// ```
    #[inline]
    pub fn and_modify<F>(self, f: F) -> Self
    where
        F: FnOnce(RefMut<T>),
    {
        match self {
            Self::Occupied(mut entry) => {
                f(entry.get_mut());
                Self::Occupied(entry)
            }
            Self::Vacant(entry) => Self::Vacant(entry),
        }
    }

    /// Provides in-place mutable access to the value of an occupied entry before any
    /// potential inserts into the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::StateRegistry;
    /// # #[derive(Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// registry.entry::<A>()
    ///    .and_modify_value(|a| { *a += 1 })
    ///    .or_insert(A(42));
    /// assert_eq!(registry.get_value::<A>(), 42);
    ///
    /// registry.entry::<A>()
    ///    .and_modify_value(|a| { *a += 1 })
    ///    .or_insert(A(42));
    /// assert_eq!(registry.get_value::<A>(), 43);
    /// ```
    #[inline]
    pub fn and_modify_value<F>(self, f: F) -> Self
    where
        T: DerefMut,
        F: FnOnce(&mut T::Target),
    {
        match self {
            Self::Occupied(mut entry) => {
                f(entry.get_mut().deref_mut());
                Self::Occupied(entry)
            }
            Self::Vacant(entry) => Self::Vacant(entry),
        }
    }

    /// Ensures a value is in the entry by inserting `default` if empty, and returns
    /// a mutable reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::StateRegistry;
    /// # #[derive(Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// registry.entry::<A>().or_insert(A(3));
    /// assert_eq!(registry.get_value::<A>(), 3);
    ///
    /// registry.entry::<A>().or_insert(A(10)).0 *= 2;
    /// assert_eq!(registry.get_value::<A>(), 6);
    /// ```
    #[inline]
    pub fn or_insert(self, default: T) -> RefMut<'a, T> {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(default),
        }
    }

    /// 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.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::StateRegistry;
    /// # #[derive(Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// registry.entry::<A>().or_insert_with(|| A(3));
    /// assert_eq!(registry.get_value::<A>(), 3);
    ///
    /// registry.entry::<A>().or_insert_with(|| A(10)).0 *= 2;
    /// assert_eq!(registry.get_value::<A>(), 6);
    /// ```
    #[inline]
    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> RefMut<'a, T> {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(default()),
        }
    }
}

impl<'a, 'b, T> Entry<'a, 'b, T>
where
    T: CustomState<'b> + Default,
{
    /// Ensures a value is in the entry by inserting the default value if empty,
    /// and returns a mutable reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::StateRegistry;
    /// # #[derive(Default, Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// registry.entry::<A>().or_default(); // A defaults to A(0)
    /// assert_eq!(registry.get_value::<A>(), 0);
    /// ```
    #[inline]
    pub fn or_default(self) -> RefMut<'a, T> {
        match self {
            Self::Occupied(entry) => entry.into_mut(),
            Self::Vacant(entry) => entry.insert(Default::default()),
        }
    }
}

/// A view into an occupied entry in a [`StateRegistry`].
///
/// It is part of the [`Entry`] enum.
///
/// [`StateRegistry`]: crate::StateRegistry
pub struct OccupiedEntry<'a, 'b, T> {
    base: hash_map::OccupiedEntry<'a, TypeId, RefCell<Box<dyn CustomState<'b>>>>,
    marker: PhantomData<T>,
}

impl<'a, 'b, T> OccupiedEntry<'a, 'b, T>
where
    T: CustomState<'b>,
{
    /// Gets a reference to the value in the entry.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, PartialEq, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    /// registry.entry::<A>().or_insert(A(12));
    ///
    /// if let Entry::Occupied(o) = registry.entry::<A>() {
    ///     assert_eq!(&*o.get(), &A(12));
    /// }
    /// ```
    #[inline]
    pub fn get(&self) -> Ref<'_, T> {
        let cell = self.base.get();
        Ref::map(cell.borrow(), |x| {
            x.as_ref().downcast_ref().unwrap_or_else(|| {
                unreachable!("`OccupiedEntry<T>` should only be constructed for valid `T`")
            })
        })
    }

    /// Gets a mutable reference to the value in the entry.
    ///
    /// If you need a reference to the `OccupiedEntry` which may outlive the
    /// destruction of the `Entry` value, see [`into_mut`].
    ///
    /// [`into_mut`]: Self::into_mut
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, PartialEq, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    /// registry.entry::<A>().or_insert(A(12));
    ///
    /// assert_eq!(registry.get_value::<A>(), 12);
    /// if let Entry::Occupied(mut o) = registry.entry::<A>() {
    ///     o.get_mut().0 += 10;
    ///     assert_eq!(&*o.get(), &A(22));
    ///
    ///     // We can use the same Entry multiple times, given that the
    ///     // reference by the previous `get_mut` is dropped before.
    ///     o.get_mut().0 += 2;
    /// }
    ///
    /// assert_eq!(registry.get_value::<A>(), 24);
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> RefMut<'_, T> {
        let cell = self.base.get_mut();
        RefMut::map(cell.borrow_mut(), |x| {
            x.as_mut().downcast_mut().unwrap_or_else(|| {
                unreachable!("`OccupiedEntry<T>` should only be constructed for valid `T`")
            })
        })
    }

    /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
    /// with a lifetime bound to the registry itself.
    ///
    /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
    ///
    /// [`get_mut`]: Self::get_mut
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, PartialEq, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    /// registry.entry::<A>().or_insert(A(12));
    ///
    /// assert_eq!(registry.get_value::<A>(), 12);
    /// if let Entry::Occupied(o) = registry.entry::<A>() {
    ///     o.into_mut().0 += 10;
    /// }
    ///
    /// assert_eq!(registry.get_value::<A>(), 22);
    /// ```
    #[inline]
    pub fn into_mut(self) -> RefMut<'a, T> {
        let cell = self.base.into_mut();
        RefMut::map(cell.borrow_mut(), |x| {
            x.as_mut().downcast_mut().unwrap_or_else(|| {
                unreachable!("`OccupiedEntry<T>` should only be constructed for valid `T`")
            })
        })
    }

    /// Sets the value of the entry, and returns the entry's old value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, PartialEq, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    /// registry.entry::<A>().or_insert(A(12));
    ///
    /// if let Entry::Occupied(mut o) = registry.entry::<A>() {
    ///     assert_eq!(o.insert(A(15)), A(12));
    /// }
    ///
    /// assert_eq!(registry.get_value::<A>(), 15);
    /// ```
    #[inline]
    pub fn insert(&mut self, value: T) -> T {
        let cell = RefCell::new(Box::new(value));
        *self
            .base
            .insert(cell)
            .into_inner()
            .downcast_box()
            .unwrap_or_else(|_| {
                unreachable!("`OccupiedEntry<T>` should only be constructed for valid `T`")
            })
    }

    /// Takes the value out of the entry, and returns it.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, PartialEq, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    /// registry.entry::<A>().or_insert(A(12));
    ///
    /// if let Entry::Occupied(o) = registry.entry::<A>() {
    ///     assert_eq!(o.remove(), A(12));
    /// }
    ///
    /// assert_eq!(registry.contains_at_top::<A>(), false);
    /// ```
    #[inline]
    pub fn remove(self) -> T {
        let cell = self.base.remove();
        *cell.into_inner().downcast_box().unwrap_or_else(|_| {
            unreachable!("`OccupiedEntry<T>` should only be constructed for valid `T`")
        })
    }
}

/// A view into an vacant entry in a [`StateRegistry`].
///
/// It is part of the [`Entry`] enum.
///
/// [`StateRegistry`]: crate::StateRegistry
pub struct VacantEntry<'a, 'b, T> {
    base: hash_map::VacantEntry<'a, TypeId, RefCell<Box<dyn CustomState<'b>>>>,
    marker: PhantomData<T>,
}

impl<'a, 'b, T> VacantEntry<'a, 'b, T>
where
    T: CustomState<'b>,
{
    /// Sets the value of the entry with the `VacantEntry`'s key,
    /// and returns a mutable reference to it.
    ///
    /// # Examples
    ///
    /// ```
    /// # use better_any::{Tid, TidAble};
    /// # use derive_more::{Deref, DerefMut};
    /// # use mahf::CustomState;
    /// use mahf::{state::registry::Entry, StateRegistry};
    /// # #[derive(Default, Debug, Deref, DerefMut, Tid)]
    /// # pub struct A(usize);
    /// # impl CustomState<'_> for A {}
    ///
    /// let mut registry = StateRegistry::new();
    ///
    /// if let Entry::Vacant(o) = registry.entry::<A>() {
    ///     o.insert(A(37));
    /// }
    /// assert_eq!(registry.get_value::<A>(), 37);
    /// ```
    #[inline]
    pub fn insert(self, value: T) -> RefMut<'a, T> {
        let cell = RefCell::new(Box::new(value));
        RefMut::map(self.base.insert(cell).borrow_mut(), |x| {
            x.as_mut()
                .downcast_mut()
                .unwrap_or_else(|| unreachable!("`T` should have been inserted before this call"))
        })
    }
}