ctoption 0.1.0

A compile-time option whose discriminant is elevated to compile time.
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
#![doc = include_str!("../README.md")]
#![no_std]
#![cfg_attr(feature = "const_trait_impl", feature(const_trait_impl))]
#![cfg_attr(feature = "core_intrinsics", feature(core_intrinsics))]
#![cfg_attr(
    feature = "adt_const_params",
    allow(incomplete_features),
    feature(adt_const_params)
)]
#![cfg_attr(
    feature = "const_precise_live_drops",
    feature(const_precise_live_drops)
)]

use core::mem::{ManuallyDrop, MaybeUninit};

/// A [`prelude`] for this crate, which is meant to be used as `use ctoption::prelude::*;`.
///
/// [`prelude`]: https://doc.rust-lang.org/std/prelude/index.html#other-preludes
pub mod prelude;

/// A compile-time alternative to [`Option`]. Unlike [`Option`],
/// this type is guaranteed to have the same size and alignmemt as `T`.
///
/// This type is especially useful for software targetting memory-constrained
/// environments where the size of types matters. However, its interface
/// can be just as ergonomic as that of [`Option`].
///
/// One important application of this type is a category of [Type State] variations
/// of the [Builder Pattern]. One example implementation of this pattern
/// will be provided after a few more beginner-friendly examples.
///
/// # Examples
///
/// ## Create and get the inner value back
///
/// ```
/// use ctoption::prelude::*;
///
/// // enforcing constant evaluation
/// const _: () = {
///     let some = CTSome::new(42);
///     assert!(some.into_inner() == 42);
/// };
/// ```
///
/// This crate offers a [`prelude`] module with the most essential items.
///
/// One of these items is the [`CTSome`] type alias, which is a convenience
/// type inspired by [`Some`] variant of the [`Option`] type.
///
/// `CTSome::new` and `CTSome::into_inner` are the two inverse associated
/// functions. One wraps a value in a `CTSome` instance, while the other
/// turns the [`CTSome`] instance into the inner value.
///
/// ## Create empty, insert the value, and get the value back
///
/// ```
/// use ctoption::prelude::*;
///
/// const _: () = {
///     let none = CTNone::new();
///     let some = none.insert(42);
///     assert!(some.into_inner() == 42);
/// };
/// ```
///
/// or, if slightly [unsugared],
///
/// ```
/// use ctoption::prelude::*;
///
/// const _: () = {
///     let none: CTOption<i32,IS_NONE> = CTNone::<i32>::new();
///     let some: CTOption<i32,IS_SOME> = {
///         let v: CTSome<i32> = none.insert(42);
///         v
///     };
///     assert!(some.into_inner() == 42);
/// };
/// ```
///
/// Similarly to [`CTSome`], [`CTNone`] is a type alias inspired by an
/// enum variant of [`Option`] type - [`None`].
///
/// The fact that [`CTSome`] and [`CTNone`] are type aliases and not
/// enum variants has deep impact on the API. Compare the code above
/// to the nearly equivalent code using [`Option`] type:
///
/// ```
/// // unwrap is unstable in const context
/// // const _: () = {
///     let mut enum_instance = None;
///     enum_instance = Some(42);
///     assert!(enum_instance.unwrap() == 42);
/// // };
/// ```
///
/// or, if unsugared similarly,
///
/// ```
/// // const _: () = {
///     let mut enum_instance: Option<i32> = None::<i32>;
///     enum_instance = Some::<i32>(42);
///     assert!(enum_instance.unwrap() == 42);
/// // };
/// ```
///
/// Unlike [`Some`] and [`None`] enum variants of [`Option`] type, [`CTSome`]
/// and [`CTNone`] correspond to (distinct) types themselves and do not
/// share a common overarching [contravariant] type (except for `!`) for every
/// parameterization. Therefore, turning an instance of one `CT*` type into an
/// instance of another `CT*` type requires juggling owned values. This is the
/// reason why the `CTNone::insert` associated function accepts an owned value
/// of [`CTNone`] and returns an owned value of [`CTSome`] - a mutable reference
/// wouldn't suffice.
///
/// However, both [`CTSome`] and [`CTNone`] are merely type aliases which allow
/// to conveniently refer to different partial parametrizations of the same
/// generic type - [`CTOption`].
///
/// ## Matching `CTOption` instances in generic code
///
/// It would be awesome if we could write something like this:
///
/// ```compile_fail
/// const fn get_ty_alias_name<T, const IS_SOME_VAL: bool>(opt: &CTOption<T, IS_SOME_VAL>) -> &'static str {
///     match opt {
///         CTSome(x) => {
///             "CTSome"
///         }
///         CTNone => {
///             "CTNone"
///         }
///     }
/// }
/// ```
///
/// However, this code won't work because match expression doesn't allow to match the value against
/// different types. If you try to do this, you'll get
/// [`error[E0532]: expected tuple struct or tuple variant, found type alias CTSome.`][E0532]
///
/// Then what about matching against the value of `IS_SOME_VAL`? Let's say we want to write a cleanup function.
///
/// ```compile_fail
/// const fn do_one_thing() {}
/// const fn do_another_thing() {}
///
/// const fn extra_cleanup<T, const IS_SOME_VAL: bool>(opt: CTOption<T, IS_SOME_VAL>) {
///     match IS_SOME_VAL {
///         true => {
///             do_one_thing()
///         }
///         false => {
///             do_another_thing()
///         }
///     }
/// }
/// ```
///
/// Then you'll encounter another problem:
/// [`error[E0493]: destructor of CTOption<T, IS_SOME_VAL> cannot be evaluated at compile-time`][E0493]. This
/// happens because [`CTOption`] has a custom implementation of [`Drop`] trait and custom implementations
/// cannot be evaluated at compile-time.
///
/// In theory, this could eventually be solved by [`core::marker::Destruct`] trait, but it is not the case
/// at the moment of writing this.
///
/// **Workaround:** for the time being, you can use [`CTOption::assume_some`] and [`CTOption::assume_none`].
///
/// [Type State]: http://cliffle.com/blog/rust-typestate/
/// [Builder Pattern]: https://rust-unofficial.github.io/patterns/patterns/creational/builder.html
/// [contravariant]: https://en.m.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
/// [unsugared]: https://en.wikipedia.org/wiki/Syntactic_sugar
/// [E0532]: https://doc.rust-lang.org/error_codes/E0532.html
/// [E0493]: https://doc.rust-lang.org/error_codes/E0493.html
#[repr(transparent)]
pub struct CTOption<T, const IS_SOME_VAL: bool>(MaybeUninit<T>);

