Skip to content

Commit 42b8ffb

Browse files
committed
switch to saturating add and add explicit panic in case of overflow
1 parent 0d6e80b commit 42b8ffb

File tree

1 file changed

+4
-36
lines changed

1 file changed

+4
-36
lines changed

src/lib.rs

+4-36
Original file line numberDiff line numberDiff line change
@@ -105,29 +105,13 @@ macro_rules! array_ref {
105105
macro_rules! array_refs {
106106
( $arr:expr, $( $pre:expr ),* ; .. ; $( $post:expr ),* ) => {{
107107
{
108-
/// A hokey struct to avoid theoretical overflow, which is only used
109-
/// at compile time, so efficiency of the overflow checks are not of
110-
/// concern.
111-
struct SaturatingUsize(usize);
112-
impl SaturatingUsize {
113-
// It is only used at compile time, so gets incorrectly
114-
// triggered as "dead code".
115-
#[allow(dead_code)]
116-
const fn add(self, rhs: usize) -> Self {
117-
if let Some(v) = self.0.checked_add(rhs) {
118-
SaturatingUsize(v)
119-
} else {
120-
SaturatingUsize(usize::MAX)
121-
}
122-
}
123-
}
124-
125108
use core::slice;
126109
#[inline]
127110
#[allow(unused_assignments)]
128111
#[allow(clippy::eval_order_dependence)]
129112
unsafe fn as_arrays<T>(a: &[T]) -> ( $( &[T; $pre], )* &[T], $( &[T; $post], )*) {
130-
const MIN_LEN: usize = SaturatingUsize(0) $( .add($pre) )* $( .add($post) )* .0;
113+
const MIN_LEN: usize = 0usize $( .saturating_add($pre) )* $( .saturating_add($post) )*;
114+
assert!(MIN_LEN < usize::MAX, "Your arrays are too big, are you trying to hack yourself?!");
131115
let var_len = a.len() - MIN_LEN;
132116
assert!(a.len() >= MIN_LEN);
133117
let mut p = a.as_ptr();
@@ -218,29 +202,13 @@ macro_rules! array_refs {
218202
macro_rules! mut_array_refs {
219203
( $arr:expr, $( $pre:expr ),* ; .. ; $( $post:expr ),* ) => {{
220204
{
221-
/// A hokey struct to avoid theoretical overflow, which is only used
222-
/// at compile time, so efficiency of the overflow checks are not of
223-
/// concern.
224-
struct SaturatingUsize(usize);
225-
impl SaturatingUsize {
226-
// It is only used at compile time, so gets incorrectly
227-
// triggered as "dead code".
228-
#[allow(dead_code)]
229-
const fn add(self, rhs: usize) -> Self {
230-
if let Some(v) = self.0.checked_add(rhs) {
231-
SaturatingUsize(v)
232-
} else {
233-
SaturatingUsize(usize::MAX)
234-
}
235-
}
236-
}
237-
238205
use core::slice;
239206
#[inline]
240207
#[allow(unused_assignments)]
241208
#[allow(clippy::eval_order_dependence)]
242209
unsafe fn as_arrays<T>(a: &mut [T]) -> ( $( &mut [T; $pre], )* &mut [T], $( &mut [T; $post], )*) {
243-
const MIN_LEN: usize = SaturatingUsize(0) $( .add($pre) )* $( .add($post) )* .0;
210+
const MIN_LEN: usize = 0usize $( .saturating_add($pre) )* $( .saturating_add($post) )*;
211+
assert!(MIN_LEN < usize::MAX, "Your arrays are too big, are you trying to hack yourself?!");
244212
let var_len = a.len() - MIN_LEN;
245213
assert!(a.len() >= MIN_LEN);
246214
let mut p = a.as_mut_ptr();

0 commit comments

Comments
 (0)