use crate::intmap::int_scale;
const SIN16_BASE: [u16; 8] = [0, 6393, 12539, 18204, 23170, 27245, 30273, 32137];
const SIN16_SLOPE: [u8; 8] = [49, 48, 44, 38, 31, 23, 14, 4];
pub const fn sin16(theta: u16) -> i16 {
let mut offset = (theta & 0x3FFF) >> 3; if theta & 0x4000 != 0 {
offset = 2047 - offset;
}
let section = (offset / 256) as usize; let b = SIN16_BASE[section];
let m = SIN16_SLOPE[section];
let secoffset8 = (offset as u8) / 2;
let mx = m as u16 * secoffset8 as u16;
let mut y = (mx as i32 + b as i32) as i16;
if theta & 0x8000 != 0 {
y = -y;
}
y
}
#[inline(always)]
pub const fn cos16(theta: u16) -> i16 {
sin16(theta.wrapping_add(16384))
}
const B_M16_INTERLEAVE: [u8; 8] = [0, 49, 49, 41, 90, 27, 117, 10];
pub const fn sin8(theta: u8) -> u8 {
let mut offset = theta;
if theta & 0x40 != 0 {
offset = 255 - offset;
}
offset &= 0x3F;
let mut secoffset = offset & 0x0F; if theta & 0x40 != 0 {
secoffset += 1;
}
let section = offset >> 4; let s2 = (section * 2) as usize;
let b = B_M16_INTERLEAVE[s2];
let m16 = B_M16_INTERLEAVE[s2 + 1];
let mx = (m16 as u16 * secoffset as u16) >> 4;
let mut y = (mx as i16 + b as i16) as i8;
if theta & 0x80 != 0 {
y = -y;
}
(y as i16 + 128) as u8
}
#[inline(always)]
pub const fn cos8(theta: u8) -> u8 {
sin8(theta.wrapping_add(64))
}
#[inline(always)]
pub fn sin8_via_sin16(theta: u8) -> u8 {
let unsigned_result = (sin16((theta as u16) << 8) as i32 + 32768) as u16;
int_scale::<u16, u8>(unsigned_result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sin16_quarter_wave_landmarks() {
assert_eq!(sin16(0), 0);
assert_eq!(sin16(8192), 23170); assert_eq!(sin16(16384), 32645); assert_eq!(sin16(32768), 0); assert_eq!(sin16(49152), -32645); assert_eq!(cos16(0), cos16(0));
}
#[test]
fn sin8_known_values() {
assert_eq!(sin8(0), 128);
assert_eq!(sin8(64), 255);
assert_eq!(sin8(192), 1);
}
#[test]
fn sin8_cos8_are_bounded_and_consistent() {
for theta in 0..=255u8 {
let s = sin8(theta);
let c = cos8(theta);
let _ = (s, c);
}
assert_eq!(cos8(0), sin8(64));
}
}