From 578fe7c8ae430c93ad1c2f32b9eac31b3c548b17 Mon Sep 17 00:00:00 2001 From: Tristan <122918260+TAdev0@users.noreply.github.com> Date: Mon, 2 Dec 2024 17:36:13 +0100 Subject: [PATCH] Core Lib Documentation: `Widesquare` module (#6806) Co-authored-by: enitrat --- corelib/src/num/traits/ops/widesquare.cairo | 51 +++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/corelib/src/num/traits/ops/widesquare.cairo b/corelib/src/num/traits/ops/widesquare.cairo index eacde986378..a3ec687521b 100644 --- a/corelib/src/num/traits/ops/widesquare.cairo +++ b/corelib/src/num/traits/ops/widesquare.cairo @@ -1,6 +1,57 @@ +//! Wide square operation. +//! +//! This module provides the [`WideSquare`] trait which enables squaring operations +//! that return a result type with double the bit width of the input type. +//! This is particularly useful when you need to square a number without +//! worrying about overflow, as the result type can hold the full range of possible values. +//! +//! # Examples +//! +//! ``` +//! use core::num::traits::WideSquare; +//! +//! // Squaring a `u8` value to get a `u16` result +//! let a: u8 = 200; +//! let result: u16 = a.wide_square(); +//! assert!(result == 40000); +//! +//! // Squaring a `u128` value to get a `u256` result +//! let x: u128 = 0xffffffffffffffffffffffffffffffff; // max u128 +//! let wide_result: u256 = x.wide_square(); // No overflow occurs +//! assert!(wide_result == 0xfffffffffffffffffffffffffffffffe00000000000000000000000000000001); +//! ``` +//! +//! # Available Implementations +//! +//! The trait is implemented for the following type pairs: +//! - `i8` → `i16` +//! - `i16` → `i32` +//! - `i32` → `i64` +//! - `i64` → `i128` +//! - `u8` → `u16` +//! - `u16` → `u32` +//! - `u32` → `u64` +//! - `u64` → `u128` +//! - `u128` → `u256` +//! - `u256` → `u512` + use crate::num::traits::WideMul; /// A trait for a type that can be squared to produce a wider type. +/// +/// This trait enables squaring operations where the result type has double +/// the bit width of the input type, preventing overflow in cases where the +/// result would exceed the input type's maximum value. +/// +/// # Examples +/// +/// ``` +/// use core::num::traits::WideSquare; +/// +/// let a: u8 = 16; +/// let result: u16 = a.wide_square(); +/// assert!(result == 256); +/// ``` pub trait WideSquare { /// The type of the result of the square. type Target;