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
//! Functions for converting types that implement [`Contiguous`]
//! into and from their integer representation.
//!
//! Related: the [`IsContiguous`](struct@IsContiguous) type.
//!
//! # Example
//!
//! Converting an enum both from and into an integer.
//!
//! ```rust
//! use constmuck::{Contiguous, IsContiguous, contiguous, infer};
//!
//! #[repr(u32)]
//! #[derive(Debug, PartialEq, Copy, Clone)]
//! enum Side {
//!     Front = 0,
//!     Back = 1,
//!     Sides = 2,
//! }
//!
//! unsafe impl Contiguous for Side {
//!    type Int = u32;
//!
//!    const MIN_VALUE: u32 = 0;
//!    const MAX_VALUE: u32 = 2;
//! }
//!
//! const SIDE_INTS: [u32; 3] = [
//!     contiguous::into_integer(Side::Front, &infer!()),
//!     contiguous::into_integer(Side::Back, &infer!()),
//!     contiguous::into_integer(Side::Sides, &infer!()),
//! ];
//! assert_eq!(SIDE_INTS, [0, 1, 2]);
//!
//! const SIDE_OPTS: [Option<Side>; 4] = [
//!     contiguous::from_u32(0, infer!()),
//!     contiguous::from_u32(1, IsContiguous!()),
//!     contiguous::from_u32(2, IsContiguous!(Side)),
//!     contiguous::from_u32(3, IsContiguous!(Side, u32)),
//! ];
//!
//! assert_eq!(
//!     SIDE_OPTS,
//!     [Some(Side::Front), Some(Side::Back), Some(Side::Sides), None],
//! );
//!
//!
//! ```
//!

/// Constructs an [`IsContiguous<$T, $IntRepr>`](struct@IsContiguous),
/// requires `$T:`[`Contiguous`](trait@bytemuck::Contiguous)`<Int = $IntRepr>`.
///
/// This has two optional type arguments (`$T` and `$IntRepr`) that default to
/// infering the type if not passed.
///
/// # Example
///
/// ```rust
/// use constmuck::{IsContiguous, contiguous};
///
/// use std::num::NonZeroU8;
///
/// // The three lines below are equivalent.
/// const FOO: IsContiguous<NonZeroU8, u8> = IsContiguous!();
/// const BAR: IsContiguous<NonZeroU8, u8> = IsContiguous!(NonZeroU8);
/// const BAZ: IsContiguous<NonZeroU8, u8> = IsContiguous!(NonZeroU8, u8);
///
/// assert_eq!(contiguous::from_u8(0, FOO), None);
/// assert_eq!(contiguous::from_u8(0, BAR), None);
/// assert_eq!(contiguous::from_u8(0, BAZ), None);
/// assert_eq!(contiguous::from_u8(1, BAZ), Some(NonZeroU8::new(1).unwrap()));
///
/// assert_eq!(contiguous::into_integer(NonZeroU8::new(1).unwrap(), &FOO), 1u8);
///
///
/// ```
#[macro_export]
macro_rules! IsContiguous {
    () => {
        <$crate::IsContiguous<_, _> as $crate::Infer>::INFER
    };
    ($T:ty $(,)*) => {
        <$crate::IsContiguous<$T, _> as $crate::Infer>::INFER
    };
    ($T:ty, $IntRepr:ty $(,)*) => {
        <$crate::IsContiguous<$T, $IntRepr> as $crate::Infer>::INFER
    };
}

use bytemuck::Contiguous;

use core::{
    fmt::{self, Debug},
    marker::PhantomData,
};

#[doc(no_inline)]
pub use crate::IsContiguous;

pub(crate) mod is_contiguous {
    use super::*;

    /// Encodes a `T:`[`Contiguous`](trait@Contiguous)`<Int = IntRepr>` bound as a value.
    ///
    /// This also stores the [minimum](Self::min_value) and [maximum](Self::max_value)
    /// values of the integer represetantion.
    ///
    /// Related: the [`contiguous`](crate::contiguous) module.
    pub struct IsContiguous<T, IntRepr> {
        pub(super) min_value: IntRepr,
        pub(super) max_value: IntRepr,
        // The lifetime of `T` is invariant,
        // just in case that it's unsound for lifetimes to be co/contravariant.
        _private: PhantomData<fn(T, IntRepr) -> (T, IntRepr)>,
    }