/// A convenience constant for `true`, which is used to indicate that
/// the [`CTOption`] instance is a [`CTSome`].
pub const IS_SOME: bool = true;

/// A convenience constant for `false`, which is used to indicate that
/// the [`CTOption`] instance is a [`CTNone`].
pub const IS_NONE: bool = false;

// the literals are used in the constants due to the bug of rust-analyzer:
// https://github.com/rust-lang/rust-analyzer/issues/15821

/// A convenience type alias for [`CTOption`] with `true` as the second
/// type parameter. This type alias is inspired by the [`Some`] variant
/// of the [`Option`] type.
pub type CTSome<T> = CTOption<T, true>;

/// A convenience type alias for [`CTOption`] with `false` as the second
/// type parameter. This type alias is inspired by the [`None`] variant
/// of the [`Option`] type.
pub type CTNone<T> = CTOption<T, false>;

#[doc(hidden)]
pub unsafe trait OptionalConstGeneric {
    type Inner;
    const IS_SOME_VAL: bool;
}

#[cfg(feature = "adt_const_params")]
pub mod workarounds {
    use core::marker::ConstParamTy;

    #[derive(Eq, PartialEq, ConstParamTy)]
    pub enum Option<T> {
        Some(T),
        None,
    }

    impl<T> Option<T> {
        #[cfg(feature = "const_precise_live_drops")]
        pub const fn into_core(self) -> core::option::Option<T> {
            match self {
                Self::Some(x) => core::option::Option::Some(x),
                Self::None => core::option::Option::None,
            }
        }
    }
}

