Skip to content

Commit

Permalink
Prevent potential bitwise operations issue (#1309)
Browse files Browse the repository at this point in the history
* fix: potential bitwise operations issue

* fix: comment
  • Loading branch information
ericnordelo authored Jan 22, 2025
1 parent fc402c6 commit aadab0f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
2 changes: 1 addition & 1 deletion docs/modules/ROOT/pages/api/utilities.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ Module containing math utilities.
[[math-average]]
==== `[.contract-item-name]#++average++#++(a: T, b: T) → T++` [.item-kind]#function#

Returns the average of two values. The result is rounded down.
Returns the average of two unsigned integers. The result is rounded down.

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

Expand Down
21 changes: 12 additions & 9 deletions packages/utils/src/math.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@

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

/// Returns the average of two numbers. The result is rounded down.
/// Returns the average of two unsigned integers. The result is rounded down.
pub fn average<
T,
impl TDrop: Drop<T>,
impl TCopy: Copy<T>,
impl TAdd: Add<T>,
impl TDiv: Div<T>,
impl TBitAnd: BitAnd<T>,
impl TBitXor: BitXor<T>,
impl TInto: Into<u8, T>,
T, +Unsigned<T>, +Add<T>, +Div<T>, +BitAnd<T>, +BitXor<T>, +Into<u8, T>, +Copy<T>, +Drop<T>,
>(
a: T, b: T,
) -> T {
// (a + b) / 2 can overflow.
(a & b) + (a ^ b) / 2_u8.into()
}

/// A trait to represent unsigned integers.
pub trait Unsigned<T>;

impl U8Unsigned of Unsigned<u8>;
impl U16Unsigned of Unsigned<u16>;
impl U32Unsigned of Unsigned<u32>;
impl U64Unsigned of Unsigned<u64>;
impl U128Unsigned of Unsigned<u128>;
impl U256Unsigned of Unsigned<u256>;

0 comments on commit aadab0f

Please sign in to comment.