lib8: trig: rewrite sin8/cos8 to use traits, for easy modular math with usize

This commit is contained in:
Victoria Fischer 2024-11-24 18:56:47 +01:00
parent 64c28b89fe
commit 35ccf20142

View File

@ -2,15 +2,21 @@ use num::PrimInt;
const b_m16_interleave: [u8; 8] = [0, 49, 49, 41, 90, 27, 117, 10];
pub fn sin8(theta: u8) -> u8 {
let mut offset: u8 = theta;
if theta & 0x40 != 0 {
pub trait Trig8 {
fn sin8(self) -> u8;
fn cos8(self) -> u8;
}
impl Trig8 for u8 {
fn sin8(self) -> u8 {
let mut offset: u8 = self;
if self & 0x40 != 0 {
offset = 255 - offset;
}
offset &= 0x3f;
let mut secoffset: u8 = offset & 0x0f;
if theta & 0x40 != 0 {
if self & 0x40 != 0 {
secoffset += 1;
}
@ -20,13 +26,32 @@ pub fn sin8(theta: u8) -> u8 {
let m16: u8 = b_m16_interleave[s2 as usize + 1];
let mx: u8 = m16.wrapping_mul(secoffset).unsigned_shr(4);
let mut y: i8 = mx as i8 + b as i8;
if theta & 0x80 != 0 {
if self & 0x80 != 0 {
y = -y;
}
y = y.wrapping_add(128u8 as i8);
return y as u8;
}
pub fn cos8(theta: u8) -> u8 {
sin8(theta.wrapping_add(64))
fn cos8(self) -> u8 {
sin8(self.wrapping_add(64))
}
}
impl Trig8 for usize {
fn sin8(self) -> u8 {
((self % 255) as u8).sin8()
}
fn cos8(self) -> u8 {
((self % 255) as u8).cos8()
}
}
pub fn sin8<T: Trig8>(theta: T) -> u8 {
theta.sin8()
}
pub fn cos8<T: Trig8>(theta: T) -> u8 {
theta.cos8()
}