ctxmap 0.5.0

A collection that can store references of different types and lifetimes.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// #![include_doc("../../README.md", start("A collection that can store references of different types and lifetimes."))]
//! A collection that can store references of different types and lifetimes.
//!
//! ## Install
//!
//! Add this to your Cargo.toml:
//!
//! ```toml
//! [dependencies]
//! ctxmap = "0.5.0"
//! ```
//!
//! ## Example
//!
//! ```rust
//! ctxmap::schema!(Schema);
//! ctxmap::key!(Schema {
//!     KEY_NO_DEFAULT: u32,
//!     KEY_INT: u32 = 10,
//!     KEY_DYN: dyn std::fmt::Display = 10,
//!     KEY_STR: str = "abc",
//!     KEY_STRING: str = format!("abc-{}", 10),
//!     mut KEY_MUT: u32 = 30,
//! });
//!
//! let mut m = ctxmap::CtxMap::new();
//! assert_eq!(m.get(&KEY_NO_DEFAULT), None);
//! assert_eq!(m.get(&KEY_INT), Some(&10));
//! assert_eq!(m[&KEY_INT], 10);
//! assert_eq!(&m[&KEY_STR], "abc");
//!
//! m.with(&KEY_INT, &20, |m| {
//!     assert_eq!(m[&KEY_INT], 20);
//! });
//! assert_eq!(m[&KEY_INT], 10);
//!
//! assert_eq!(m[&KEY_MUT], 30);
//! m[&KEY_MUT] = 40;
//! assert_eq!(m[&KEY_MUT], 40);
//!
//! m.with_mut(&KEY_MUT, &mut 50, |m| {
//!     assert_eq!(m[&KEY_MUT], 50);
//!     m[&KEY_MUT] = 60;
//!     assert_eq!(m[&KEY_MUT], 60);
//! });
//! assert_eq!(m[&KEY_MUT], 40);
//! ```
// #![include_doc("../../README.md", end("## License"))]

use helpers::*;
use std::{
    any::Any,
    cell::UnsafeCell,
    marker::PhantomData,
    ops::{Index, IndexMut},
};

/// A collection that can store references of different types and lifetimes.
pub struct CtxMap<S: Schema> {
    schema: PhantomData<S>,
    ptrs: Vec<Option<*const dyn Any>>,
    values: UnsafeCell<Vec<Option<Box<dyn Any>>>>,
}

impl<S: Schema> CtxMap<S> {
    /// Create a new `CtxMap` with initial values.
    ///
    /// # Example
    ///
    /// ```
    /// ctxmap::schema!(S);
    /// ctxmap::key!(S { KEY_A: u16 = 20 });
    /// ctxmap::key!(S { KEY_B: u8 });
    ///
    /// let m = ctxmap::CtxMap::new();
    /// assert_eq!(m[&KEY_A], 20);
    /// assert_eq!(m.get(&KEY_A), Some(&20));
    /// assert_eq!(m.get(&KEY_B), None);
    /// ```
    pub fn new() -> Self {
        Self {
            schema: PhantomData,
            values: UnsafeCell::new(Vec::new()),
            ptrs: Vec::new(),
        }
    }

