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