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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, Douglas Creager.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------

//! This crate provides a replacement for the standard [`Option`][] type where you have full
//! control over how the `None` and `Some` variants are represented in memory.
//!
//! Normally, you don't have to think about this.  The standard [`Option`][] is a perfectly normal
//! `enum`, and the compiler takes care of determining the most efficient in-memory representation.
//! In particular, the compiler knows that certain types have [_niches_][] — in-memory bit patterns
//! that do not represent valid values of the type.  If a type has a niche, then the compiler can
//! use that bit pattern to represent the `None` variant.  This works automatically for most of the
//! types you might care about: in particular, for references and the various `NonZero` types in
//! `std::num`.
//!
//! However, sometimes a type has _multiple_ possible niches, and you need control over which one
//! the compiler chooses to use.  Or, you might have defined a type such that the compiler cannot
//! see that it has a niche available to use.  In this case, you can use the `Niche` and
//! `ControlledOption` types from this crate to take full control over how the `None` and `Some`
//! variants are laid out in memory.
//!
//! [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
//! [_niches_]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche

use std::alloc::Layout;

/// A type should implement `Niche` if its memory representation has any bit patterns that do not
/// represent valid values.  If so, one of those can be used to represent the `None` case of an
/// option.
pub trait Niche: Sized {
    /// The type that is used to store values of `Self` inside of a `ControlledOption`.  This might
    /// be `Self` itself, if your niche is a valid instance of the type, but which violates some
    /// runtime constraint.  But if you cannot easily create your niche as an instance of `Self`,
    /// you can use some other type, you can use some other type instead.
    ///
    /// A word of caution: is it this `Output` type that is stored inside of a `ControlledOption`.
    /// If you want `ControlledOption<Self>` to have the same memory layout as `Self` (so that you
    /// can use `#[repr(transparent)]`, for instance), then you must ensure that `Self` and
    /// `Output` have the same layout, as determined by [`std::alloc::Layout::new`][new], and that
    /// every valid bit pattern for `Self` is be a valid bit pattern for `Output` that returns
    /// `true` for `is_some`.
    ///
    /// [new]: https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.new
    type Output;

    /// Returns the niche value for this type that should be used to represent `None` for a
    /// `ControlledOption`.
    fn none() -> Self::Output;

    /// Returns whether value is the niche value for this type.
    fn is_none(value: &Self::Output) -> bool;

    /// Transforms a non-niche value of this type into its `Output` type.  When `Output` is `Self`,
    /// this will be the identity function.
    fn into_some(value: Self) -> Self::Output;

    /// Transforms a non-niche value of this type from its `Output` type.  When `Output` is `Self`,
    /// this will be the identity function.
    fn from_some(value: Self::Output) -> Self;
}

/// An `Option` type where you have control over the in-memory representation of the `None` and
/// `Some` variants.  See the [module-level documentation][parent] for more information.
///
/// [parent]: index.html
#[repr(transparent)]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ControlledOption<T>
where
    T: Niche,
{
    value: T::Output,
}

impl<T> ControlledOption<T>
where
    T: Niche,
{
    /// Creates a new `None` instance for this option.
    #[inline]
    pub fn none() -> ControlledOption<T> {
        let value = T::none();
        debug_assert!(T::is_none(&value));
        ControlledOption { value }
    }

    /// Creates a new `Some` instance for this option.
    #[inline]
    pub fn some(value: T) -> ControlledOption<T> {
        let value = T::into_some(value);
        debug_assert!(!T::is_none(&value));
        ControlledOption { value }
    }

    /// Returns `true` is the option is a `None` value.
    #[inline]
    pub fn is_none(&self) -> bool {
        T::is_none(&self.value)
    }

    /// Returns `true` is the option is a `Some` value.
    #[inline]
    pub fn is_some(&self) -> bool {
        !T::is_none(&self.value)
    }

    /// Transforms an [`Option`][] into a `ControlledOption`.
    ///
    /// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
    #[inline]
    pub fn from_option(value: Option<T>) -> ControlledOption<T> {
        value.into()
    }

    /// Transforms a `ControlledOption` into an [`Option`][].  This gives you access to all of the
    /// usual assortment of useful methods that you expect from an `Option`.
    ///
    /// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
    #[inline]
    pub fn into_option(self) -> Option<T> {
        self.into()
    }
}