    /// Sets a value corresponding to the key only while `f` is being called.
    ///
    /// # Example
    ///
    /// ```
    /// ctxmap::schema!(S);
    /// ctxmap::key!(S { KEY_A: u16 = 20 });
    ///
    /// let mut m = ctxmap::CtxMap::new();
    /// assert_eq!(m[&KEY_A], 20);
    /// m.with(&KEY_A, &30, |m| {
    ///     assert_eq!(m[&KEY_A], 30);
    /// });
    /// assert_eq!(m[&KEY_A], 20);
    /// ```
    pub fn with<T: ?Sized + 'static, U>(
        &mut self,
        key: &'static Key<S, T>,
        value: &T,
        f: impl FnOnce(&mut CtxMapView<S>) -> U,
    ) -> U {
        self.view().with(key, value, f)
    }

    /// Sets a mutable value corresponding to the key only while `f` is being called.
    ///
    /// # Example
    ///
    /// ```
    /// ctxmap::schema!(S);
    /// ctxmap::key!(S { mut KEY_A: u16 = 20 });
    ///
    /// let mut m = ctxmap::CtxMap::new();
    /// assert_eq!(m[&KEY_A], 20);
    /// m[&KEY_A] = 25;
    /// assert_eq!(m[&KEY_A], 25);
    /// m.with_mut(&KEY_A, &mut 30, |m| {
    ///     assert_eq!(m[&KEY_A], 30);
    ///     m[&KEY_A] = 35;
    ///     assert_eq!(m[&KEY_A], 35);
    /// });
    /// assert_eq!(m[&KEY_A], 25);
    /// ```
    pub fn with_mut<T: ?Sized + 'static, U, const MUT: bool>(
        &mut self,
        key: &'static Key<S, T, MUT>,
        value: &mut T,
        f: impl FnOnce(&mut CtxMapView<S>) -> U,
    ) -> U {
        self.view().with_mut(key, value, f)
    }

    /// Get [`CtxMapView`] that references `self`.
    pub fn view(&mut self) -> CtxMapView<S> {
        CtxMapView(self)
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// # Example
    ///
    /// ```
    /// ctxmap::schema!(S);
    /// ctxmap::key!(S { KEY_A: u16 });
    ///
    /// let mut m = ctxmap::CtxMap::new();
    /// assert_eq!(m.get(&KEY_A), None);
    /// m.with(&KEY_A, &10, |m| {
    ///     assert_eq!(m.get(&KEY_A), Some(&10));
    /// });
    /// assert_eq!(m.get(&KEY_A), None);
    /// ```
    pub fn get<T: ?Sized, const MUT: bool>(&self, key: &'static Key<S, T, MUT>) -> Option<&T> {
        let index = key.index;
        unsafe {
            if let Some(Some(p)) = self.ptrs.get(index) {
                if let Some(p) = <dyn Any>::downcast_ref::<*const T>(&**p) {
                    Some(&**p)
                } else if let Some(p) = <dyn Any>::downcast_ref::<*mut T>(&**p) {
                    Some(&**p)
                } else {
                    unreachable!()
                }
            } else {
                let data = key.data.as_ref()?.as_ref();
                loop {
                    if let Some(Some(value)) = (*self.values.get()).get(index) {
                        let p: *const dyn Any = value.as_ref();
                        return Some(data.get(&*p));
                    }
                    self.init_value(index, data);
                }
            }
        }
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// # Example
    ///
    /// ```
    /// ctxmap::schema!(S);
    /// ctxmap::key!(S { mut KEY_A: u16 });
    ///
    /// let mut m = ctxmap::CtxMap::new();
    /// assert_eq!(m.get_mut(&KEY_A), None);
    /// m.with_mut(&KEY_A, &mut 10, |m| {
    ///     assert_eq!(m.get_mut(&KEY_A), Some(&mut 10));
    /// });
    /// assert_eq!(m.get_mut(&KEY_A), None);
    /// ```
    pub fn get_mut<T: ?Sized>(&mut self, key: &'static KeyMut<S, T>) -> Option<&mut T> {
        let index = key.index;
        unsafe {
            if let Some(Some(p)) = self.ptrs.get(index) {
                Some(&mut **<dyn Any>::downcast_ref::<*mut T>(&**p).unwrap())
            } else {
                let data = key.data.as_ref()?.as_ref();
                loop {
                    if let Some(Some(value)) = (*self.values.get()).get_mut(index) {
                        let p: *mut dyn Any = value.as_mut();
                        return Some(data.get_mut(&mut *p));
                    }
                    self.init_value(index, data);
                }
            }
        }
    }
    unsafe fn init_value<T: ?Sized>(&self, index: usize, data: &dyn KeyData<T>) {
        let init = data.init();
        let values = &mut *self.values.get();
        if values.len() <= index {
            values.resize_with(index + 1, || None);
        }
        values[index] = Some(init);
    }
}

impl<S: Schema> Default for CtxMap<S> {
    fn default() -> Self {
        Self::new()
    }
}
impl<S, T, const MUT: bool> Index<&'static Key<S, T, MUT>> for CtxMap<S>
where
    S: Schema,
    T: ?Sized + 'static,
{
    type Output = T;

    fn index(&self, index: &'static Key<S, T, MUT>) -> &Self::Output {
        self.get(index).expect("no entry found for key")
    }
}
impl<S, T> IndexMut<&'static KeyMut<S, T>> for CtxMap<S>
where
    S: Schema,
    T: ?Sized + 'static,
{
    fn index_mut(&mut self, index: &'static KeyMut<S, T>) -> &mut Self::Output {
        self.get_mut(index).expect("no entry found for key")
    }
}

/// Mutable reference to [`CtxMap`] where the value has changed.
///
/// Use `CtxMapViwe` instead of `&mut CtxMap` because `&mut CtxMap`,
/// whose value has been changed, will be broken if [`std::mem::swap`] is used.
pub struct CtxMapView<'a, S: Schema>(&'a mut CtxMap<S>);

