dashu_int/sqr/
mod.rs

1//! Square.
2
3use alloc::alloc::Layout;
4
5use crate::{
6    arch::word::Word,
7    helper_macros::debug_assert_zero,
8    memory::{self, Memory},
9    mul, Sign,
10};
11
12mod simple;
13
14/// If operand length <= this, simple squaring will be used.
15const MAX_LEN_SIMPLE: usize = 30;
16
17pub fn memory_requirement_exact(len: usize) -> Layout {
18    if len <= MAX_LEN_SIMPLE {
19        memory::zero_layout()
20    } else {
21        mul::memory_requirement_up_to(2 * len, len)
22    }
23}
24
25/// b = a * a, b must be filled with zeros.
26pub fn sqr(b: &mut [Word], a: &[Word], memory: &mut Memory) {
27    debug_assert!(a.len() >= 2, "use native multiplication when a is small");
28    debug_assert!(b.len() == a.len() * 2);
29    debug_assert!(b.iter().all(|&v| v == 0));
30
31    if a.len() <= MAX_LEN_SIMPLE {
32        simple::square(b, a);
33    } else {
34        debug_assert_zero!(mul::add_signed_mul_same_len(b, Sign::Positive, a, a, memory));
35    }
36}