    impl<T, IntRepr: Debug> Debug for IsContiguous<T, IntRepr> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("IsContiguous")
                .field("min_value", &self.min_value)
                .field("max_value", &self.max_value)
                .finish()
        }
    }

    impl<T, IntRepr: Copy> Copy for IsContiguous<T, IntRepr> {}

    impl<T, IntRepr: Clone> Clone for IsContiguous<T, IntRepr> {
        fn clone(&self) -> Self {
            Self {
                min_value: self.min_value.clone(),
                max_value: self.max_value.clone(),
                _private: PhantomData,
            }
        }
    }

    impl<T: Contiguous> IsContiguous<T, T::Int> {
        /// Constructs an `IsContiguous`
        ///
        /// You can also use the [`IsContiguous`](macro@IsContiguous) or [`infer`] macros
        /// to construct `IsContiguous` arguments.
        pub const NEW: Self = Self {
            min_value: T::MIN_VALUE,
            max_value: T::MAX_VALUE,
            _private: PhantomData,
        };
    }

    impl<T, IntRepr> IsContiguous<T, IntRepr> {
        const __PHANTOM__: PhantomData<fn(T, IntRepr) -> (T, IntRepr)> = PhantomData;

        /// Constructs an `IsContiguous` without checking that `T` implements
        /// [`Contiguous<Int = IntRepr>`](bytemuck::Contiguous)
        ///
        /// # Safety
        ///
        /// You must ensure that `T` follows the
        /// [safety requirements of `Contiguous`](bytemuck::Contiguous#safety),
        /// `<T as Contiguous>::Int` is `IntRepr`,
        /// `min_value` equals `<T as Contiguous>::MIN_VALUE`,
        /// and `max_value` equals `<T as Contiguous>::MAX_VALUE`.
        ///
        ///
        /// # Example
        ///
        /// ```rust
        /// use constmuck::{IsContiguous, contiguous};
        ///
        /// use std::num::Wrapping;
        ///
        /// let ic = unsafe { IsContiguous::<Wrapping<u8>, u8>::new_unchecked(10, 20) };
        ///
        /// assert_eq!(contiguous::from_u8(9, ic), None);
        /// assert_eq!(contiguous::from_u8(10, ic), Some(Wrapping(10)));
        /// assert_eq!(contiguous::from_u8(20, ic), Some(Wrapping(20)));
        /// assert_eq!(contiguous::from_u8(21, ic), None);
        ///
        /// assert_eq!(contiguous::into_integer(Wrapping(11), &ic), 11);
        /// assert_eq!(contiguous::into_integer(Wrapping(15), &ic), 15);
        ///
        ///
        /// ```
        pub const unsafe fn new_unchecked(min_value: IntRepr, max_value: IntRepr) -> Self {
            Self {
                min_value,
                max_value,
                _private: Self::__PHANTOM__,
            }
        }
    }
    impl<T, IntRepr> IsContiguous<T, IntRepr> {
        /// Gets the minimum value of `T`'s integer representation
        ///
        /// # Example
        ///
        /// ```rust
        /// use constmuck::IsContiguous;
        ///
        /// use std::num::NonZeroU8;
        ///
        /// {
        ///     let ic = IsContiguous!(NonZeroU8);
        ///     assert_eq!(ic.min_value(), &1);
        /// }
        /// {
        ///     let ic = IsContiguous!(u16);
        ///     assert_eq!(ic.min_value(), &0);
        /// }
        /// ```
        #[inline(always)]
        pub const fn min_value(&self) -> &IntRepr {
            &self.min_value
        }

        /// Gets the maximum value of `T`'s integer representation
        ///
        /// # Example
        ///
        /// ```rust
        /// use constmuck::IsContiguous;
        ///
        /// use std::num::NonZeroU16;
        ///
        /// {
        ///     let ic = IsContiguous!(NonZeroU16);
        ///     assert_eq!(ic.max_value(), &u16::MAX);
        /// }
        /// {
        ///     let ic = IsContiguous!(u8);
        ///     assert_eq!(ic.max_value(), &u8::MAX);
        /// }
        /// ```
        #[inline(always)]
        pub const fn max_value(&self) -> &IntRepr {
            &self.max_value
        }
    }
}

impl<T: Contiguous> crate::Infer for IsContiguous<T, T::Int> {
    const INFER: Self = Self::NEW;
}

