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
use derive_more::Display;

/// An error which can occur when converting from a type with a greater value range to one with a
/// smaller one.
#[derive(Debug, Clone, Eq, PartialEq, Display)]
#[display(fmt = "converting to type with smaller value range failed")]
pub struct TryFromGreaterError(pub(crate) ());

impl std::error::Error for TryFromGreaterError {}

/// Creates a new type which is represented by a primitive type but has a restricted value range.
macro_rules! newtype {
    (
        $(#[$outer:meta])*
        name = $name: ident,
        repr = $repr: ty,
        max = $max: literal
    ) => {
        $(#[$outer])*
        #[derive(
            Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, derive_more::Display,
        )]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        pub struct $name(pub(crate) $repr);

        impl $name {
            /// The smallest value that can be represented by this type.
            pub const MIN: $name = $name(0);

            /// The largest value that can be represented by this type.
            pub const MAX: $name = $name($max);

            fn is_valid<T: PartialOrd + From<$repr>>(number: T) -> bool {
                number <= $max.into()
            }

            doc_comment::doc_comment! {
                concat!(
"Creates a ", stringify!($name), ".

# Panics

This function panics if `value` is greater than ", $max, "."
                ),
                pub fn new(value: $repr) -> $name {
                    assert!($name::is_valid(value));
                    $name(value)
                }
            }

            doc_comment::doc_comment! {
                concat!(
"Creates a ", stringify!($name), " without checking `value`.

# Safety

`value` must not be greater than ", $max, "."
                ),
                pub const unsafe fn new_unchecked(value: $repr) -> $name {
                    $name(value)
                }
            }

            /// Returns the value as a primitive type.
            pub const fn get(self) -> $repr {
                self.0
            }
        }
    };
}

/// Creates a `From` trait implementation from another newtype which has the same or smaller value
/// range.
macro_rules! impl_from_newtype_to_newtype {
    ($from: ty, $into: ty) => {
        impl From<$from> for $into {
            fn from(value: $from) -> Self {
                Self(value.0 as _)
            }
        }
    };
}

/// Creates a `From` trait implementation from a newtype to a primitive type with a higher
/// value range.
macro_rules! impl_from_newtype_to_primitive {
    ($from: ty, $into: ty) => {
        impl From<$from> for $into {
            fn from(value: $from) -> Self {
                value.0 as _
            }
        }
    };
}

/// Creates a `From` trait implementation from a primitive with a lower value range to a newtype.
macro_rules! impl_from_primitive_to_newtype {
    ($from: ty, $into: ty) => {
        impl From<$from> for $into {
            fn from(value: $from) -> Self {
                Self(value as _)
            }
        }
    };
}

/// Creates a `TryFrom` trait implementation from a newtype with a higher value range to a newtype.
macro_rules! impl_try_from_newtype_to_newtype {
    ($from: ty, $into: ty) => {
        impl std::convert::TryFrom<$from> for $into {
            type Error = $crate::TryFromGreaterError;

            fn try_from(value: $from) -> Result<Self, Self::Error> {
                if !Self::is_valid(value.0) {
                    return Err($crate::TryFromGreaterError(()));
                }
                Ok(Self(value.0 as _))
            }
        }
    };
}

/// Creates a `TryFrom` trait implementation from a primitive type with a higher value range to a
/// newtype.
macro_rules! impl_try_from_primitive_to_newtype {
    ($from: ty, $into: ty) => {
        impl std::convert::TryFrom<$from> for $into {
            type Error = $crate::TryFromGreaterError;

            fn try_from(value: $from) -> Result<Self, Self::Error> {
                if !Self::is_valid(value) {
                    return Err($crate::TryFromGreaterError(()));
                }
                Ok(Self(value as _))
            }
        }
    };
}