From 244c34c91e39a1770b181e3a239a0049ca830673 Mon Sep 17 00:00:00 2001 From: Tristan <122918260+TAdev0@users.noreply.github.com> Date: Mon, 2 Dec 2024 17:31:16 +0100 Subject: [PATCH] Core Lib Documentation: `Wrapping` module (#6805) Co-authored-by: enitrat --- corelib/src/num/traits/ops/wrapping.cairo | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/corelib/src/num/traits/ops/wrapping.cairo b/corelib/src/num/traits/ops/wrapping.cairo index adfb8ed94bb..2fd274c65af 100644 --- a/corelib/src/num/traits/ops/wrapping.cairo +++ b/corelib/src/num/traits/ops/wrapping.cairo @@ -1,4 +1,43 @@ +//! Arithmetic operations with overflow and underflow wrapping. +//! +//! This module provides traits for performing arithmetic operations that wrap around at the +//! boundary of the type in case of overflow or underflow. This is particularly useful when you want +//! to: +//! - Perform arithmetic operations without panicking on overflow/underflow +//! - Implement modular arithmetic +//! - Handle cases where overflow is expected and desired +//! +//! # Examples +//! +//! ``` +//! use core::num::traits::{WrappingAdd, WrappingSub, WrappingMul}; +//! +//! // Addition wrapping +//! let a: u8 = 255; +//! assert!(a.wrapping_add(1) == 0); +//! +//! // Subtraction wrapping +//! let b: u8 = 0; +//! assert!(b.wrapping_sub(1) == 255); +//! +//! // Multiplication wrapping +//! let c: u8 = 200; +//! assert!(c.wrapping_mul(2) == 144); // (200 * 2) % 256 = 144 +//! ``` + /// Performs addition that wraps around on overflow. +/// +/// # Examples +/// +/// ``` +/// use core::num::traits::WrappingAdd; +/// +/// let result = 255_u8.wrapping_add(1); +/// assert!(result == 0); +/// +/// let result = 100_u8.wrapping_add(200); +/// assert!(result == 44); // (100 + 200) % 256 = 44 +/// ``` pub trait WrappingAdd { /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of the /// type. @@ -6,6 +45,18 @@ pub trait WrappingAdd { } /// Performs subtraction that wraps around on overflow. +/// +/// # Examples +/// +/// ``` +/// use core::num::traits::WrappingSub; +/// +/// let result = 0_u8.wrapping_sub(1); +/// assert!(result == 255); +/// +/// let result = 100_u8.wrapping_sub(150); +/// assert!(result == 206); +/// ``` pub trait WrappingSub { /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary of /// the type. @@ -13,6 +64,18 @@ pub trait WrappingSub { } /// Performs multiplication that wraps around on overflow. +/// +/// # Examples +/// +/// ``` +/// use core::num::traits::WrappingMul; +/// +/// let result = 10_u8.wrapping_mul(30); +/// assert!(result == 44); // (10 * 30) % 256 = 44 +/// +/// let result = 200_u8.wrapping_mul(2); +/// assert!(result == 144); // (200 * 2) % 256 = 144 +/// ``` pub trait WrappingMul { /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary /// of the type.