Skip to main content

harn_vm/value/
handles.rs

1use std::rc::Rc;
2use std::sync::atomic::{AtomicBool, AtomicI64};
3use std::sync::Arc;
4
5use super::{VmError, VmValue};
6
7/// The raw join handle type for spawned tasks.
8pub type VmJoinHandle = tokio::task::JoinHandle<Result<(VmValue, String), VmError>>;
9
10/// A spawned async task handle with cancellation support.
11pub struct VmTaskHandle {
12    pub handle: VmJoinHandle,
13    /// Cooperative cancellation token. Set to true to request graceful shutdown.
14    pub cancel_token: Arc<AtomicBool>,
15}
16
17/// A channel handle for the VM (uses tokio mpsc).
18#[derive(Debug, Clone)]
19pub struct VmChannelHandle {
20    pub name: Rc<str>,
21    pub sender: Arc<tokio::sync::mpsc::Sender<VmValue>>,
22    pub receiver: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
23    pub closed: Arc<AtomicBool>,
24}
25
26/// An atomic integer handle for the VM.
27#[derive(Debug, Clone)]
28pub struct VmAtomicHandle {
29    pub value: Arc<AtomicI64>,
30}
31
32/// A lazy integer range — Python-style. Stores only `(start, end, inclusive)`
33/// so the in-memory footprint is O(1) regardless of the range's length.
34/// `len()`, indexing (`r[k]`), `.contains(x)`, `.first()`, `.last()` are all
35/// O(1); direct iteration walks step-by-step without materializing a list.
36///
37/// Empty-range convention (Python-consistent):
38/// - Inclusive empty when `start > end`.
39/// - Exclusive empty when `start >= end`.
40///
41/// Negative / reversed ranges are NOT supported in v1: `5 to 1` is simply
42/// empty. Authors who want reverse iteration should call `.to_list().reverse()`.
43#[derive(Debug, Clone, Copy)]
44pub struct VmRange {
45    pub start: i64,
46    pub end: i64,
47    pub inclusive: bool,
48}
49
50impl VmRange {
51    /// Number of elements this range yields.
52    ///
53    /// Uses saturating arithmetic so that pathological ranges near
54    /// `i64::MAX`/`i64::MIN` do not panic on overflow. Because a range's
55    /// element count must fit in `i64` the returned length saturates at
56    /// `i64::MAX` for ranges whose width exceeds that (e.g. `i64::MIN to
57    /// i64::MAX` inclusive). Callers that later narrow to `usize` for
58    /// allocation should still guard against huge lengths — see
59    /// `to_vec` / `get` for the indexable-range invariants.
60    pub fn len(&self) -> i64 {
61        if self.inclusive {
62            if self.start > self.end {
63                0
64            } else {
65                self.end.saturating_sub(self.start).saturating_add(1)
66            }
67        } else if self.start >= self.end {
68            0
69        } else {
70            self.end.saturating_sub(self.start)
71        }
72    }
73
74    pub fn is_empty(&self) -> bool {
75        self.len() == 0
76    }
77
78    /// Element at the given 0-based index, bounds-checked.
79    /// Returns `None` when out of bounds or when `start + idx` would
80    /// overflow (which can only happen when `len()` saturated).
81    pub fn get(&self, idx: i64) -> Option<i64> {
82        if idx < 0 || idx >= self.len() {
83            None
84        } else {
85            self.start.checked_add(idx)
86        }
87    }
88
89    /// First element or `None` when empty.
90    pub fn first(&self) -> Option<i64> {
91        if self.is_empty() {
92            None
93        } else {
94            Some(self.start)
95        }
96    }
97
98    /// Last element or `None` when empty.
99    pub fn last(&self) -> Option<i64> {
100        if self.is_empty() {
101            None
102        } else if self.inclusive {
103            Some(self.end)
104        } else {
105            Some(self.end - 1)
106        }
107    }
108
109    /// Whether `v` falls inside the range (O(1)).
110    pub fn contains(&self, v: i64) -> bool {
111        if self.is_empty() {
112            return false;
113        }
114        if self.inclusive {
115            v >= self.start && v <= self.end
116        } else {
117            v >= self.start && v < self.end
118        }
119    }
120
121    /// Materialize to a `Vec<VmValue>` — the explicit escape hatch.
122    ///
123    /// Uses `checked_add` on the per-element index so a range near
124    /// `i64::MAX` stops at the representable bound instead of panicking.
125    /// Callers should still treat a very long range as unwise to
126    /// materialize (the whole point of `VmRange` is to avoid this).
127    pub fn to_vec(&self) -> Vec<VmValue> {
128        let len = self.len();
129        if len <= 0 {
130            return Vec::new();
131        }
132        let cap = len as usize;
133        let mut out = Vec::with_capacity(cap);
134        for i in 0..len {
135            match self.start.checked_add(i) {
136                Some(v) => out.push(VmValue::Int(v)),
137                None => break,
138            }
139        }
140        out
141    }
142}
143
144/// A generator object: lazily produces values via yield.
145/// The generator body runs as a spawned task that sends values through a channel.
146#[derive(Debug, Clone)]
147pub struct VmGenerator {
148    /// Whether the generator has finished (returned or exhausted).
149    pub done: Rc<std::cell::Cell<bool>>,
150    /// Receiver end of the yield channel (generator sends values here).
151    /// Wrapped in a shared async mutex so recv() can be called without holding
152    /// a RefCell borrow across await points.
153    pub receiver: Rc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
154}