Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix sqrt overflow panic on high bit values #6

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions cordic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ extern crate std;
mod cordic_number;

pub use cordic_number::CordicNumber;
use fixed::types::U0F64;
use core::convert::TryInto;
use fixed::{traits::Fixed, types::U0F64};

const ATAN_TABLE: &[u8] = include_bytes!("tables/cordic_atan.table");
const EXP_MINUS_ONE_TABLE: &[u8] = include_bytes!("tables/cordic_exp_minus_one.table");
Expand Down Expand Up @@ -201,33 +201,42 @@ pub fn exp<T: CordicNumber>(x: T) -> T {
}

/// Compute the square root of the given fixed-point number.
pub fn sqrt<T: CordicNumber>(x: T) -> T {
if x == T::zero() || x == T::one() {
pub fn sqrt<T: CordicNumber + Fixed>(x: T) -> T {
if x == <T as CordicNumber>::zero() || x == T::one() {
return x;
}

let mut pow2 = T::one();
let mut result;

// Note: Checked multiplication is required on 'big' numbers because they can overflow on `pow2*pow2`.
if x < T::one() {
while x <= pow2 * pow2 {
pow2 = pow2 >> 1;
pow2 = pow2 >> 1u32;
}

result = pow2;
} else {
// x >= T::one()
while pow2 * pow2 <= x {
pow2 = pow2 << 1;
while if let Some(p) = pow2.checked_mul(pow2) {
p <= x
} else {
false
} {
pow2 = pow2 << 1u32;
}

result = pow2 >> 1;
result = pow2 >> 1u32;
}

for _ in 0..T::num_bits() {
pow2 = pow2 >> 1;
pow2 = pow2 >> 1u32;
let next_result = result + pow2;
if next_result * next_result <= x {
if if let Some(nr) = next_result.checked_mul(next_result) {
nr <= x
} else {
false
} {
result = next_result;
}
}
Expand Down