1use std::fmt;
2use std::sync::Arc;
3
4use super::cap::CapId;
5
6pub const TAG_SYS_DOWN: u16 = 0xFF01;
8pub const TAG_SYS_EXIT: u16 = 0xFF02;
11pub const TAG_SYS_AWAIT: u16 = 0xFF03;
14
15#[derive(Clone, Debug, PartialEq)]
32pub struct Message {
33 pub sender: u64,
35 pub reply_cap: CapId,
37 pub request_id: u64,
39 pub tag: u16,
41 pub payload: Arc<Value>,
43}
44
45impl Message {
46 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 pub fn request(request_id: u64, tag: u16, payload: impl Into<Value>) -> Self {
60 Self::new(0, request_id, tag, payload)
61 }
62
63 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 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 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 #[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
108pub const MAX_LIST_LEN: usize = 32;
111
112pub const MAX_MAP_LEN: usize = 32;
114
115#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum MapKey {
119 Int(i64),
120 Str(Arc<str>),
121}
122
123impl MapKey {
124 pub fn int(n: i64) -> Self {
125 MapKey::Int(n)
126 }
127
128 pub fn str(text: impl AsRef<str>) -> Self {
129 MapKey::Str(Arc::from(text.as_ref()))
130 }
131}
132
133fn discarded_payload() -> Arc<Value> {
135 static EMPTY: std::sync::OnceLock<Arc<Value>> = std::sync::OnceLock::new();
136 Arc::clone(EMPTY.get_or_init(|| Arc::new(Value::Unit)))
137}
138
139impl Drop for Message {
140 fn drop(&mut self) {
141 if !matches!(self.payload.as_ref(), Value::Message(_)) {
146 return;
147 }
148 let payload = std::mem::replace(&mut self.payload, discarded_payload());
149 let mut current = match Arc::into_inner(payload) {
150 Some(value) => value,
151 None => return,
152 };
153 while let Value::Message(mut message) = current {
154 let inner = std::mem::replace(&mut message.payload, discarded_payload());
155 current = match Arc::into_inner(inner) {
156 Some(value) => value,
157 None => return,
158 };
159 }
160 }
161}
162
163impl fmt::Display for Message {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 write!(
166 f,
167 "msg{{from=flow#{}, reply={}, id={}, tag={}, payload={}}}",
168 self.sender, self.reply_cap, self.request_id, self.tag, self.payload
169 )
170 }
171}
172
173#[derive(Clone, Debug, PartialEq)]
181pub enum Value {
182 Unit,
183 Bool(bool),
184 Int(i64),
185 Float(f64),
186 Pid(u64),
188 Message(Message),
190 Cap(CapId),
192 Str(Arc<str>),
194 Bytes(Arc<[u8]>),
196 List(Arc<[Value]>),
199 Map(Arc<[(MapKey, Value)]>),
202}
203
204impl Value {
205 #[inline]
209 pub fn wire_tag(&self) -> u8 {
210 match self {
211 Value::Unit => 0,
212 Value::Bool(_) => 1,
213 Value::Int(_) => 2,
214 Value::Float(_) => 3,
215 Value::Pid(_) => 4,
216 Value::Message(_) => 5,
217 Value::Cap(_) => 6,
218 Value::Str(_) => 7,
219 Value::Bytes(_) => 8,
220 Value::List(_) => 9,
221 Value::Map(_) => 10,
222 }
223 }
224
225 pub fn map_get(&self, key: &MapKey) -> Option<&Value> {
227 match self {
228 Value::Map(entries) => entries
229 .iter()
230 .find(|(existing, _)| existing == key)
231 .map(|(_, value)| value),
232 _ => None,
233 }
234 }
235
236 pub fn try_map(entries: Vec<(MapKey, Value)>) -> Option<Self> {
239 if entries.len() > MAX_MAP_LEN {
240 return None;
241 }
242 for index in 0..entries.len() {
243 for earlier in 0..index {
244 if entries[index].0 == entries[earlier].0 {
245 return None;
246 }
247 }
248 }
249 let value = Value::Map(Arc::from(entries));
250 if value.within_nesting_limit() {
251 Some(value)
252 } else {
253 None
254 }
255 }
256
257 pub fn try_list(items: Vec<Value>) -> Option<Self> {
261 if items.len() > MAX_LIST_LEN {
262 return None;
263 }
264 let value = Value::List(Arc::from(items));
265 if value.within_nesting_limit() {
266 Some(value)
267 } else {
268 None
269 }
270 }
271
272 #[inline]
274 pub fn str(s: impl AsRef<str>) -> Self {
275 Value::Str(Arc::from(s.as_ref()))
276 }
277
278 #[inline]
280 pub fn bytes(b: impl AsRef<[u8]>) -> Self {
281 Value::Bytes(Arc::from(b.as_ref()))
282 }
283
284 pub(crate) fn within_nesting_limit(&self) -> bool {
289 fn walk(value: &Value, depth: u32) -> bool {
290 if depth > super::MAX_VALUE_DEPTH {
291 return false;
292 }
293 match value {
294 Value::Message(message) => walk(message.payload.as_ref(), depth + 1),
295 Value::List(items) => items.iter().all(|item| walk(item, depth + 1)),
296 Value::Map(entries) => entries.iter().all(|(_, value)| walk(value, depth + 1)),
297 _ => true,
298 }
299 }
300 walk(self, 0)
301 }
302
303 pub(crate) fn map_caps<E: Clone>(
311 &self,
312 depth: u32,
313 too_nested: &E,
314 on_cap: &mut impl FnMut(CapId) -> Result<CapId, E>,
315 on_message: &mut impl FnMut(&mut Message) -> Result<(), E>,
316 ) -> Result<Value, E> {
317 if depth > super::MAX_VALUE_DEPTH {
318 return Err(too_nested.clone());
319 }
320 match self {
321 Value::Cap(id) if id.is_none() => Ok(Value::Cap(*id)),
322 Value::Cap(id) => Ok(Value::Cap(on_cap(*id)?)),
323 Value::Message(message) => {
324 let payload =
325 message
326 .payload
327 .map_caps(depth + 1, too_nested, on_cap, on_message)?;
328 let mut next = message.clone().with_payload(payload);
329 on_message(&mut next)?;
330 Ok(Value::Message(next))
331 }
332 Value::List(items) => {
333 let mut next = Vec::with_capacity(items.len());
334 for item in items.iter() {
335 next.push(item.map_caps(depth + 1, too_nested, on_cap, on_message)?);
336 }
337 Value::try_list(next).ok_or_else(|| too_nested.clone())
338 }
339 Value::Map(entries) => {
340 let mut next = Vec::with_capacity(entries.len());
341 for (key, value) in entries.iter() {
342 next.push((
343 key.clone(),
344 value.map_caps(depth + 1, too_nested, on_cap, on_message)?,
345 ));
346 }
347 Value::try_map(next).ok_or_else(|| too_nested.clone())
348 }
349 other => Ok(other.clone()),
350 }
351 }
352
353 pub(crate) fn stamp_unset_envelopes(
360 &self,
361 depth: u32,
362 sender_if_unset: u64,
363 mint: &mut impl FnMut() -> u64,
364 ) -> Option<Value> {
365 if depth > super::MAX_VALUE_DEPTH {
366 return None;
367 }
368 match self {
369 Value::Message(message) => {
370 let payload =
371 message
372 .payload
373 .stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?;
374 let mut next = message.clone().with_payload(payload);
375 if next.sender == 0 && sender_if_unset != 0 {
376 next.sender = sender_if_unset;
377 }
378 if next.request_id == 0 {
379 next.request_id = mint();
380 }
381 Some(Value::Message(next))
382 }
383 Value::List(items) => {
384 let mut next = Vec::with_capacity(items.len());
385 for item in items.iter() {
386 next.push(item.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?);
387 }
388 Value::try_list(next)
389 }
390 Value::Map(entries) => {
391 let mut next = Vec::with_capacity(entries.len());
392 for (key, value) in entries.iter() {
393 next.push((
394 key.clone(),
395 value.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?,
396 ));
397 }
398 Value::try_map(next)
399 }
400 other => Some(other.clone()),
401 }
402 }
403
404 pub(crate) fn contains_live_cap(&self, depth: u32) -> bool {
410 if depth > super::MAX_VALUE_DEPTH {
411 return true;
412 }
413 match self {
414 Value::Cap(id) => !id.is_none(),
415 Value::Message(message) => {
416 !message.reply_cap.is_none() || message.payload.contains_live_cap(depth + 1)
417 }
418 Value::List(items) => items.iter().any(|item| item.contains_live_cap(depth + 1)),
419 Value::Map(entries) => entries
420 .iter()
421 .any(|(_, value)| value.contains_live_cap(depth + 1)),
422 _ => false,
423 }
424 }
425
426 #[inline]
430 pub fn is_truthy(&self) -> bool {
431 match self {
432 Value::Unit | Value::Bool(false) | Value::Int(0) => false,
433 Value::Str(s) if s.is_empty() => false,
434 Value::Bytes(b) if b.is_empty() => false,
435 Value::List(items) if items.is_empty() => false,
436 Value::Map(entries) if entries.is_empty() => false,
437 _ => true,
438 }
439 }
440
441 #[inline]
447 pub fn as_int(&self) -> Option<i64> {
448 match self {
449 Value::Int(i) => Some(*i),
450 Value::Bool(b) => Some(*b as i64),
451 _ => None,
452 }
453 }
454
455 #[inline]
456 pub fn as_pid(&self) -> Option<u64> {
457 match self {
458 Value::Pid(p) => Some(*p),
459 _ => None,
460 }
461 }
462
463 #[inline]
464 pub fn as_cap(&self) -> Option<CapId> {
465 match self {
466 Value::Cap(c) => Some(*c),
467 _ => None,
468 }
469 }
470
471 #[inline]
472 pub fn as_message(&self) -> Option<&Message> {
473 match self {
474 Value::Message(m) => Some(m),
475 _ => None,
476 }
477 }
478
479 #[inline]
480 pub fn as_str(&self) -> Option<&str> {
481 match self {
482 Value::Str(s) => Some(s.as_ref()),
483 _ => None,
484 }
485 }
486
487 #[inline]
488 pub fn as_bytes(&self) -> Option<&[u8]> {
489 match self {
490 Value::Bytes(b) => Some(b.as_ref()),
491 Value::Str(s) => Some(s.as_bytes()),
492 _ => None,
493 }
494 }
495
496 #[inline]
507 pub fn memory_size(&self) -> usize {
508 match self.heap_size_limited() {
509 Some(heap) => std::mem::size_of::<Self>().saturating_add(heap),
510 None => usize::MAX,
511 }
512 }
513
514 #[inline]
520 pub fn heap_size(&self) -> usize {
521 self.heap_size_limited().unwrap_or(usize::MAX)
522 }
523
524 fn heap_size_limited(&self) -> Option<usize> {
530 fn walk(value: &Value, depth: u32) -> Option<usize> {
531 let mut extra = 0usize;
532 let mut cursor = value;
533 let mut depth = depth;
534 loop {
535 match cursor {
536 Value::Message(message) => {
537 if depth >= super::MAX_VALUE_DEPTH {
538 return None;
539 }
540 extra = extra.checked_add(std::mem::size_of::<Value>())?;
541 cursor = message.payload.as_ref();
542 depth += 1;
543 }
544 Value::List(items) => {
545 if depth >= super::MAX_VALUE_DEPTH {
546 return None;
547 }
548 let slots = items.len().checked_mul(std::mem::size_of::<Value>())?;
549 extra = extra.checked_add(slots)?;
550 for item in items.iter() {
551 extra = extra.checked_add(walk(item, depth + 1)?)?;
552 }
553 return Some(extra);
554 }
555 Value::Map(entries) => {
556 if depth >= super::MAX_VALUE_DEPTH {
557 return None;
558 }
559 let slots = entries.len().checked_mul(std::mem::size_of::<Value>())?;
560 extra = extra.checked_add(slots)?;
561 for (key, value) in entries.iter() {
562 if let MapKey::Str(text) = key {
563 extra = extra.checked_add(text.len())?;
564 }
565 extra = extra.checked_add(walk(value, depth + 1)?)?;
566 }
567 return Some(extra);
568 }
569 Value::Str(s) => return extra.checked_add(s.len()),
570 Value::Bytes(b) => return extra.checked_add(b.len()),
571 Value::Unit
572 | Value::Bool(_)
573 | Value::Int(_)
574 | Value::Float(_)
575 | Value::Pid(_)
576 | Value::Cap(_) => return Some(extra),
577 }
578 }
579 }
580 walk(self, 0)
581 }
582
583 pub fn type_name(&self) -> &'static str {
584 match self {
585 Value::Unit => "unit",
586 Value::Bool(_) => "bool",
587 Value::Int(_) => "int",
588 Value::Float(_) => "float",
589 Value::Pid(_) => "pid",
590 Value::Message(_) => "message",
591 Value::Cap(_) => "cap",
592 Value::Str(_) => "str",
593 Value::Bytes(_) => "bytes",
594 Value::List(_) => "list",
595 Value::Map(_) => "map",
596 }
597 }
598}
599
600impl fmt::Display for Value {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 match self {
603 Value::Unit => write!(f, "()"),
604 Value::Bool(b) => write!(f, "{b}"),
605 Value::Int(i) => write!(f, "{i}"),
606 Value::Float(x) => write!(f, "{x}"),
607 Value::Pid(p) => write!(f, "flow#{p}"),
608 Value::Message(m) => write!(f, "{m}"),
609 Value::Cap(c) => write!(f, "{c}"),
610 Value::Str(s) => write!(f, "{s}"),
611 Value::Bytes(b) => write!(f, "bytes[{}]", b.len()),
612 Value::List(items) => {
613 write!(f, "[")?;
614 for (index, item) in items.iter().enumerate() {
615 if index > 0 {
616 write!(f, ", ")?;
617 }
618 write!(f, "{item}")?;
619 }
620 write!(f, "]")
621 }
622 Value::Map(entries) => {
623 write!(f, "{{")?;
624 for (index, (key, value)) in entries.iter().enumerate() {
625 if index > 0 {
626 write!(f, ", ")?;
627 }
628 match key {
629 MapKey::Int(n) => write!(f, "{n}")?,
630 MapKey::Str(text) => write!(f, "{text}")?,
631 }
632 write!(f, ": {value}")?;
633 }
634 write!(f, "}}")
635 }
636 }
637 }
638}
639
640impl From<i64> for Value {
641 fn from(v: i64) -> Self {
642 Value::Int(v)
643 }
644}
645impl From<i32> for Value {
646 fn from(v: i32) -> Self {
647 Value::Int(i64::from(v))
648 }
649}
650impl From<u64> for Value {
651 fn from(v: u64) -> Self {
654 let n = match i64::try_from(v) {
655 Ok(n) => n,
656 Err(_) => i64::MAX,
657 };
658 Value::Int(n)
659 }
660}
661impl From<bool> for Value {
662 fn from(v: bool) -> Self {
663 Value::Bool(v)
664 }
665}
666impl From<f64> for Value {
667 fn from(v: f64) -> Self {
668 Value::Float(v)
669 }
670}
671impl From<Message> for Value {
672 fn from(m: Message) -> Self {
673 Value::Message(m)
674 }
675}
676impl From<CapId> for Value {
677 fn from(c: CapId) -> Self {
678 Value::Cap(c)
679 }
680}
681impl From<&str> for Value {
682 fn from(s: &str) -> Self {
683 Value::str(s)
684 }
685}
686impl From<String> for Value {
687 fn from(s: String) -> Self {
688 Value::Str(Arc::from(s))
689 }
690}
691impl From<&[u8]> for Value {
692 fn from(b: &[u8]) -> Self {
693 Value::bytes(b)
694 }
695}
696impl From<Vec<u8>> for Value {
697 fn from(b: Vec<u8>) -> Self {
698 Value::Bytes(Arc::from(b))
699 }
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705
706 #[test]
707 fn nesting_stops_at_the_decoder_ceiling() {
708 let mut value = Value::Int(1);
709 for _ in 0..16 {
710 value = Value::Message(Message::new(0, 1, 1, value));
711 }
712 assert!(value.within_nesting_limit());
713 value = Value::Message(Message::new(0, 1, 1, value));
714 assert!(!value.within_nesting_limit());
715 }
716
717 #[test]
718 fn message_is_truthy_and_round_trips_helpers() {
719 let m = Message::new(7, 99, 10, 1u64);
720 let v = Value::Message(m.clone());
721 assert!(v.is_truthy());
722 assert_eq!(v.as_message(), Some(&m));
723 assert_eq!(v.type_name(), "message");
724 assert_eq!(m.payload.as_ref(), &Value::Int(1));
725 }
726
727 #[test]
728 fn authenticate_stamps_sender_and_reply_cap() {
729 let reply = CapId::from_raw(7);
730 let m = Message::new(999, 1, 2, 3u64).authenticate(42, reply);
731 assert_eq!(m.sender, 42);
732 assert_eq!(m.reply_cap, reply);
733 assert_eq!(m.request_id, 1);
734 }
735
736 #[test]
737 fn str_payload_is_charged_on_the_hop() {
738 let hop = Value::Message(Message::new(1, 1, 1, Value::str("hello")));
739 assert!(hop.heap_size() >= 5);
740 }
741
742 #[test]
743 fn nested_message_heap_counts_each_envelope_until_the_ceiling() {
744 let word = std::mem::size_of::<Value>();
745 let mut value = Value::str("hello");
746 for _ in 0..16 {
747 value = Value::Message(Message::new(0, 1, 1, value));
748 }
749 assert!(value.within_nesting_limit());
750 assert_eq!(value.heap_size(), 16 * word + 5);
751 assert_eq!(value.memory_size(), word + 16 * word + 5);
752 let blob = Value::Message(Message::new(0, 1, 1, Value::bytes(vec![0u8; 50_000])));
753 assert_eq!(blob.heap_size(), word + 50_000);
754 value = Value::Message(Message::new(0, 1, 1, value));
755 assert!(!value.within_nesting_limit());
756 assert_eq!(value.heap_size(), usize::MAX);
757 assert_eq!(value.memory_size(), usize::MAX);
758 }
759
760 #[test]
761 fn a_long_message_chain_sizes_without_recursing_off_the_stack() {
762 let mut value = Value::Int(1);
763 for _ in 0..10_000 {
764 value = Value::Message(Message::new(0, 1, 1, value));
765 }
766 assert!(!value.within_nesting_limit());
767 assert_eq!(value.heap_size(), usize::MAX);
768 assert_eq!(value.memory_size(), usize::MAX);
769 }
770
771 #[test]
772 fn cap_is_truthy() {
773 let cap = CapId::from_raw(3);
774 assert!(Value::Cap(cap).is_truthy());
775 assert_eq!(Value::Cap(cap).as_cap(), Some(cap));
776 }
777
778 #[test]
779 fn str_and_bytes_helpers() {
780 let s = Value::str("hi");
781 assert_eq!(s.as_str(), Some("hi"));
782 assert_eq!(s.type_name(), "str");
783 assert!(s.is_truthy());
784 assert!(!Value::str("").is_truthy());
785
786 let b = Value::bytes([1u8, 2, 3]);
787 assert_eq!(b.as_bytes(), Some(&[1, 2, 3][..]));
788 assert_eq!(b.type_name(), "bytes");
789 assert!(b.is_truthy());
790 assert!(!Value::bytes([]).is_truthy());
791
792 assert_eq!(s.as_bytes(), Some(b"hi".as_slice()));
793 }
794
795 #[test]
796 fn u64_above_i64_max_saturates() {
797 assert_eq!(Value::from(u64::MAX), Value::Int(i64::MAX));
798 assert_eq!(Value::from(4u64), Value::Int(4));
799 }
800
801 #[test]
802 fn str_eq_compares_content() {
803 assert_eq!(Value::str("a"), Value::from("a".to_owned()));
804 assert_ne!(Value::str("a"), Value::str("b"));
805 assert_eq!(Value::bytes([9]), Value::from(vec![9u8]));
806 }
807}