Skip to main content

byteflow/bytecode/
value.rs

1use std::fmt;
2use std::sync::Arc;
3
4use super::cap::CapId;
5
6/// Reserved Atomic Hop tag for monitor `DOWN` events (not an application tag).
7pub const TAG_SYS_DOWN: u16 = 0xFF01;
8/// Reserved Atomic Hop tag for linked-exit notices (`Ask` target death or
9/// `trap_exit` link signal).
10pub const TAG_SYS_EXIT: u16 = 0xFF02;
11
12/// Envelope carried in mailboxes and registers (**Atomic Hop**).
13///
14/// `payload` is a [`Value`] behind [`Arc`] so hops can carry `Int`, `Str`,
15/// `Bytes`, or nested messages. Mailbox byte budgets charge
16/// [`Value::memory_size`] of the whole hop, including the payload tree.
17///
18/// # Security
19///
20/// - **`sender`**: FlowId stamped by the scheduler on bytecode `Send` / `Ask`
21///   and host [`crate::Runtime::send`] (`0` = [`crate::FlowId::HOST`])
22///   (invariant **S1**). Not a capability.
23/// - **`reply_cap`**: stable SEND-only [`CapId`] per `(recipient, sender)`
24///   pair (holder = recipient, reused across hops). Correlation is
25///   [`Self::request_id`]. [`CapId::NONE`] means “no reply grant”.
26///
27/// See `docs/security.md`.
28#[derive(Clone, Debug, PartialEq)]
29pub struct Message {
30    /// Authenticated origin FlowId (`0` = trusted host / non-flow).
31    pub sender: u64,
32    /// Capability granting **SEND** back to [`Self::sender`], or [`CapId::NONE`].
33    pub reply_cap: CapId,
34    /// Client correlation token; echoed on replies (`Ask` / **S2**).
35    pub request_id: u64,
36    /// Protocol discriminator (opaque to the VM).
37    pub tag: u16,
38    /// Application body (shared so hop clones are cheap).
39    pub payload: Arc<Value>,
40}
41
42impl Message {
43    /// Build an envelope. `sender` / `reply_cap` are placeholders until a
44    /// bytecode hop is authenticated by the scheduler.
45    pub fn new(sender: u64, request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
46        Self {
47            sender,
48            reply_cap: CapId::NONE,
49            request_id,
50            tag,
51            payload: Arc::new(payload.into()),
52        }
53    }
54
55    /// Outgoing hop from host Rust (`sender` / `reply_cap` filled on delivery).
56    pub fn request(request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
57        Self::new(0, request_id, tag, payload)
58    }
59
60    /// Reply envelope echoing `request_id` from a received hop (host path).
61    pub fn reply_to(req: &Self, tag: u16, payload: impl Into<Value>) -> Self {
62        Self::new(0, req.request_id, tag, payload)
63    }
64
65    /// Runtime lifecycle hop: monitor `DOWN` (`tag == `[`TAG_SYS_DOWN`]).
66    pub fn down(monitor: u64, target_flow: u64, reason: u64) -> Self {
67        Self::new(
68            target_flow,
69            monitor,
70            TAG_SYS_DOWN,
71            Value::Int(reason as i64),
72        )
73    }
74
75    /// Runtime lifecycle hop: Ask target exited, or a linked peer exited
76    /// while this flow has `trap_exit` enabled (`tag == `[`TAG_SYS_EXIT`]).
77    pub fn linked_exit(target_flow: u64, reason: u64) -> Self {
78        Self::new(target_flow, 0, TAG_SYS_EXIT, Value::Int(reason as i64))
79    }
80
81    #[inline]
82    pub fn is_down(&self) -> bool {
83        self.tag == TAG_SYS_DOWN
84    }
85
86    #[inline]
87    pub fn is_exit(&self) -> bool {
88        self.tag == TAG_SYS_EXIT
89    }
90
91    /// Stamp origin FlowId and attach a reply capability (scheduler only).
92    #[inline]
93    pub(crate) fn authenticate(mut self, sender: u64, reply_cap: CapId) -> Self {
94        self.sender = sender;
95        self.reply_cap = reply_cap;
96        self
97    }
98
99    pub(crate) fn with_payload(mut self, payload: Value) -> Self {
100        self.payload = Arc::new(payload);
101        self
102    }
103}
104
105impl fmt::Display for Message {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        write!(
108            f,
109            "msg{{from=flow#{}, reply={}, id={}, tag={}, payload={}}}",
110            self.sender, self.reply_cap, self.request_id, self.tag, self.payload
111        )
112    }
113}
114
115/// A dynamically-tagged runtime value.
116///
117/// [`Value::Cap`] is an opaque [`CapId`] for `Send` / `Ask`. Authority lives
118/// in the runtime [`crate::CapTable`], keyed by holder — not in this tag.
119/// [`Value::Pid`] remains for **identity** inside authenticated messages.
120///
121/// [`Value::Str`] / [`Value::Bytes`] are heap payloads shared via [`Arc`].
122#[derive(Clone, Debug, PartialEq)]
123pub enum Value {
124    Unit,
125    Bool(bool),
126    Int(i64),
127    Float(f64),
128    /// Internal / message identity (FlowId as `u64`). **Not** a Send target.
129    Pid(u64),
130    /// Atomic Hop envelope. See [`Message`].
131    Message(Message),
132    /// Opaque capability token. Required for `Send` / `Ask`.
133    Cap(CapId),
134    /// UTF-8 text (constant pool, natives, host).
135    Str(Arc<str>),
136    /// Opaque byte buffer (constant pool, natives, host).
137    Bytes(Arc<[u8]>),
138}
139
140impl Value {
141    /// BFV0 wire tag for this value (`Unit=0` … `Bytes=8`).
142    ///
143    /// Used by [`crate::Opcode::ReceiveMatchKind`] selective receive.
144    #[inline]
145    pub fn wire_tag(&self) -> u8 {
146        match self {
147            Value::Unit => 0,
148            Value::Bool(_) => 1,
149            Value::Int(_) => 2,
150            Value::Float(_) => 3,
151            Value::Pid(_) => 4,
152            Value::Message(_) => 5,
153            Value::Cap(_) => 6,
154            Value::Str(_) => 7,
155            Value::Bytes(_) => 8,
156        }
157    }
158
159    /// Build a [`Value::Str`] from anything string-like.
160    #[inline]
161    pub fn str(s: impl AsRef<str>) -> Self {
162        Value::Str(Arc::from(s.as_ref()))
163    }
164
165    /// Build a [`Value::Bytes`] from a byte slice.
166    #[inline]
167    pub fn bytes(b: impl AsRef<[u8]>) -> Self {
168        Value::Bytes(Arc::from(b.as_ref()))
169    }
170
171    /// Truthiness used by `Opcode::Branch`: falsy are `Unit`, `Bool(false)`,
172    /// `Int(0)`, empty [`Value::Str`], and empty [`Value::Bytes`].
173    #[inline]
174    pub fn is_truthy(&self) -> bool {
175        match self {
176            Value::Unit | Value::Bool(false) | Value::Int(0) => false,
177            Value::Str(s) if s.is_empty() => false,
178            Value::Bytes(b) if b.is_empty() => false,
179            _ => true,
180        }
181    }
182
183    #[inline]
184    pub fn as_int(&self) -> Option<i64> {
185        match self {
186            Value::Int(i) => Some(*i),
187            Value::Bool(b) => Some(*b as i64),
188            _ => None,
189        }
190    }
191
192    #[inline]
193    pub fn as_pid(&self) -> Option<u64> {
194        match self {
195            Value::Pid(p) => Some(*p),
196            _ => None,
197        }
198    }
199
200    #[inline]
201    pub fn as_cap(&self) -> Option<CapId> {
202        match self {
203            Value::Cap(c) => Some(*c),
204            _ => None,
205        }
206    }
207
208    #[inline]
209    pub fn as_message(&self) -> Option<&Message> {
210        match self {
211            Value::Message(m) => Some(m),
212            _ => None,
213        }
214    }
215
216    #[inline]
217    pub fn as_str(&self) -> Option<&str> {
218        match self {
219            Value::Str(s) => Some(s.as_ref()),
220            _ => None,
221        }
222    }
223
224    #[inline]
225    pub fn as_bytes(&self) -> Option<&[u8]> {
226        match self {
227            Value::Bytes(b) => Some(b.as_ref()),
228            Value::Str(s) => Some(s.as_bytes()),
229            _ => None,
230        }
231    }
232
233    /// Bytes this value is **charged** for against a mailbox byte budget
234    /// (see [`crate::MailboxBytes`]).
235    ///
236    /// [`Value::Str`] / [`Value::Bytes`] / hop payloads are `Arc`-shared: the
237    /// same buffer cloned into N mailboxes exists once in memory, but each
238    /// mailbox is charged the full length. That over-counts on purpose.
239    #[inline]
240    pub fn memory_size(&self) -> usize {
241        std::mem::size_of::<Self>() + self.heap_size()
242    }
243
244    /// Heap bytes owned (transitively) by this value, excluding the enum
245    /// itself.
246    #[inline]
247    pub fn heap_size(&self) -> usize {
248        match self {
249            Value::Str(s) => s.len(),
250            Value::Bytes(b) => b.len(),
251            Value::Message(m) => m.payload.memory_size(),
252            Value::Unit
253            | Value::Bool(_)
254            | Value::Int(_)
255            | Value::Float(_)
256            | Value::Pid(_)
257            | Value::Cap(_) => 0,
258        }
259    }
260
261    pub fn type_name(&self) -> &'static str {
262        match self {
263            Value::Unit => "unit",
264            Value::Bool(_) => "bool",
265            Value::Int(_) => "int",
266            Value::Float(_) => "float",
267            Value::Pid(_) => "pid",
268            Value::Message(_) => "message",
269            Value::Cap(_) => "cap",
270            Value::Str(_) => "str",
271            Value::Bytes(_) => "bytes",
272        }
273    }
274}
275
276impl fmt::Display for Value {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        match self {
279            Value::Unit => write!(f, "()"),
280            Value::Bool(b) => write!(f, "{b}"),
281            Value::Int(i) => write!(f, "{i}"),
282            Value::Float(x) => write!(f, "{x}"),
283            Value::Pid(p) => write!(f, "flow#{p}"),
284            Value::Message(m) => write!(f, "{m}"),
285            Value::Cap(c) => write!(f, "{c}"),
286            Value::Str(s) => write!(f, "{s}"),
287            Value::Bytes(b) => write!(f, "bytes[{}]", b.len()),
288        }
289    }
290}
291
292impl From<i64> for Value {
293    fn from(v: i64) -> Self {
294        Value::Int(v)
295    }
296}
297impl From<i32> for Value {
298    fn from(v: i32) -> Self {
299        Value::Int(i64::from(v))
300    }
301}
302impl From<u64> for Value {
303    /// Fits the `Int` domain. Values above `i64::MAX` saturate instead of
304    /// becoming negative.
305    fn from(v: u64) -> Self {
306        let n = match i64::try_from(v) {
307            Ok(n) => n,
308            Err(_) => i64::MAX,
309        };
310        Value::Int(n)
311    }
312}
313impl From<bool> for Value {
314    fn from(v: bool) -> Self {
315        Value::Bool(v)
316    }
317}
318impl From<f64> for Value {
319    fn from(v: f64) -> Self {
320        Value::Float(v)
321    }
322}
323impl From<Message> for Value {
324    fn from(m: Message) -> Self {
325        Value::Message(m)
326    }
327}
328impl From<CapId> for Value {
329    fn from(c: CapId) -> Self {
330        Value::Cap(c)
331    }
332}
333impl From<&str> for Value {
334    fn from(s: &str) -> Self {
335        Value::str(s)
336    }
337}
338impl From<String> for Value {
339    fn from(s: String) -> Self {
340        Value::Str(Arc::from(s))
341    }
342}
343impl From<&[u8]> for Value {
344    fn from(b: &[u8]) -> Self {
345        Value::bytes(b)
346    }
347}
348impl From<Vec<u8>> for Value {
349    fn from(b: Vec<u8>) -> Self {
350        Value::Bytes(Arc::from(b))
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn message_is_truthy_and_round_trips_helpers() {
360        let m = Message::new(7, 99, 10, 1u64);
361        let v = Value::Message(m.clone());
362        assert!(v.is_truthy());
363        assert_eq!(v.as_message(), Some(&m));
364        assert_eq!(v.type_name(), "message");
365        assert_eq!(m.payload.as_ref(), &Value::Int(1));
366    }
367
368    #[test]
369    fn authenticate_stamps_sender_and_reply_cap() {
370        let reply = CapId::from_raw(7);
371        let m = Message::new(999, 1, 2, 3u64).authenticate(42, reply);
372        assert_eq!(m.sender, 42);
373        assert_eq!(m.reply_cap, reply);
374        assert_eq!(m.request_id, 1);
375    }
376
377    #[test]
378    fn str_payload_is_charged_on_the_hop() {
379        let hop = Value::Message(Message::new(1, 1, 1, Value::str("hello")));
380        assert!(hop.heap_size() >= 5);
381    }
382
383    #[test]
384    fn cap_is_truthy() {
385        let cap = CapId::from_raw(3);
386        assert!(Value::Cap(cap).is_truthy());
387        assert_eq!(Value::Cap(cap).as_cap(), Some(cap));
388    }
389
390    #[test]
391    fn str_and_bytes_helpers() {
392        let s = Value::str("hi");
393        assert_eq!(s.as_str(), Some("hi"));
394        assert_eq!(s.type_name(), "str");
395        assert!(s.is_truthy());
396        assert!(!Value::str("").is_truthy());
397
398        let b = Value::bytes([1u8, 2, 3]);
399        assert_eq!(b.as_bytes(), Some(&[1, 2, 3][..]));
400        assert_eq!(b.type_name(), "bytes");
401        assert!(b.is_truthy());
402        assert!(!Value::bytes([]).is_truthy());
403
404        assert_eq!(s.as_bytes(), Some(b"hi".as_slice()));
405    }
406
407    #[test]
408    fn u64_above_i64_max_saturates() {
409        assert_eq!(Value::from(u64::MAX), Value::Int(i64::MAX));
410        assert_eq!(Value::from(4u64), Value::Int(4));
411    }
412
413    #[test]
414    fn str_eq_compares_content() {
415        assert_eq!(Value::str("a"), Value::from("a".to_owned()));
416        assert_ne!(Value::str("a"), Value::str("b"));
417        assert_eq!(Value::bytes([9]), Value::from(vec![9u8]));
418    }
419}