impl<T> Default for ControlledOption<T>
where
    T: Niche,
{
    #[inline]
    fn default() -> ControlledOption<T> {
        ControlledOption::none()
    }
}

impl<T> From<T> for ControlledOption<T>
where
    T: Niche,
{
    #[inline]
    fn from(value: T) -> ControlledOption<T> {
        ControlledOption::some(value)
    }
}

impl<T> From<Option<T>> for ControlledOption<T>
where
    T: Niche,
{
    #[inline]
    fn from(value: Option<T>) -> ControlledOption<T> {
        match value {
            Some(value) => ControlledOption::some(value),
            None => ControlledOption::none(),
        }
    }
}

impl<T> Into<Option<T>> for ControlledOption<T>
where
    T: Niche,
{
    #[inline]
    fn into(self) -> Option<T> {
        if T::is_none(&self.value) {
            None
        } else {
            Some(T::from_some(self.value))
        }
    }
}

//-------------------------------------------------------------------------------------------------
// Structs
//
// The ‘controlled-option-macros’ crate provides a derive macro for the ‘Niche’ trait.  The derived
// implementation depends on the following functions to get access to the field that you want to
// use as the struct's niche.

/// Automatically derives a [`Niche`][] implementation for a struct type.
///
/// You must mark one of the fields with a `#[niche]` attribute.  This field's type must already
/// implement [`Niche`][].  The `None` value for the struct will be uninitialized memory, except
/// for the chosen field, which will be filled in with its `None` niche value.  (This requires that
/// the [`Niche`][] implementation for the field's type must have the same layout for its `Self`
/// and `Output` types.)
pub use controlled_option_macros::Niche;

#[doc(hidden)]
pub fn fill_struct_field_with_none<T>(field: *mut T)
where
    T: Niche,
{
    debug_assert!(Layout::new::<T>() == Layout::new::<T::Output>());
    let repr = field as *mut T::Output;
    unsafe { repr.write(T::none()) };
}

#[doc(hidden)]
pub fn struct_field_is_none<T>(field: *const T) -> bool
where
    T: Niche,
{
    debug_assert!(Layout::new::<T>() == Layout::new::<T::Output>());
    let repr = field as *const T::Output;
    T::is_none(unsafe { &*repr })
}

//-------------------------------------------------------------------------------------------------
// References

impl<'a, T> Niche for &'a T {
    type Output = *const T;

    #[inline]
    fn none() -> Self::Output {
        std::ptr::null()
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        value.is_null()
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { &*value }
    }
}

impl<'a, T> Niche for &'a mut T {
    type Output = *mut T;

    #[inline]
    fn none() -> Self::Output {
        std::ptr::null_mut()
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        value.is_null()
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { &mut *value }
    }
}

//-------------------------------------------------------------------------------------------------
// Non-zero types

impl Niche for std::num::NonZeroI8 {
    type Output = i8;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroI16 {
    type Output = i16;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroI32 {
    type Output = i32;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroI64 {
    type Output = i64;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroIsize {
    type Output = isize;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroU8 {
    type Output = u8;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroU16 {
    type Output = u16;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroU32 {
    type Output = u32;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroU64 {
    type Output = u64;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}

impl Niche for std::num::NonZeroUsize {
    type Output = usize;

    #[inline]
    fn none() -> Self::Output {
        0
    }

    #[inline]
    fn is_none(value: &Self::Output) -> bool {
        *value == 0
    }

    #[inline]
    fn into_some(value: Self) -> Self::Output {
        value.get()
    }

    #[inline]
    fn from_some(value: Self::Output) -> Self {
        unsafe { Self::new_unchecked(value) }
    }
}