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/// Reserved Atomic Hop tag for a host `HostAwait` completion.
12/// `request_id` is the ticket written into the await register.
13pub const TAG_SYS_AWAIT: u16 = 0xFF03;
14
15/// Envelope carried in mailboxes and registers (**Atomic Hop**).
16///
17/// `payload` is a [`Value`] behind [`Arc`] so hops can carry `Int`, `Str`,
18/// `Bytes`, or nested messages. Mailbox byte budgets charge
19/// [`Value::memory_size`] of the whole hop, including the payload tree.
20///
21/// # Security
22///
23/// - **`sender`**: FlowId stamped by the scheduler on bytecode `Send` / `Ask`
24///   and host [`crate::Runtime::send`] (`0` = [`crate::FlowId::HOST`])
25///   (invariant **S1**). Not a capability.
26/// - **`reply_cap`**: stable SEND-only [`CapId`] per `(recipient, sender)`
27///   pair (holder = recipient, reused across hops). Correlation is
28///   [`Self::request_id`]. [`CapId::NONE`] means “no reply grant”.
29///
30/// See `docs/security.md`.
31#[derive(Clone, Debug, PartialEq)]
32pub struct Message {
33    /// Authenticated origin FlowId (`0` = trusted host / non-flow).
34    pub sender: u64,
35    /// Capability granting **SEND** back to [`Self::sender`], or [`CapId::NONE`].
36    pub reply_cap: CapId,
37    /// Client correlation token; echoed on replies (`Ask` / **S2**).
38    pub request_id: u64,
39    /// Protocol discriminator (opaque to the VM).
40    pub tag: u16,
41    /// Application body (shared so hop clones are cheap).
42    pub payload: Arc<Value>,
43}
44
45impl Message {
46    /// Build an envelope. `sender` / `reply_cap` are placeholders until a
47    /// bytecode hop is authenticated by the scheduler.
48    pub fn new(sender: u64, request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
49        Self {
50            sender,
51            reply_cap: CapId::NONE,
52            request_id,
53            tag,
54            payload: Arc::new(payload.into()),
55        }
56    }
57
58    /// Outgoing hop from host Rust (`sender` / `reply_cap` filled on delivery).
59    #[inline]
60    pub fn request(request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
61        Self::new(0, request_id, tag, payload)
62    }
63
64    /// Reply envelope echoing `request_id` from a received hop (host path).
65    #[inline]
66    pub fn reply_to(req: &Self, tag: u16, payload: impl Into<Value>) -> Self {
67        Self::new(0, req.request_id, tag, payload)
68    }
69
70    /// Runtime lifecycle hop: monitor `DOWN` (`tag == `[`TAG_SYS_DOWN`]).
71    #[inline]
72    pub fn down(monitor: u64, target_flow: u64, reason: u64) -> Self {
73        Self::new(
74            target_flow,
75            monitor,
76            TAG_SYS_DOWN,
77            Value::Int(reason as i64),
78        )
79    }
80
81    /// Runtime lifecycle hop: Ask target exited, or a linked peer exited
82    /// while this flow has `trap_exit` enabled (`tag == `[`TAG_SYS_EXIT`]).
83    #[inline]
84    pub fn linked_exit(target_flow: u64, reason: u64) -> Self {
85        Self::new(target_flow, 0, TAG_SYS_EXIT, Value::Int(reason as i64))
86    }
87
88    #[inline]
89    pub fn is_down(&self) -> bool {
90        self.tag == TAG_SYS_DOWN
91    }
92
93    #[inline]
94    pub fn is_exit(&self) -> bool {
95        self.tag == TAG_SYS_EXIT
96    }
97
98    /// Stamp origin FlowId and attach a reply capability (scheduler only).
99    #[inline(always)]
100    pub(crate) fn authenticate(mut self, sender: u64, reply_cap: CapId) -> Self {
101        self.sender = sender;
102        self.reply_cap = reply_cap;
103        self
104    }
105
106    #[inline]
107    pub(crate) fn with_payload(mut self, payload: Value) -> Self {
108        self.payload = Arc::new(payload);
109        self
110    }
111}
112
113/// Most elements a [`Value::List`] may hold. Wider sequences are rejected
114/// by the decoder, `ListPack`, and [`Value::try_list`].
115pub const MAX_LIST_LEN: usize = 256;
116
117/// Most pairs a [`Value::Map`] may hold. Keys are [`MapKey`] (`Int` or `Str`).
118pub const MAX_MAP_LEN: usize = 256;
119
120/// Most fields a [`Value::Record`] may hold. Positional, not a map.
121pub const MAX_RECORD_LEN: usize = 256;
122
123/// Key of a [`Value::Map`]. Floats are not keys: equality would not be
124/// a useful match, and a NaN key could never be read back.
125#[derive(Clone, Debug, PartialEq, Eq, Hash)]
126pub enum MapKey {
127    Int(i64),
128    Str(Arc<str>),
129}
130
131impl MapKey {
132    #[inline]
133    pub fn int(n: i64) -> Self {
134        MapKey::Int(n)
135    }
136
137    #[inline]
138    pub fn str(text: impl AsRef<str>) -> Self {
139        MapKey::Str(Arc::from(text.as_ref()))
140    }
141}
142
143/// Shared stand-in so [`Drop`] can detach a payload without allocating.
144#[inline]
145fn discarded_payload() -> Arc<Value> {
146    static EMPTY: std::sync::OnceLock<Arc<Value>> = std::sync::OnceLock::new();
147    Arc::clone(EMPTY.get_or_init(|| Arc::new(Value::Unit)))
148}
149
150impl Drop for Message {
151    fn drop(&mut self) {
152        // Leaf payloads fall through to the field drop. A nested `Message`
153        // is a chain: the default drop recurses one frame per hop and
154        // overflowed the stack on a long chain (the same failure `push`
155        // used to hit while sizing).
156        if !matches!(self.payload.as_ref(), Value::Message(_)) {
157            return;
158        }
159        let payload = std::mem::replace(&mut self.payload, discarded_payload());
160        let mut current = match Arc::into_inner(payload) {
161            Some(value) => value,
162            None => return,
163        };
164        while let Value::Message(mut message) = current {
165            let inner = std::mem::replace(&mut message.payload, discarded_payload());
166            current = match Arc::into_inner(inner) {
167                Some(value) => value,
168                None => return,
169            };
170        }
171    }
172}
173
174impl fmt::Display for Message {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(
177            f,
178            "msg{{from=flow#{}, reply={}, id={}, tag={}, payload={}}}",
179            self.sender, self.reply_cap, self.request_id, self.tag, self.payload
180        )
181    }
182}
183
184/// A dynamically-tagged runtime value.
185///
186/// [`Value::Cap`] is an opaque [`CapId`] for `Send` / `Ask`. Authority lives
187/// in the runtime capability table, keyed by holder — not in this tag.
188/// [`Value::Pid`] remains for **identity** inside authenticated messages.
189///
190/// [`Value::Str`] / [`Value::Bytes`] are heap payloads shared via [`Arc`].
191#[derive(Clone, Debug, PartialEq)]
192pub enum Value {
193    Unit,
194    Bool(bool),
195    Int(i64),
196    Float(f64),
197    /// Internal / message identity (FlowId as `u64`). **Not** a Send target.
198    Pid(u64),
199    /// Atomic Hop envelope. See [`Message`].
200    Message(Message),
201    /// Opaque capability token. Required for `Send` / `Ask`.
202    Cap(CapId),
203    /// UTF-8 text (constant pool, natives, host).
204    Str(Arc<str>),
205    /// Opaque byte buffer (constant pool, natives, host).
206    Bytes(Arc<[u8]>),
207    /// Bounded sequence (ABI v6 wire tag `9`). At most [`MAX_LIST_LEN`]
208    /// elements; nesting shares the decoder depth ceiling with `Message`.
209    List(Arc<[Value]>),
210    /// Bounded map (ABI v7 wire tag `10`). At most [`MAX_MAP_LEN`] pairs.
211    /// Insertion order is kept. A duplicate key is rejected at construction.
212    Map(Arc<[(MapKey, Value)]>),
213    /// Positional record (ABI v8 wire tag `11`). At most [`MAX_RECORD_LEN`]
214    /// fields. Not a map and not a receive pattern.
215    Record(Arc<[Value]>),
216}
217
218/// A repeated [`MapKey`] is a distinct failure from nesting or length.
219/// [`Value::try_map`] rejects both; the decoder reports the duplicate on its
220/// own so a hostile module is not described as too deep.
221pub(crate) fn map_has_duplicate_key(entries: &[(MapKey, Value)]) -> bool {
222    let mut seen = std::collections::HashSet::with_capacity(entries.len());
223    for entry in entries {
224        if !seen.insert(&entry.0) {
225            return true;
226        }
227    }
228    false
229}
230
231impl Value {
232    /// BFV0 wire tag for this value (`Unit=0` … `Bytes=8`, `List=9`, `Map=10`,
233    /// `Record=11`).
234    ///
235    /// Used by [`crate::Opcode::ReceiveMatchKind`] selective receive, which
236    /// names tags `0..=10`. A record is tag `11` and is not a receive pattern.
237    #[inline]
238    pub fn wire_tag(&self) -> u8 {
239        match self {
240            Value::Unit => 0,
241            Value::Bool(_) => 1,
242            Value::Int(_) => 2,
243            Value::Float(_) => 3,
244            Value::Pid(_) => 4,
245            Value::Message(_) => 5,
246            Value::Cap(_) => 6,
247            Value::Str(_) => 7,
248            Value::Bytes(_) => 8,
249            Value::List(_) => 9,
250            Value::Map(_) => 10,
251            Value::Record(_) => 11,
252        }
253    }
254
255    /// Value stored under `key`, if `self` is a map that contains it.
256    pub fn map_get(&self, key: &MapKey) -> Option<&Value> {
257        match self {
258            Value::Map(entries) => entries
259                .iter()
260                .find(|(existing, _)| existing == key)
261                .map(|(_, value)| value),
262            _ => None,
263        }
264    }
265
266    /// Build a [`Value::Map`]. Fails when there are more than [`MAX_MAP_LEN`]
267    /// pairs, a key is repeated, or nesting exceeds the decoder ceiling.
268    pub fn try_map(entries: Vec<(MapKey, Value)>) -> Option<Self> {
269        if entries.len() > MAX_MAP_LEN || map_has_duplicate_key(&entries) {
270            return None;
271        }
272        let value = Value::Map(Arc::from(entries));
273        if value.within_nesting_limit() {
274            Some(value)
275        } else {
276            None
277        }
278    }
279
280    /// Build a [`Value::List`]. Fails when `items` is longer than
281    /// [`MAX_LIST_LEN`] or the nested `Message` / `List` depth exceeds the
282    /// decoder ceiling.
283    pub fn try_list(items: Vec<Value>) -> Option<Self> {
284        if items.len() > MAX_LIST_LEN {
285            return None;
286        }
287        let value = Value::List(Arc::from(items));
288        if value.within_nesting_limit() {
289            Some(value)
290        } else {
291            None
292        }
293    }
294
295    /// Build a [`Value::Record`]. Fails when `fields` is longer than
296    /// [`MAX_RECORD_LEN`] or nesting exceeds the decoder ceiling.
297    pub fn try_record(fields: Vec<Value>) -> Option<Self> {
298        if fields.len() > MAX_RECORD_LEN {
299            return None;
300        }
301        let value = Value::Record(Arc::from(fields));
302        if value.within_nesting_limit() {
303            Some(value)
304        } else {
305            None
306        }
307    }
308
309    /// Build a [`Value::Str`] from anything string-like.
310    #[inline]
311    pub fn str(s: impl AsRef<str>) -> Self {
312        Value::Str(Arc::from(s.as_ref()))
313    }
314
315    /// Build a [`Value::Bytes`] from a byte slice.
316    #[inline]
317    pub fn bytes(b: impl AsRef<[u8]>) -> Self {
318        Value::Bytes(Arc::from(b.as_ref()))
319    }
320
321    /// Same ceiling as the `.bf` decoder ([`super::MAX_VALUE_DEPTH`]).
322    ///
323    /// A deeper `Message` chain would recurse through cap reissue on a
324    /// worker stack. The walk stops at the limit instead of descending.
325    pub(crate) fn within_nesting_limit(&self) -> bool {
326        fn walk(value: &Value, depth: u32) -> bool {
327            if depth > super::MAX_VALUE_DEPTH {
328                return false;
329            }
330            match value {
331                Value::Message(message) => walk(message.payload.as_ref(), depth + 1),
332                Value::List(items) | Value::Record(items) => {
333                    items.iter().all(|item| walk(item, depth + 1))
334                }
335                Value::Map(entries) => entries.iter().all(|(_, value)| walk(value, depth + 1)),
336                _ => true,
337            }
338        }
339        walk(self, 0)
340    }
341
342    /// Rewrite every live [`CapId`](crate::CapId) stored as [`Value::Cap`].
343    ///
344    /// [`CapId::NONE`](crate::CapId::NONE) stays put until `on_message`
345    /// decides what a nested hop's `reply_cap` becomes. A [`Value::List`] is
346    /// walked element by element, so a token cannot hide in a sequence and
347    /// cross a flow boundary unchanged. `on_message` runs after the payload
348    /// has been rewritten, from the inside out.
349    pub(crate) fn map_caps<E: Clone>(
350        &self,
351        depth: u32,
352        too_nested: &E,
353        on_cap: &mut impl FnMut(CapId) -> Result<CapId, E>,
354        on_message: &mut impl FnMut(&mut Message) -> Result<(), E>,
355    ) -> Result<Value, E> {
356        if depth > super::MAX_VALUE_DEPTH {
357            return Err(too_nested.clone());
358        }
359        match self {
360            Value::Cap(id) if id.is_none() => Ok(Value::Cap(*id)),
361            Value::Cap(id) => Ok(Value::Cap(on_cap(*id)?)),
362            Value::Message(message) => {
363                let payload =
364                    message
365                        .payload
366                        .map_caps(depth + 1, too_nested, on_cap, on_message)?;
367                let mut next = message.clone().with_payload(payload);
368                on_message(&mut next)?;
369                Ok(Value::Message(next))
370            }
371            Value::List(items) => {
372                let mut next = Vec::with_capacity(items.len());
373                for item in items.iter() {
374                    next.push(item.map_caps(depth + 1, too_nested, on_cap, on_message)?);
375                }
376                Value::try_list(next).ok_or_else(|| too_nested.clone())
377            }
378            Value::Map(entries) => {
379                let mut next = Vec::with_capacity(entries.len());
380                for (key, value) in entries.iter() {
381                    next.push((
382                        key.clone(),
383                        value.map_caps(depth + 1, too_nested, on_cap, on_message)?,
384                    ));
385                }
386                Value::try_map(next).ok_or_else(|| too_nested.clone())
387            }
388            Value::Record(fields) => {
389                let mut next = Vec::with_capacity(fields.len());
390                for field in fields.iter() {
391                    next.push(field.map_caps(depth + 1, too_nested, on_cap, on_message)?);
392                }
393                Value::try_record(next).ok_or_else(|| too_nested.clone())
394            }
395            other => Ok(other.clone()),
396        }
397    }
398
399    /// Stamp envelopes that `make_msg` left unset (`sender == 0`,
400    /// `request_id == 0`). A non-zero sender was already authenticated and
401    /// is kept. `reply_cap` is not minted here — the caller decides whether
402    /// a reply grant exists on this boundary.
403    ///
404    /// `None` means the value is nested past the decoder ceiling.
405    pub(crate) fn stamp_unset_envelopes(
406        &self,
407        depth: u32,
408        sender_if_unset: u64,
409        mint: &mut impl FnMut() -> u64,
410    ) -> Option<Value> {
411        if depth > super::MAX_VALUE_DEPTH {
412            return None;
413        }
414        match self {
415            Value::Message(message) => {
416                let payload =
417                    message
418                        .payload
419                        .stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?;
420                let mut next = message.clone().with_payload(payload);
421                if next.sender == 0 && sender_if_unset != 0 {
422                    next.sender = sender_if_unset;
423                }
424                if next.request_id == 0 {
425                    next.request_id = mint();
426                }
427                Some(Value::Message(next))
428            }
429            Value::List(items) => {
430                let mut next = Vec::with_capacity(items.len());
431                for item in items.iter() {
432                    next.push(item.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?);
433                }
434                Value::try_list(next)
435            }
436            Value::Map(entries) => {
437                let mut next = Vec::with_capacity(entries.len());
438                for (key, value) in entries.iter() {
439                    next.push((
440                        key.clone(),
441                        value.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?,
442                    ));
443                }
444                Value::try_map(next)
445            }
446            Value::Record(fields) => {
447                let mut next = Vec::with_capacity(fields.len());
448                for field in fields.iter() {
449                    next.push(field.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?);
450                }
451                Value::try_record(next)
452            }
453            other => Some(other.clone()),
454        }
455    }
456
457    /// A live capability token appears anywhere in this value, including a
458    /// nested hop's `reply_cap` and the elements of a list.
459    ///
460    /// Past the decoder ceiling the answer is `true`: the caller must fail
461    /// closed instead of shipping a value it could not inspect.
462    pub(crate) fn contains_live_cap(&self, depth: u32) -> bool {
463        if depth > super::MAX_VALUE_DEPTH {
464            return true;
465        }
466        match self {
467            Value::Cap(id) => !id.is_none(),
468            Value::Message(message) => {
469                !message.reply_cap.is_none() || message.payload.contains_live_cap(depth + 1)
470            }
471            Value::List(items) | Value::Record(items) => {
472                items.iter().any(|item| item.contains_live_cap(depth + 1))
473            }
474            Value::Map(entries) => entries
475                .iter()
476                .any(|(_, value)| value.contains_live_cap(depth + 1)),
477            _ => false,
478        }
479    }
480
481    /// Returns true if this value is a scalar (charges 0 heap bytes and has no nested allocations).
482    #[inline]
483    pub fn is_scalar(&self) -> bool {
484        matches!(
485            self,
486            Value::Unit
487                | Value::Bool(_)
488                | Value::Int(_)
489                | Value::Float(_)
490                | Value::Pid(_)
491                | Value::Cap(_)
492        )
493    }
494
495    /// Truthiness used by `Opcode::Branch`: falsy are `Unit`, `Bool(false)`,
496    /// `Int(0)`, empty [`Value::Str`], empty [`Value::Bytes`], empty
497    /// [`Value::List`], empty [`Value::Map`], and empty [`Value::Record`].
498    #[inline]
499    pub fn is_truthy(&self) -> bool {
500        match self {
501            Value::Unit | Value::Bool(false) | Value::Int(0) => false,
502            Value::Str(s) if s.is_empty() => false,
503            Value::Bytes(b) if b.is_empty() => false,
504            Value::List(items) | Value::Record(items) if items.is_empty() => false,
505            Value::Map(entries) if entries.is_empty() => false,
506            _ => true,
507        }
508    }
509
510    /// `Int`, or `Bool` as `0` / `1`.
511    ///
512    /// This coercion is for host natives ([`crate::vm::expect_int`]). Opcode
513    /// operands that require an integer (`Sleep`, tags, `request_id`) do not
514    /// use it — a `Bool` there is a type error.
515    #[inline]
516    pub fn as_int(&self) -> Option<i64> {
517        match self {
518            Value::Int(i) => Some(*i),
519            Value::Bool(b) => Some(*b as i64),
520            _ => None,
521        }
522    }
523
524    #[inline]
525    pub fn as_pid(&self) -> Option<u64> {
526        match self {
527            Value::Pid(p) => Some(*p),
528            _ => None,
529        }
530    }
531
532    #[inline]
533    pub fn as_cap(&self) -> Option<CapId> {
534        match self {
535            Value::Cap(c) => Some(*c),
536            _ => None,
537        }
538    }
539
540    #[inline]
541    pub fn as_message(&self) -> Option<&Message> {
542        match self {
543            Value::Message(m) => Some(m),
544            _ => None,
545        }
546    }
547
548    #[inline]
549    pub fn as_str(&self) -> Option<&str> {
550        match self {
551            Value::Str(s) => Some(s.as_ref()),
552            _ => None,
553        }
554    }
555
556    #[inline]
557    pub fn as_bytes(&self) -> Option<&[u8]> {
558        match self {
559            Value::Bytes(b) => Some(b.as_ref()),
560            Value::Str(s) => Some(s.as_bytes()),
561            _ => None,
562        }
563    }
564
565    /// Bytes this value is **charged** for against a mailbox byte budget
566    /// (see [`crate::MailboxBytes`]).
567    ///
568    /// [`Value::Str`] / [`Value::Bytes`] / hop payloads are `Arc`-shared: the
569    /// same buffer cloned into N mailboxes exists once in memory, but each
570    /// mailbox is charged the full length. That over-counts on purpose.
571    ///
572    /// A `Message` chain deeper than the decoder depth ceiling does not
573    /// walk the tail. The returned size is [`usize::MAX`], which no mailbox
574    /// budget can admit.
575    #[inline]
576    pub fn memory_size(&self) -> usize {
577        match self.heap_size_limited() {
578            Some(heap) => std::mem::size_of::<Self>().saturating_add(heap),
579            None => usize::MAX,
580        }
581    }
582
583    /// Heap bytes owned (transitively) by this value, excluding the enum
584    /// itself.
585    ///
586    /// One `Arc` inside this value is counted once. A chain past the decoder
587    /// ceiling yields [`usize::MAX`] instead of recursing.
588    #[inline]
589    pub fn heap_size(&self) -> usize {
590        self.heap_size_limited().unwrap_or(usize::MAX)
591    }
592
593    /// `None` when the `Message` chain is deeper than the decoder ceiling or
594    /// the byte sum does not fit in `usize`.
595    ///
596    /// Iterative on purpose: `Mailbox::push` asks for this size, and a
597    /// recursive walk of a long chain overflowed the caller's stack.
598    fn heap_size_limited(&self) -> Option<usize> {
599        fn walk(value: &Value, depth: u32) -> Option<usize> {
600            let mut extra = 0usize;
601            let mut cursor = value;
602            let mut depth = depth;
603            loop {
604                match cursor {
605                    Value::Message(message) => {
606                        if depth >= super::MAX_VALUE_DEPTH {
607                            return None;
608                        }
609                        extra = extra.checked_add(std::mem::size_of::<Value>())?;
610                        cursor = message.payload.as_ref();
611                        depth += 1;
612                    }
613                    Value::List(items) | Value::Record(items) => {
614                        if depth >= super::MAX_VALUE_DEPTH {
615                            return None;
616                        }
617                        let slots = items.len().checked_mul(std::mem::size_of::<Value>())?;
618                        extra = extra.checked_add(slots)?;
619                        for item in items.iter() {
620                            extra = extra.checked_add(walk(item, depth + 1)?)?;
621                        }
622                        return Some(extra);
623                    }
624                    Value::Map(entries) => {
625                        if depth >= super::MAX_VALUE_DEPTH {
626                            return None;
627                        }
628                        let slots = entries.len().checked_mul(std::mem::size_of::<Value>())?;
629                        extra = extra.checked_add(slots)?;
630                        for (key, value) in entries.iter() {
631                            if let MapKey::Str(text) = key {
632                                extra = extra.checked_add(text.len())?;
633                            }
634                            extra = extra.checked_add(walk(value, depth + 1)?)?;
635                        }
636                        return Some(extra);
637                    }
638                    Value::Str(s) => return extra.checked_add(s.len()),
639                    Value::Bytes(b) => return extra.checked_add(b.len()),
640                    Value::Unit
641                    | Value::Bool(_)
642                    | Value::Int(_)
643                    | Value::Float(_)
644                    | Value::Pid(_)
645                    | Value::Cap(_) => return Some(extra),
646                }
647            }
648        }
649        walk(self, 0)
650    }
651
652    pub fn type_name(&self) -> &'static str {
653        match self {
654            Value::Unit => "unit",
655            Value::Bool(_) => "bool",
656            Value::Int(_) => "int",
657            Value::Float(_) => "float",
658            Value::Pid(_) => "pid",
659            Value::Message(_) => "message",
660            Value::Cap(_) => "cap",
661            Value::Str(_) => "str",
662            Value::Bytes(_) => "bytes",
663            Value::List(_) => "list",
664            Value::Map(_) => "map",
665            Value::Record(_) => "record",
666        }
667    }
668}
669
670impl fmt::Display for Value {
671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672        match self {
673            Value::Unit => write!(f, "()"),
674            Value::Bool(b) => write!(f, "{b}"),
675            Value::Int(i) => write!(f, "{i}"),
676            Value::Float(x) => write!(f, "{x}"),
677            Value::Pid(p) => write!(f, "flow#{p}"),
678            Value::Message(m) => write!(f, "{m}"),
679            Value::Cap(c) => write!(f, "{c}"),
680            Value::Str(s) => write!(f, "{s}"),
681            Value::Bytes(b) => write!(f, "bytes[{}]", b.len()),
682            Value::List(items) => {
683                write!(f, "[")?;
684                for (index, item) in items.iter().enumerate() {
685                    if index > 0 {
686                        write!(f, ", ")?;
687                    }
688                    write!(f, "{item}")?;
689                }
690                write!(f, "]")
691            }
692            Value::Map(entries) => {
693                write!(f, "{{")?;
694                for (index, (key, value)) in entries.iter().enumerate() {
695                    if index > 0 {
696                        write!(f, ", ")?;
697                    }
698                    match key {
699                        MapKey::Int(n) => write!(f, "{n}")?,
700                        MapKey::Str(text) => write!(f, "{text}")?,
701                    }
702                    write!(f, ": {value}")?;
703                }
704                write!(f, "}}")
705            }
706            Value::Record(fields) => {
707                write!(f, "rec(")?;
708                for (index, field) in fields.iter().enumerate() {
709                    if index > 0 {
710                        write!(f, ", ")?;
711                    }
712                    write!(f, "{field}")?;
713                }
714                write!(f, ")")
715            }
716        }
717    }
718}
719
720impl From<i64> for Value {
721    fn from(v: i64) -> Self {
722        Value::Int(v)
723    }
724}
725impl From<i32> for Value {
726    fn from(v: i32) -> Self {
727        Value::Int(i64::from(v))
728    }
729}
730impl From<u64> for Value {
731    /// Fits the `Int` domain. Values above `i64::MAX` saturate instead of
732    /// becoming negative.
733    fn from(v: u64) -> Self {
734        let n = match i64::try_from(v) {
735            Ok(n) => n,
736            Err(_) => i64::MAX,
737        };
738        Value::Int(n)
739    }
740}
741impl From<bool> for Value {
742    fn from(v: bool) -> Self {
743        Value::Bool(v)
744    }
745}
746impl From<f64> for Value {
747    fn from(v: f64) -> Self {
748        Value::Float(v)
749    }
750}
751impl From<Message> for Value {
752    fn from(m: Message) -> Self {
753        Value::Message(m)
754    }
755}
756impl From<CapId> for Value {
757    fn from(c: CapId) -> Self {
758        Value::Cap(c)
759    }
760}
761impl From<&str> for Value {
762    fn from(s: &str) -> Self {
763        Value::str(s)
764    }
765}
766impl From<String> for Value {
767    fn from(s: String) -> Self {
768        Value::Str(Arc::from(s))
769    }
770}
771impl From<&[u8]> for Value {
772    fn from(b: &[u8]) -> Self {
773        Value::bytes(b)
774    }
775}
776impl From<Vec<u8>> for Value {
777    fn from(b: Vec<u8>) -> Self {
778        Value::Bytes(Arc::from(b))
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[test]
787    fn nesting_stops_at_the_decoder_ceiling() {
788        let mut value = Value::Int(1);
789        for _ in 0..16 {
790            value = Value::Message(Message::new(0, 1, 1, value));
791        }
792        assert!(value.within_nesting_limit());
793        value = Value::Message(Message::new(0, 1, 1, value));
794        assert!(!value.within_nesting_limit());
795    }
796
797    #[test]
798    fn message_is_truthy_and_round_trips_helpers() {
799        let m = Message::new(7, 99, 10, 1u64);
800        let v = Value::Message(m.clone());
801        assert!(v.is_truthy());
802        assert_eq!(v.as_message(), Some(&m));
803        assert_eq!(v.type_name(), "message");
804        assert_eq!(m.payload.as_ref(), &Value::Int(1));
805    }
806
807    #[test]
808    fn authenticate_stamps_sender_and_reply_cap() {
809        let reply = CapId::from_raw(7);
810        let m = Message::new(999, 1, 2, 3u64).authenticate(42, reply);
811        assert_eq!(m.sender, 42);
812        assert_eq!(m.reply_cap, reply);
813        assert_eq!(m.request_id, 1);
814    }
815
816    #[test]
817    fn str_payload_is_charged_on_the_hop() {
818        let hop = Value::Message(Message::new(1, 1, 1, Value::str("hello")));
819        assert!(hop.heap_size() >= 5);
820    }
821
822    #[test]
823    fn nested_message_heap_counts_each_envelope_until_the_ceiling() {
824        let word = std::mem::size_of::<Value>();
825        let mut value = Value::str("hello");
826        for _ in 0..16 {
827            value = Value::Message(Message::new(0, 1, 1, value));
828        }
829        assert!(value.within_nesting_limit());
830        assert_eq!(value.heap_size(), 16 * word + 5);
831        assert_eq!(value.memory_size(), word + 16 * word + 5);
832        let blob = Value::Message(Message::new(0, 1, 1, Value::bytes(vec![0u8; 50_000])));
833        assert_eq!(blob.heap_size(), word + 50_000);
834        value = Value::Message(Message::new(0, 1, 1, value));
835        assert!(!value.within_nesting_limit());
836        assert_eq!(value.heap_size(), usize::MAX);
837        assert_eq!(value.memory_size(), usize::MAX);
838    }
839
840    #[test]
841    fn a_long_message_chain_sizes_without_recursing_off_the_stack() {
842        let mut value = Value::Int(1);
843        for _ in 0..10_000 {
844            value = Value::Message(Message::new(0, 1, 1, value));
845        }
846        assert!(!value.within_nesting_limit());
847        assert_eq!(value.heap_size(), usize::MAX);
848        assert_eq!(value.memory_size(), usize::MAX);
849    }
850
851    #[test]
852    fn cap_is_truthy() {
853        let cap = CapId::from_raw(3);
854        assert!(Value::Cap(cap).is_truthy());
855        assert_eq!(Value::Cap(cap).as_cap(), Some(cap));
856    }
857
858    #[test]
859    fn str_and_bytes_helpers() {
860        let s = Value::str("hi");
861        assert_eq!(s.as_str(), Some("hi"));
862        assert_eq!(s.type_name(), "str");
863        assert!(s.is_truthy());
864        assert!(!Value::str("").is_truthy());
865
866        let b = Value::bytes([1u8, 2, 3]);
867        assert_eq!(b.as_bytes(), Some(&[1, 2, 3][..]));
868        assert_eq!(b.type_name(), "bytes");
869        assert!(b.is_truthy());
870        assert!(!Value::bytes([]).is_truthy());
871
872        assert_eq!(s.as_bytes(), Some(b"hi".as_slice()));
873    }
874
875    #[test]
876    fn u64_above_i64_max_saturates() {
877        assert_eq!(Value::from(u64::MAX), Value::Int(i64::MAX));
878        assert_eq!(Value::from(4u64), Value::Int(4));
879    }
880
881    #[test]
882    fn str_eq_compares_content() {
883        assert_eq!(Value::str("a"), Value::from("a".to_owned()));
884        assert_ne!(Value::str("a"), Value::str("b"));
885        assert_eq!(Value::bytes([9]), Value::from(vec![9u8]));
886    }
887}