impl<'a, S: Schema> CtxMapView<'a, S> {
    /// Sets a value to `CtxMap` only while `f` is being called.
    ///
    /// See [`CtxMap::with`] for more details.
    pub fn with<T: ?Sized + 'static, U>(
        &mut self,
        key: &'static Key<S, T>,
        value: &T,
        f: impl FnOnce(&mut CtxMapView<S>) -> U,
    ) -> U {
        let ptr: *const T = value;
        self.with_impl(key, ptr, f)
    }

    /// Sets a mutable value to `CtxMap` only while `f` is being called.
    ///
    /// See [`CtxMap::with_mut`] for more details.
    pub fn with_mut<T: ?Sized + 'static, U, const MUT: bool>(
        &mut self,
        key: &'static Key<S, T, MUT>,
        value: &mut T,
        f: impl FnOnce(&mut CtxMapView<S>) -> U,
    ) -> U {
        let ptr: *mut T = value;
        self.with_impl(key, ptr, f)
    }

    fn with_impl<T: ?Sized + 'static, U, P: 'static, const MUT: bool>(
        &mut self,
        key: &'static Key<S, T, MUT>,
        ptr: P,
        f: impl FnOnce(&mut CtxMapView<S>) -> U,
    ) -> U {
        let index = key.index;
        if self.0.ptrs.len() <= index {
            self.0.ptrs.resize_with(index + 1, || None);
        }
        let old = self.0.ptrs[index];
        self.0.ptrs[index] = Some(&ptr);
        let retval = f(self);
        self.0.ptrs[index] = old;
        retval
    }

    /// Return `CtxMapView` with modified lifetime.
    pub fn view(&mut self) -> CtxMapView<S> {
        CtxMapView(self.0)
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// See [`CtxMap::get`] for more details.
    pub fn get<T: ?Sized, const MUT: bool>(&self, key: &'static Key<S, T, MUT>) -> Option<&T> {
        self.0.get(key)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// See [`CtxMap::get_mut`] for more details.
    pub fn get_mut<T: ?Sized>(&mut self, key: &'static KeyMut<S, T>) -> Option<&mut T> {
        self.0.get_mut(key)
    }
}

impl<'a, S, T, const MUT: bool> Index<&'static Key<S, T, MUT>> for CtxMapView<'a, S>
where
    S: Schema,
    T: ?Sized + 'static,
{
    type Output = T;

    fn index(&self, index: &'static Key<S, T, MUT>) -> &Self::Output {
        &self.0[index]
    }
}
impl<'a, S, T> IndexMut<&'static KeyMut<S, T>> for CtxMapView<'a, S>
where
    S: Schema,
    T: ?Sized + 'static,
{
    fn index_mut(&mut self, index: &'static KeyMut<S, T>) -> &mut Self::Output {
        &mut self.0[index]
    }
}

/// A key for [`CtxMap`].
///
/// Use [`key`] macro to create `Key`.
pub struct Key<S: Schema, T: ?Sized + 'static, const MUT: bool = false> {
    schema: PhantomData<S>,
    index: usize,
    data: Option<Box<dyn KeyData<T>>>,
}
pub type KeyMut<S, T> = Key<S, T, true>;

trait KeyData<T: ?Sized>: Send + Sync {
    fn get<'a>(&self, value: &'a dyn Any) -> &'a T;
    fn get_mut<'a>(&self, value: &'a mut dyn Any) -> &'a mut T;
    fn init(&self) -> Box<dyn Any>;
}

