about summary refs log tree commit diff stats
path: root/crates/core/src/utilities.rs
blob: b6bb86d34e7311ac8c10a4064abdb5b108f14e28 (plain) (blame)
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
//! Utilities used throughout the library.

use alloc::{alloc::Allocator, collections::TryReserveError, vec::Vec};

#[cfg(feature = "core-fmt")]
use core::fmt;

#[cfg(feature = "core-error")]
use core::error;

/// Extension trait for handling OOM conditions better with a [`Vec`].
pub trait VecMemoryExt<T> {
    /// Appends an element to the back of the vector.
    ///
    /// # Errors
    ///
    /// This method errors if the capacity overflows or if the allocator
    /// reports a failure.
    fn try_push(&mut self, value: T) -> Result<(), TryReserveError>;
}

impl<T, A> VecMemoryExt<T> for Vec<T, A>
where
    A: Allocator,
{
    fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
        self.try_reserve(1)?;

        //SAFETY: we just reserved space for this element
        unsafe { self.push_within_capacity(value).unwrap_unchecked() };

        Ok(())
    }
}

/// Extension trait for wrapping arithmetic.
pub const trait WrappingArithmeticExt {
    /// Wrapping integer increment.
    fn wrapping_increment(self) -> Self;

    /// Mutable wrapping integer increment.
    fn wrapping_increment_mut(&mut self);

    /// Wrapping integer decrement.
    fn wrapping_decrement(self) -> Self;

    /// Mutable wrapping integer decrement.
    fn wrapping_decrement_mut(&mut self);
}

macro_rules! wrapping_arithmetic_ext_impl {
    ($t:ty) => {
        impl const WrappingArithmeticExt for $t {
            fn wrapping_increment(self) -> Self {
                self.wrapping_add(1)
            }

            fn wrapping_increment_mut(&mut self) {
                *self = self.wrapping_add(1);
            }

            fn wrapping_decrement(self) -> Self {
                self.wrapping_sub(1)
            }

            fn wrapping_decrement_mut(&mut self) {
                *self = self.wrapping_sub(1);
            }
        }
    };
}

wrapping_arithmetic_ext_impl!(usize);
wrapping_arithmetic_ext_impl!(u64);
wrapping_arithmetic_ext_impl!(u32);
wrapping_arithmetic_ext_impl!(u16);
wrapping_arithmetic_ext_impl!(u8);

wrapping_arithmetic_ext_impl!(isize);
wrapping_arithmetic_ext_impl!(i64);
wrapping_arithmetic_ext_impl!(i32);
wrapping_arithmetic_ext_impl!(i16);
wrapping_arithmetic_ext_impl!(i8);

/// Extension trait for checked arithmetic that turns the output into a
/// [`Result`].
pub const trait CheckedArithmeticExt: Sized {
    /// Checked integer addition.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_add(self, rhs: Self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer decrement.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_decrement(self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer division.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_div(self, rhs: Self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer increment.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_increment(self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer multiplication.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_mul(self, rhs: Self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer remainder.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_rem(self, rhs: Self) -> Result<Self, IntegerOverflowError>;

    /// Checked integer subtraction.
    ///
    /// # Errors
    ///
    /// Returns an error if the result would have overflowed.
    fn errored_sub(self, rhs: Self) -> Result<Self, IntegerOverflowError>;
}

macro_rules! checked_arithmetic_ext_impl {
    ($t:ty) => {
        impl const CheckedArithmeticExt for $t {
            fn errored_add(
                self,
                rhs: Self,
            ) -> Result<Self, IntegerOverflowError> {
                self.checked_add(rhs).ok_or(IntegerOverflowError)
            }

            fn errored_decrement(self) -> Result<Self, IntegerOverflowError> {
                self.errored_sub(1)
            }

            fn errored_div(
                self,
                rhs: Self,
            ) -> Result<Self, IntegerOverflowError> {
                self.checked_div(rhs).ok_or(IntegerOverflowError)
            }

            fn errored_increment(self) -> Result<Self, IntegerOverflowError> {
                self.errored_add(1)
            }

            fn errored_mul(
                self,
                rhs: Self,
            ) -> Result<Self, IntegerOverflowError> {
                self.checked_mul(rhs).ok_or(IntegerOverflowError)
            }

            fn errored_rem(
                self,
                rhs: Self,
            ) -> Result<Self, IntegerOverflowError> {
                self.checked_rem(rhs).ok_or(IntegerOverflowError)
            }

            fn errored_sub(
                self,
                rhs: Self,
            ) -> Result<Self, IntegerOverflowError> {
                self.checked_sub(rhs).ok_or(IntegerOverflowError)
            }
        }
    };
}

checked_arithmetic_ext_impl!(usize);
checked_arithmetic_ext_impl!(u64);
checked_arithmetic_ext_impl!(u32);
checked_arithmetic_ext_impl!(u16);
checked_arithmetic_ext_impl!(u8);

checked_arithmetic_ext_impl!(isize);
checked_arithmetic_ext_impl!(i64);
checked_arithmetic_ext_impl!(i32);
checked_arithmetic_ext_impl!(i16);
checked_arithmetic_ext_impl!(i8);

/// Representation of an integer overflow error.
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "core-fmt", derive(Debug))]
pub struct IntegerOverflowError;

#[cfg(feature = "core-fmt")]
impl fmt::Display for IntegerOverflowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("integer overflow")
    }
}

#[cfg(feature = "core-error")]
impl error::Error for IntegerOverflowError {}