/// Converts `value: T` into `IntRepr` (its integer representation).
///
/// Requires that `T` implements [`Contiguous<Int = IntRepr>`](bytemuck::Contiguous)
///
/// # By-reference `IsContiguous` argument
///
/// This takes an [`IsContiguous`](struct@IsContiguous)
/// by reference, to allow calling this function in a
/// function generic over the integer representation
/// (eg: `const fn foo<T, I>(bound: &IsContiguous<T, I>, `)
/// multiple times.
///
/// The `constmuck::contiguous::from_*`
/// functions have a concrete integer representation they deal with,
/// which means the `IsContiguous` type they take implements `Copy`,
/// and can be passed by value multiple times.
///
/// # Example
///
/// ```
/// use constmuck::{Contiguous, IsContiguous, contiguous, infer};
///
/// #[repr(i8)]
/// #[derive(Debug, PartialEq, Copy, Clone)]
/// enum Order {
///     FrontToBack = 10,
///     BackToFront = 11,
///     RightToLeft = 12,
///     LeftToRight = 13,
/// }
///
/// unsafe impl Contiguous for Order {
///    type Int = i8;
///
///    const MIN_VALUE: i8 = 10;
///    const MAX_VALUE: i8 = 13;
/// }
///
///
/// const FTB: i8 = contiguous::into_integer(Order::FrontToBack, &infer!());
/// assert_eq!(FTB, 10);
///
/// const BTF: i8 = contiguous::into_integer(Order::BackToFront, &IsContiguous!());
/// assert_eq!(BTF, 11);
///
/// const RTL: i8 = contiguous::into_integer(Order::RightToLeft, &IsContiguous!(Order));
/// assert_eq!(RTL, 12);
///
/// const LTR: i8 = contiguous::into_integer(Order::LeftToRight, &IsContiguous!(Order, i8));
/// assert_eq!(LTR, 13);
///
/// ```
///
#[inline(always)]
pub const fn into_integer<T, IntRepr>(value: T, _bounds: &IsContiguous<T, IntRepr>) -> IntRepr {
    // safety:
    // `_bounds: &IsContiguous<T, IntRepr>` guarantees that `T` is represented as
    // an `IntRepr`,
    unsafe { __priv_transmute!(T, IntRepr, value) }
}

/// Converts `integer: u8` to `T` if it's between the minimum and maximum values for `T`,
/// otherwise returns `None`.
///
/// Requires that `T` implements [`Contiguous<Int = u8>`](bytemuck::Contiguous)
///
/// # Examples
///
/// ### `NonZeroU8`
///
/// ```rust
/// use constmuck::{IsContiguous, contiguous, infer};
///
/// use std::num::NonZeroU8;
///
/// const ZERO: Option<NonZeroU8> = contiguous::from_u8(0, infer!());
/// assert_eq!(ZERO, None);
///
/// const ONE: Option<NonZeroU8> = contiguous::from_u8(1, IsContiguous!());
/// assert_eq!(ONE, NonZeroU8::new(1));
///
/// const HUNDRED: Option<NonZeroU8> = contiguous::from_u8(100, IsContiguous!(NonZeroU8));
/// assert_eq!(HUNDRED, NonZeroU8::new(100));
///
/// ```
///
/// ### Custom type
///
/// ```rust
/// use constmuck::{Contiguous, IsContiguous, contiguous, infer};
///
/// #[repr(u8)]
/// #[derive(Debug, PartialEq, Copy, Clone)]
/// enum Direction {
///     Up = 10,
///     Down = 11,
///     Left = 12,
///     Right = 13,
/// }
///
/// unsafe impl Contiguous for Direction {
///    type Int = u8;
///
///    const MIN_VALUE: u8 = 10;
///    const MAX_VALUE: u8 = 13;
/// }
///
///
/// const NONE0: Option<Direction> = contiguous::from_u8(0, infer!());
/// assert_eq!(NONE0, None);
///
/// const NONE9: Option<Direction> = contiguous::from_u8(9, infer!());
/// assert_eq!(NONE9, None);
///
/// const UP: Option<Direction> = contiguous::from_u8(10, infer!());
/// assert_eq!(UP, Some(Direction::Up));
///
/// const DOWN: Option<Direction> = contiguous::from_u8(11, IsContiguous!());
/// assert_eq!(DOWN, Some(Direction::Down));
///
/// // Passing the `Direction` type argument is required,
/// // since any type can `ìmpl PartialEq<Foo> for Direction`.
/// let left = contiguous::from_u8(12, IsContiguous!(Direction));
/// assert_eq!(left, Some(Direction::Left));
///
/// let right = contiguous::from_u8(13, IsContiguous!(Direction, u8));
/// assert_eq!(right, Some(Direction::Right));
///
/// const NONE14: Option<Direction> = contiguous::from_u8(14, IsContiguous!());
/// assert_eq!(NONE14, None);
///
/// ```
pub const fn from_u8<T>(integer: u8, bounds: IsContiguous<T, u8>) -> Option<T> {
    #[cfg(debug_assertions)]
    #[allow(unconditional_panic)]
    if bounds.min_value > bounds.max_value {
        crate::panic_! {
            {
                let x = 0;
                let _: () = [/* bounds.min_value is larger than bounds.max_value */][x];
            }
            {
                crate::const_panic::concat_panic!{
                    "\nbounds.min_value: ",
                    bounds.min_value,
                    " is larger than bounds.max_value: ",
                    bounds.max_value,
                }
            }
        }
    }

    if bounds.min_value <= integer && integer <= bounds.max_value {
        // safety:
        // `bounds: IsContiguous<T, u8>` guarantees that `T` is represented as a `u8`,
        // and is valid for all values between `bounds.min_value` and
        // `bounds.max_value` inclusive.
        unsafe { Some(__priv_transmute_from_copy!(u8, T, integer)) }
    } else {
        None
    }
}