/// Key collection for [`CtxMap`].
///
/// Use [`schema`] macro to define a type that implement `Schema`.
pub trait Schema: 'static + Sized {
    fn data() -> &'static SchemaData;

    fn key<T: ?Sized>() -> Key<Self, T> {
        Key {
            schema: PhantomData,
            index: Self::data().push_key(),
            data: None,
        }
    }
    fn key_mut<T: ?Sized>() -> KeyMut<Self, T> {
        Key {
            schema: PhantomData,
            index: Self::data().push_key(),
            data: None,
        }
    }

    fn key_with_default<Init, ToRef, V, T>(init: Init, to_ref: ToRef) -> Key<Self, T>
    where
        Init: Send + Sync + Fn() -> V + 'static,
        ToRef: Send + Sync + Fn(&V) -> &T + 'static,
        V: 'static,
        T: ?Sized,
    {
        fn to_mut_unreachable<V, T: ?Sized>(_: &mut V) -> &mut T {
            unreachable!()
        }

        Key {
            schema: PhantomData,
            index: Self::data().push_key(),
            data: Some(Box::new(KeyDataValue {
                init,
                to_ref,
                to_mut: to_mut_unreachable,
            })),
        }
    }
    fn key_mut_with_default<Init, ToRef, ToMut, V, T>(
        init: Init,
        to_ref: ToRef,
        to_mut: ToMut,
    ) -> KeyMut<Self, T>
    where
        Init: Send + Sync + Fn() -> V + 'static,
        ToRef: Send + Sync + Fn(&V) -> &T + 'static,
        ToMut: Send + Sync + Fn(&mut V) -> &mut T + 'static,
        V: 'static,
        T: ?Sized,
    {
        Key {
            schema: PhantomData,
            index: Self::data().push_key(),
            data: Some(Box::new(KeyDataValue {
                init,
                to_ref,
                to_mut,
            })),
        }
    }
}

struct KeyDataValue<Init, ToRef, ToMut> {
    init: Init,
    to_ref: ToRef,
    to_mut: ToMut,
}

impl<Init, ToRef, ToMut, V, T> KeyData<T> for KeyDataValue<Init, ToRef, ToMut>
where
    Init: Send + Sync + Fn() -> V,
    ToRef: Send + Sync + Fn(&V) -> &T,
    ToMut: Send + Sync + Fn(&mut V) -> &mut T,
    V: 'static,
    T: ?Sized,
{
    fn get<'a>(&self, value: &'a dyn Any) -> &'a T {
        (self.to_ref)(<dyn Any>::downcast_ref::<V>(value).unwrap())
    }
    fn get_mut<'a>(&self, value: &'a mut dyn Any) -> &'a mut T {
        (self.to_mut)(<dyn Any>::downcast_mut::<V>(value).unwrap())
    }
    fn init(&self) -> Box<dyn Any> {
        Box::new((self.init)())
    }
}

#[doc(hidden)]
pub mod helpers {
    use crate::Schema;
    pub use once_cell::sync::Lazy;
    use std::{
        ops::Deref,
        sync::atomic::{AtomicUsize, Ordering},
    };

    pub struct SchemaData {
        next: AtomicUsize,
    }

    impl SchemaData {
        pub const fn new() -> Self {
            SchemaData {
                next: AtomicUsize::new(0),
            }
        }
        pub(crate) fn push_key(&self) -> usize {
            self.next.fetch_add(1, Ordering::SeqCst)
        }
    }

    pub struct Key<S: Schema, T: ?Sized + 'static, const MUT: bool = false>(
        Lazy<crate::Key<S, T, MUT>>,
    );
    pub struct KeyMut<S: Schema, T: ?Sized + 'static>(Lazy<crate::KeyMut<S, T>>);

    impl<S: Schema, T: ?Sized + 'static> Key<S, T> {
        pub const fn new(f: fn() -> crate::Key<S, T>) -> Self {
            Self(Lazy::new(f))
        }
    }
    impl<S: Schema, T: ?Sized + 'static> Deref for Key<S, T> {
        type Target = crate::Key<S, T>;
        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }
    impl<S: Schema, T: ?Sized + 'static> KeyMut<S, T> {
        pub const fn new(f: fn() -> crate::KeyMut<S, T>) -> Self {
            Self(Lazy::new(f))
        }
    }
    impl<S: Schema, T: ?Sized + 'static> Deref for KeyMut<S, T> {
        type Target = crate::KeyMut<S, T>;
        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }
}

