Skip to main content

runmat_runtime/
output_count.rs

1use runmat_builtins::Value;
2use runmat_thread_local::runmat_thread_local;
3use std::cell::RefCell;
4
5runmat_thread_local! {
6    static OUTPUT_COUNT_STACK: RefCell<Vec<Option<usize>>> = const { RefCell::new(Vec::new()) };
7}
8
9pub struct OutputCountGuard {
10    did_push: bool,
11}
12
13impl Drop for OutputCountGuard {
14    fn drop(&mut self) {
15        if !self.did_push {
16            return;
17        }
18        OUTPUT_COUNT_STACK.with(|stack| {
19            let mut stack = stack.borrow_mut();
20            let _ = stack.pop();
21        });
22    }
23}
24
25pub fn push_output_count(count: Option<usize>) -> OutputCountGuard {
26    OUTPUT_COUNT_STACK.with(|stack| {
27        stack.borrow_mut().push(count);
28    });
29    OutputCountGuard { did_push: true }
30}
31
32pub fn current_output_count() -> Option<usize> {
33    OUTPUT_COUNT_STACK.with(|stack| stack.borrow().last().cloned().flatten())
34}
35
36pub fn output_list_with_padding(out_count: usize, mut outputs: Vec<Value>) -> Value {
37    if outputs.len() < out_count {
38        outputs.resize(out_count, Value::Num(0.0));
39    }
40    Value::OutputList(outputs)
41}