macro_rules! declare_from_integer_fns {
    ($(($fn_name:ident, $Int:ident))*) => (
        declare_from_integer_fns!{
            @inner
            $((
                $fn_name,
                $Int,
                concat!(
                    "Converts `ìnteger: ", stringify!($Int), "` to `T` if it's between ",
                    "the minimum and maximum values for `T`, otherwise returns `None`.\n\n",
                    "Requires that `T` implements [`Contiguous<Int = ", stringify!($Int),
                    ">`](bytemuck::Contiguous)"
                )
            ))*
        }
    );
    (@inner $(($fn_name:ident, $Int:ident, $shared_doc:expr))*)=>{
        $(
            impl<T> FromInteger<T, $Int> {
                #[doc = $shared_doc]
                #[inline(always)]
                pub const fn call(self) -> Option<T> {
                    $fn_name(self.0, self.1)
                }
            }
        )*

        $(
            declare_from_integer_fns!{@free_fn $fn_name, $Int, $shared_doc}
        )*
    };
    (@free_fn from_u8, $Int:ident, $shared_doc:expr)=>{};
    (@free_fn $fn_name:ident, $Int:ident, $shared_doc:expr)=>{
        #[doc = $shared_doc]
        /// # Examples
        ///
        /// For examples, you can look
        /// [at the ones for `from_u8`](self::from_u8#examples).
        ///
        pub const fn $fn_name<T>(integer: $Int, bounds: IsContiguous<T, $Int>) -> Option<T> {
            #[cfg(debug_assertions)]
            #[allow(unconditional_panic)]
            if bounds.min_value > bounds.max_value {
                crate::panic_!{
                    {
                        let x = 0;
                        let _: () = [/* bounds.min_value is larger than bounds.max_value */][x];
                    }
                    {
                        crate::const_panic::concat_panic!{
                            "\nbounds.min_value: ",
                            bounds.min_value,
                            " is larger than bounds.max_value: ",
                            bounds.max_value,
                        }
                    }
                }
            }

            if bounds.min_value <= integer && integer <= bounds.max_value {
                // safety:
                // `bounds: IsContiguous<T, $Int>` guarantees that
                // `T` is represented as a `$Int`, and is valid for all values between
                // `bounds.min_value` and `bounds.max_value` inclusive.
                unsafe { Some(__priv_transmute_from_copy!($Int, T, integer)) }
            } else {
                None
            }
        }
    };
}

declare_from_integer_fns! {
    (from_i8, i8)
    (from_i16, i16)
    (from_i32, i32)
    (from_i64, i64)
    (from_i128, i128)
    (from_isize, isize)
    (from_u8, u8)
    (from_u16, u16)
    (from_u32, u32)
    (from_u64, u64)
    (from_u128, u128)
    (from_usize, usize)
}

/// Converts `IntRepr` to `T` if it's between the minimum and maximum values for `T`,
/// otherwise returns `None`.
///
/// This is only useful over the functions in the [`contiguous`](crate::contiguous)
/// module when one needs to select the method based on the type of the integer.
///
/// # Limitation
///
/// The concrete type of the integer must be known for the `call` method to be callable,
/// it can't be inferred from the type that it's converted into.
///
/// # Example
///
/// ```rust
/// use constmuck::contiguous::FromInteger;
/// use constmuck::{IsContiguous, infer};
///
/// use std::num::{NonZeroU32, NonZeroUsize};
///
/// const ZERO_USIZE: Option<NonZeroUsize> =
///     FromInteger(0usize, infer!()).call();
/// assert_eq!(ZERO_USIZE, None);
///
/// const TWO_USIZE: Option<NonZeroUsize> =
///     FromInteger(2usize, IsContiguous!()).call();
/// assert_eq!(TWO_USIZE, NonZeroUsize::new(2));
///
///
/// const ZERO_U64: Option<NonZeroU32> =
///     FromInteger(0u32, IsContiguous!(NonZeroU32)).call();
/// assert_eq!(ZERO_U64, None);
///
/// const ONE_U64: Option<NonZeroU32> =
///     FromInteger(1u32, IsContiguous!(NonZeroU32, u32)).call();
/// assert_eq!(ONE_U64, NonZeroU32::new(1));
///
///
/// ```
///
#[allow(missing_debug_implementations)]
pub struct FromInteger<T, IntRepr>(pub IntRepr, pub IsContiguous<T, IntRepr>);