/// Define a type that implements [`Schema`].
///
/// # Example
///
/// ```
/// ctxmap::schema!(S1);
/// ctxmap::schema!(pub S2);
/// ```
#[macro_export]
macro_rules! schema {
    ($vis:vis $id:ident) => {
        $vis struct $id;
        impl $crate::Schema for $id {
            fn data() -> &'static $crate::helpers::SchemaData {
                static DATA: $crate::helpers::SchemaData = $crate::helpers::SchemaData::new();
                &DATA
            }
        }

    };
}

/// Define a key for [`CtxMap`].
///
/// # Example
///
/// ```
/// ctxmap::schema!(S);
/// ctxmap::key!(S { KEY_1: u8 });
/// ctxmap::key!(S { KEY_2: str });
/// ```
///
/// You can define multiple keys at once.
///
/// ```
/// ctxmap::schema!(S);
/// ctxmap::key!(S {
///     KEY_1: u8,
///     KEY_2: str,
/// });
/// ```
///
/// You can specify a default value.
///
/// The default value can be an expression that, when applied with `&` operator, becomes a reference to the type of the key.
///
/// For example, `&"abc"` and `&String::new()` can be `&str`,
/// so `"abc"` and `String::new()` can be used as default values for keys of type `str`.
///
/// ```
/// use std::fmt::Display;
///
/// ctxmap::schema!(S);
/// ctxmap::key!(S {
///     KEY_1: u8 = 10,
///     KEY_2: str = "abc",
///     KEY_3: str = String::new(),
///     KEY_4: dyn Display = 10,
///     KEY_5: dyn Display = "xyz",
/// });
/// ```
///
/// You can specify mutability.
///
/// Keys with `mut` can be used in [`with_mut`](CtxMap::with_mut), [`get_mut`](CtxMap::get_mut) and [`index_mut`](CtxMap::index_mut).
///
/// ```
/// ctxmap::schema!(S);
/// ctxmap::key!(S {
///     mut KEY_1: u8,
///     mut KEY_2: String,
/// });
/// ```
///
/// You can specify visibility.
///
/// ```
/// ctxmap::schema!(pub S);
/// ctxmap::key!(S { KEY_A: u8 });
/// ctxmap::key!(S { pub KEY_B: u8 });
/// ctxmap::key!(S { pub(crate) KEY_C: u8 });
/// ```
#[macro_export]
macro_rules! key {
    ($schema:ty { }) => { };
    ($schema:ty { $vis:vis $id:ident: $type:ty }) => {
        $vis static $id: $crate::helpers::Key<$schema, $type> =
            $crate::helpers::Key::new(|| <$schema as $crate::Schema>::key());
    };
    ($schema:ty { $vis:vis mut $id:ident: $type:ty }) => {
        $vis static $id: $crate::helpers::KeyMut<$schema, $type> =
            $crate::helpers::KeyMut::new(|| <$schema as $crate::Schema>::key_mut());
    };
    ($schema:ty { $vis:vis $id:ident: $type:ty = $init:expr }) => {
        $vis static $id: $crate::helpers::Key<$schema, $type> =
            $crate::helpers::Key::new(|| <$schema as $crate::Schema>::key_with_default::<_, _, _, $type>(
                || $init,
                |x| x));
    };
    ($schema:ty { $vis:vis mut $id:ident: $type:ty = $init:expr }) => {
        $vis static $id: $crate::helpers::KeyMut<$schema, $type> =
            $crate::helpers::KeyMut::new(|| <$schema as $crate::Schema>::key_mut_with_default::<_, _, _, _, $type>(
                || $init,
                |x| x,
                |x| x));
    };
    ($schema:ty { $vis:vis $id:ident: $type:ty, $($tt:tt)* }) => {
        $crate::key!($schema { $vis $id: $type });
        $crate::key!($schema { $($tt)* });
    };
    ($schema:ty { $vis:vis mut $id:ident: $type:ty, $($tt:tt)* }) => {
        $crate::key!($schema { $vis mut $id: $type });
        $crate::key!($schema { $($tt)* });
    };
    ($schema:ty { $vis:vis $id:ident: $type:ty = $init:expr, $($tt:tt)* }) => {
        $crate::key!($schema { $vis $id: $type = $init });
        $crate::key!($schema { $($tt)* });
    };
    ($schema:ty { $vis:vis mut $id:ident: $type:ty = $init:expr, $($tt:tt)* }) => {
        $crate::key!($schema { $vis mut $id: $type = $init });
        $crate::key!($schema { $($tt)* });
    };

}