Skip to main content

ruda_kernel/dsl/frontend/container/cell/
runtime.rs

1use crate::dsl::prelude::RudaPrimitive;
2use crate::dsl::frontend::assign::expand_no_check;
3use crate::dsl::prelude::*;
4use ruda_core::ir::Operation;
5use ruda_kernel_macros::intrinsic;
6
7#[derive(Clone, Copy)]
8pub struct RuntimeCell<T: RudaType> {
9    #[allow(unused)]
10    value: T,
11}
12
13pub struct RuntimeCellExpand<T: RudaType> {
14    value: <T as crate::dsl::prelude::RudaType>::ExpandType,
15}
16impl<T: RudaType> Clone for RuntimeCellExpand<T> {
17    fn clone(&self) -> Self {
18        Self {
19            value: self.value.clone(),
20        }
21    }
22}
23impl<T: RudaType> crate::dsl::prelude::RudaType for RuntimeCell<T> {
24    type ExpandType = RuntimeCellExpand<T>;
25}
26impl<T: RudaType> crate::dsl::prelude::IntoMut for RuntimeCellExpand<T> {
27    fn into_mut(self, _scope: &mut crate::dsl::prelude::Scope) -> Self {
28        Self {
29            // We keep the same as a cell would do.
30            value: self.value.clone(),
31        }
32    }
33}
34impl<T: RudaType> crate::dsl::prelude::RudaDebug for RuntimeCellExpand<T> {}
35
36#[ruda]
37impl<T: RudaPrimitive> RuntimeCell<T> {
38    /// Create a new runtime cell with the given initial value.
39    #[allow(unused_variables)]
40    pub fn new(init: T) -> Self {
41        intrinsic!(|scope| {
42            let value = init_expand(scope, init.expand, true, Operation::Copy);
43            RuntimeCellExpand {
44                value: value.into(),
45            }
46        })
47    }
48
49    /// Store a new value in the cell.
50    #[allow(unused_variables)]
51    pub fn store(&self, value: T) {
52        intrinsic!(|scope| {
53            expand_no_check(scope, value, self.value);
54        })
55    }
56
57    /// Get the value from the call
58    pub fn read(&self) -> T {
59        intrinsic!(|scope| {
60            let value = init_expand(scope, self.value.expand, false, Operation::Copy);
61            value.into()
62        })
63    }
64
65    /// Consume the cell.
66    pub fn consume(self) -> T {
67        intrinsic!(|scope| { self.value })
68    }
69}
70
71#[ruda]
72impl<T: RudaIndexMut> RuntimeCell<T> {
73    /// Store a new value in the cell at the given index.
74    #[allow(unused_variables)]
75    pub fn store_at(&mut self, index: <T as RudaIndex>::Idx, value: <T as RudaIndex>::Output) {
76        intrinsic!(|scope| { self.value.expand_index_mut(scope, index, value) })
77    }
78}
79
80#[ruda]
81impl<T: RudaIndex> RuntimeCell<T> {
82    /// Read a value in the cell at the given index.
83    #[allow(unused_variables)]
84    pub fn read_at(&self, index: T::Idx) -> T::Output {
85        intrinsic!(|scope| { self.value.expand_index(scope, index) })
86    }
87}