Skip to main content

byteflow/bytecode/
value.rs

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