unsafe impl<T, const IS_SOME_VAL: bool> OptionalConstGeneric for CTOption<T, IS_SOME_VAL> {
    type Inner = T;
    const IS_SOME_VAL: bool = IS_SOME_VAL;
}

#[cfg(feature = "core_intrinsics")]
pub mod opt_const_generic {
    use super::{CTSome, OptionalConstGeneric};
    use core::mem::MaybeUninit;

    pub const fn to_option<T: OptionalConstGeneric>(opt: T) -> Option<T::Inner> {
        let storage: MaybeUninit<T::Inner> = unsafe { core::intrinsics::transmute_unchecked(opt) };
        match T::IS_SOME_VAL {
            true => {
                let opt = unsafe { CTSome::<T::Inner>::from_maybe_uninit(storage) };
                Some(opt.into_inner())
            }
            false => None,
        }
    }
}

impl<T> CTSome<T> {
    /// Creates a new instance of [`CTSome`] from a value.
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const _: () = {
    ///    let some = CTSome::new(42);
    ///    assert!(some.into_inner() == 42);
    /// };
    /// ```
    pub const fn new(val: T) -> Self {
        Self(MaybeUninit::new(val))
    }

    /// Turns the [`CTSome`] instance into the inner value.
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const _: () = {
    ///   let some = CTSome::new(42);
    ///   assert!(some.into_inner() == 42);
    /// };
    #[doc(alias = "unwrap")]
    pub const fn into_inner(self) -> T {
        union CTSomeUnion<T> {
            md_ctsome: ManuallyDrop<CTSome<T>>,
            md_inner: ManuallyDrop<T>,
        }

        let md_ctsome = ManuallyDrop::new(self);

        let u = CTSomeUnion { md_ctsome };

        let md_inner = unsafe { u.md_inner };
        ManuallyDrop::into_inner(md_inner)
    }

    /// Assumes that the [`CTSome`] is an instance of [`CTOption`] with
    /// the provided `IS_SOME_VAL`. This may be needed in generic code
    /// where the [`CTSome`] instance was narrowed down from [`CTOption`]
    /// instance but the type inference is not powerful enough to infer
    /// that [`CTOption<T, IS_SOME_VAL>`] is the same as [`CTSome<T>`].
    pub const unsafe fn assume_const_generic_val<const IS_SOME_VAL: bool>(
        self,
    ) -> CTOption<T, IS_SOME_VAL> {
        union CTOptionVariantUnion<U, const NESTED_IS_SOME_VAL: bool> {
            md_ctsome: ManuallyDrop<CTSome<U>>,
            md_ctopt: ManuallyDrop<CTOption<U, NESTED_IS_SOME_VAL>>,
        }

        let md_ctsome = ManuallyDrop::new(self);
        let u = CTOptionVariantUnion { md_ctsome };
        let md_ctopt = unsafe { u.md_ctopt };
        ManuallyDrop::into_inner(md_ctopt)
    }
}

impl<T> CTNone<T> {
    // It does not make sense to have a non-const constructor for CTNone.
    #[allow(clippy::new_without_default)]
    /// Creates a new instance of [`CTNone`].
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const _: () = {
    ///   let none = CTNone::<i32>::new();
    ///   let some = none.insert(42);
    ///   assert!(some.into_inner() == 42);
    /// };
    pub const fn new() -> Self {
        Self(MaybeUninit::uninit())
    }

    /// Inserts a value into the storage of the [`CTNone`] instance
    /// and returns it as a [`CTSome`] instance.
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const _: () = {
    ///  let none = CTNone::<i32>::new();
    ///  let some = none.insert(42);
    ///  assert!(some.into_inner() == 42);
    /// };
    /// ```
    pub const fn insert(mut self, val: T) -> CTSome<T> {
        union CTOptionVariantUnion<T> {
            md_ctsome: ManuallyDrop<CTSome<T>>,
            md_ctnone: ManuallyDrop<CTNone<T>>,
        }

        self.0 = MaybeUninit::new(val);
        let md_ctnone = ManuallyDrop::new(self);
        let u = CTOptionVariantUnion { md_ctnone };
        let md_ctsome = unsafe { u.md_ctsome };
        ManuallyDrop::into_inner(md_ctsome)
    }

    /// Drops the [`CTNone`] instance without running the destructor.
    ///
    /// See [`core::mem::forget`] for more information.
    pub const fn forget(self) {
        core::mem::forget(self);
    }

    /// Assumes that the [`CTNone`] is an instance of [`CTOption`] with
    /// the provided `IS_SOME_VAL`. This may be needed in generic code
    /// where the [`CTNone`] instance was narrowed down from [`CTOption`]
    /// instance but the type inference is not powerful enough to infer
    /// that [`CTOption<T, IS_SOME_VAL>`] is the same as [`CTNone<T>`].
    pub const unsafe fn assume_const_generic_val<const IS_SOME_VAL: bool>(
        self,
    ) -> CTOption<T, IS_SOME_VAL> {
        union CTOptionVariantUnion<U, const NESTED_IS_SOME_VAL: bool> {
            md_ctnone: ManuallyDrop<CTNone<U>>,
            md_ctopt: ManuallyDrop<CTOption<U, NESTED_IS_SOME_VAL>>,
        }

        let md_ctnone = ManuallyDrop::new(self);
        let u = CTOptionVariantUnion { md_ctnone };
        let md_ctopt = unsafe { u.md_ctopt };
        ManuallyDrop::into_inner(md_ctopt)
    }
}

impl<T, const IS_SOME_VAL: bool> CTOption<T, IS_SOME_VAL> {
    /// Creates a new instance of [`CTOption`] from a [`MaybeUninit`] storage.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the value is properly initialized if
    /// `IS_SOME_VAL` is [`IS_SOME`].
    pub const unsafe fn from_maybe_uninit(val: MaybeUninit<T>) -> Self {
        Self(val)
    }

    /// Checks if the instance is actually [`CTSome`], rather than [`CTNone`].
    ///
    /// **Note:** At the moment of writing, calling the function in a generic context
    /// will **not** infer that
    ///
    /// 1. in the branch where [`is_some`](Self::is_some) returned `true`,
    /// // the type is actually [`CTSome`],
    /// 2. in the branch where [`is_some`](Self::is_some) returned `false`,
    /// // the type is actually [`CTNone`].
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const _: () = {
    ///  let some = CTSome::new(42);
    ///  assert!(some.is_some());
    ///  // destructor of `CTOption<i32, true>` cannot be evaluated at compile-time
    ///  // so we need to convert it into inner that can be evaluated at compile-time.
    ///  let _ = some.into_inner();
    /// };
    pub const fn is_some(&self) -> bool {
        IS_SOME_VAL
    }

    /// Turns the [`CTOption`] instance into [`CTSome`] instance without
    /// checking if the instance is a [`CTSome`].
    ///
    /// # Safety
    ///
    /// The caller must ensure that the underlying storage is properly initialized.
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const fn add_inner_or_none<const IS_SOME_VAL: bool>(a: u32, b: CTOption<u32, IS_SOME_VAL>) -> u32 {
    ///    if b.is_some() {
    ///      let some: CTSome<u32> = unsafe { b.assume_some() };
    ///      a + some.into_inner()
    ///    } else {
    ///      let none: CTNone<u32> = unsafe { b.assume_none() };
    ///      none.forget();
    ///      a
    ///    }
    /// }
    ///
    /// const _: () = {
    ///   let some = CTSome::new(2);
    ///   assert!(add_inner_or_none(2, some) == 4);
    ///   let none = CTNone::<u32>::new();
    ///   assert!(add_inner_or_none(2, none) == 2);
    /// };
    /// ```
    pub const unsafe fn assume_some(self) -> CTSome<T> {
        union CTOptionVariantUnion<U, const NESTED_IS_SOME_VAL: bool> {
            md_ctsome: ManuallyDrop<CTSome<U>>,
            md_ctopt: ManuallyDrop<CTOption<U, NESTED_IS_SOME_VAL>>,
        }

        let md_ctopt = ManuallyDrop::new(self);
        let u = CTOptionVariantUnion { md_ctopt };
        let md_ctsome = unsafe { u.md_ctsome };
        ManuallyDrop::into_inner(md_ctsome)
    }

    /// Turns the [`CTOption`] instance into [`CTNone`] instance without
    /// running the destructor.
    ///
    /// # Safety
    ///
    /// The caller must ensure that, if the original value was [`CTSome`],
    /// the destructor was run manually.
    ///
    /// # Example
    ///
    /// ```
    /// use ctoption::prelude::*;
    ///
    /// const fn add_inner_or_none<const IS_SOME_VAL: bool>(a: u32, b: CTOption<u32, IS_SOME_VAL>) -> u32 {
    ///   if b.is_some() {
    ///     let some: CTSome<u32> = unsafe { b.assume_some() };
    ///     a + some.into_inner()
    ///   } else {
    ///     let none: CTNone<u32> = unsafe { b.assume_none() };
    ///     none.forget();
    ///     a
    ///   }
    /// }
    ///
    /// const _: () = {
    ///     let some = CTSome::new(2);
    ///     assert!(add_inner_or_none(2, some) == 4);
    ///     let none = CTNone::<u32>::new();
    ///     assert!(add_inner_or_none(2, none) == 2);
    /// };
    pub const unsafe fn assume_none(self) -> CTNone<T> {
        union CTOptionVariantUnion<U, const NESTED_IS_SOME_VAL: bool> {
            md_ctnone: ManuallyDrop<CTNone<U>>,
            md_ctopt: ManuallyDrop<CTOption<U, NESTED_IS_SOME_VAL>>,
        }

        let md_ctopt = ManuallyDrop::new(self);
        let u = CTOptionVariantUnion { md_ctopt };
        let md_ctnone = unsafe { u.md_ctnone };
        ManuallyDrop::into_inner(md_ctnone)
    }

    // const fn map<F,O>(self, f: F) -> CTOption<O, IS_SOME_VAL>
    // where
    //     F: FnOnce(T) -> O,
    // {
    //     if self.is_some() {
    //         let some: CTSome<T> = unsafe { self.assume_some() };
    //         let inner: T = some.into_inner();
    //         let mapped_inner: O = f(inner);
    //         let mapped_some: CTSome<O> = CTSome::new(mapped_inner);
    //         unsafe { mapped_some.assume_const_generic_val() }
    //     } else {
    //         let none: CTNone<T> = unsafe { self.assume_none() };
    //         none.forget();
    //         let none: CTNone<O> = CTNone::new();
    //         unsafe { none.assume_const_generic_val() }
    //     }
    // }
}

#[cfg(not(feature = "const_trait_impl"))]
impl<T, const IS_SOME_VAL: bool> Drop for CTOption<T, IS_SOME_VAL> {
    fn drop(&mut self) {
        if IS_SOME_VAL {
            unsafe { self.0.assume_init_drop() }
        }
    }
}

#[cfg(feature = "const_trait_impl")]
macro_rules! provide_items_guarded_by_const_trait_impl {
    () => {
        // The items are in a macro because they use a new syntax, which is not
        // a valid Rust syntax at the moment of writing this.
        pub const fn const_drop<T: ~const core::marker::Destruct>(val: T) {
            core::mem::forget(val);
        }

        impl<T, const IS_SOME_VAL: bool> const Drop for CTOption<T, IS_SOME_VAL> {
            fn drop(&mut self) {
                if IS_SOME_VAL {
                    unsafe { self.0.assume_init_drop() }
                }
            }
        }
    };
}

#[cfg(feature = "const_trait_impl")]
provide_items_guarded_by_const_trait_impl!();

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    #[test]
    const fn into_inner_works() {
        let opt = CTSome::new(3);
        let v = opt.into_inner();
        if v != 3 {
            panic!("v != 3");
        }
    }

    #[test]
    const fn test_insert() {
        let none = CTNone::<i32>::new();
        let some = none.insert(42);
        assert!(some.into_inner() == 42);
    }
}