Skip to content

Commit aadab0f

Browse files
authored
Prevent potential bitwise operations issue (#1309)
* fix: potential bitwise operations issue * fix: comment
1 parent fc402c6 commit aadab0f

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

docs/modules/ROOT/pages/api/utilities.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ Module containing math utilities.
174174
[[math-average]]
175175
==== `[.contract-item-name]#++average++#++(a: T, b: T) → T++` [.item-kind]#function#
176176

177-
Returns the average of two values. The result is rounded down.
177+
Returns the average of two unsigned integers. The result is rounded down.
178178

179179
NOTE: `T` is a generic value matching different numeric implementations.
180180

packages/utils/src/math.cairo

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,22 @@
33

44
use core::traits::{BitAnd, BitXor, Into};
55

6-
/// Returns the average of two numbers. The result is rounded down.
6+
/// Returns the average of two unsigned integers. The result is rounded down.
77
pub fn average<
8-
T,
9-
impl TDrop: Drop<T>,
10-
impl TCopy: Copy<T>,
11-
impl TAdd: Add<T>,
12-
impl TDiv: Div<T>,
13-
impl TBitAnd: BitAnd<T>,
14-
impl TBitXor: BitXor<T>,
15-
impl TInto: Into<u8, T>,
8+
T, +Unsigned<T>, +Add<T>, +Div<T>, +BitAnd<T>, +BitXor<T>, +Into<u8, T>, +Copy<T>, +Drop<T>,
169
>(
1710
a: T, b: T,
1811
) -> T {
1912
// (a + b) / 2 can overflow.
2013
(a & b) + (a ^ b) / 2_u8.into()
2114
}
15+
16+
/// A trait to represent unsigned integers.
17+
pub trait Unsigned<T>;
18+
19+
impl U8Unsigned of Unsigned<u8>;
20+
impl U16Unsigned of Unsigned<u16>;
21+
impl U32Unsigned of Unsigned<u32>;
22+
impl U64Unsigned of Unsigned<u64>;
23+
impl U128Unsigned of Unsigned<u128>;
24+
impl U256Unsigned of Unsigned<u256>;

0 commit comments

Comments
 (0)