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
//! テスト用:確保を数えるグローバルアロケータ(`testing` 機能)。
//!
//! 拡張音源の `tests/realtime.rs` で、`render()` の中でメモリを確保しないことを確かめるのに使う。
//! テストのファイルで次のように登録する。
//!
//! ```ignore
//! use pikopiko_runtime::kit::testing::{allocations, Counting};
//! #[global_allocator]
//! static A: Counting = Counting;
//!
//! let n = allocations(|| { /* ここでの確保を数える */ });
//! assert_eq!(n, 0);
//! ```

#![allow(unsafe_code)] // テスト用アロケータのためだけに使う

use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;

/// 確保を数えるアロケータ(中身は `System` に任せる)。数えるのは [`allocations`] の中だけ。
pub struct Counting;

thread_local! {
    static WATCH: Cell<bool> = const { Cell::new(false) };
    static COUNT: Cell<usize> = const { Cell::new(0) };
}

fn note() {
    let _ = WATCH.try_with(|w| {
        if w.get() {
            let _ = COUNT.try_with(|c| c.set(c.get() + 1));
        }
    });
}

// SAFETY: 中身はそのまま `System` に任せ、数を数えるだけ
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, l: Layout) -> *mut u8 {
        note();
        System.alloc(l)
    }
    unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
        System.dealloc(p, l)
    }
    unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
        note();
        System.realloc(p, l, n)
    }
}

/// `f` の中で、このスレッドが確保した回数(`Counting` をグローバルアロケータにしたときだけ数える)。
pub fn allocations(f: impl FnOnce()) -> usize {
    COUNT.with(|c| c.set(0));
    WATCH.with(|w| w.set(true));
    f();
    WATCH.with(|w| w.set(false));
    COUNT.with(|c| c.get())
}