pikopiko-runtime 0.1.0

no_std, heap-free runtime for pikopiko: synth trait, event-binary sequencer, effects and built-in synths (AY-3-8912, buzzer, sfx).
Documentation
//! シード固定の乱数。

/// シード固定の乱数(xorshift64*)。同じシードなら、どの機種でも同じ並びになる。
/// `sfx` と `sfx-hd` のランダム生成・mutate が使う。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rng(u64);

impl Rng {
    /// シードから作る(0 でもよい)。
    pub const fn new(seed: u64) -> Self {
        // splitmix64 で 1 回かき混ぜ、0 を避ける
        let mut z = seed.wrapping_add(0x9e37_79b9_7f4a_7c15);
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^= z >> 31;
        Rng(if z == 0 { 1 } else { z })
    }

    /// 次の 64 ビット。
    pub fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.0 = x;
        x.wrapping_mul(0x2545_f491_4f6c_dd1d)
    }

    /// `lo..=hi` の整数。
    pub fn range(&mut self, lo: i32, hi: i32) -> i32 {
        if hi <= lo {
            return lo;
        }
        let span = (hi - lo) as u64 + 1;
        lo + ((self.next_u64() >> 32) % span) as i32
    }

    /// 確率 `percent`%で真。
    pub fn chance(&mut self, percent: u32) -> bool {
        ((self.next_u64() >> 32) % 100) < percent as u64
    }
}

#[cfg(test)]
mod tests {
    use super::Rng;

    #[test]
    fn sequence_is_fixed() {
        // 共通化の前の sfx・sfx-hd と同じ並び(値を変えると、ランダム生成の音が変わる)
        let mut r = Rng::new(0);
        let v: [u64; 3] = [r.next_u64(), r.next_u64(), r.next_u64()];
        let mut again = Rng::new(0);
        assert_eq!(v, [again.next_u64(), again.next_u64(), again.next_u64()]);
        assert_ne!(Rng::new(1).next_u64(), Rng::new(2).next_u64());
        let mut r = Rng::new(42);
        for _ in 0..1000 {
            let x = r.range(-3, 5);
            assert!((-3..=5).contains(&x));
        }
        assert_eq!(r.range(7, 7), 7);
        assert_eq!(r.range(7, 2), 7);
        assert!(!r.chance(0));
        assert!(r.chance(100));
    }
}