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 = 256;
111
112pub const MAX_MAP_LEN: usize = 256;
114
115pub const MAX_RECORD_LEN: usize = 256;
117
118#[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
136fn 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 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#[derive(Clone, Debug, PartialEq)]
184pub enum Value {
185 Unit,
186 Bool(bool),
187 Int(i64),
188 Float(f64),
189 Pid(u64),
191 Message(Message),
193 Cap(CapId),
195 Str(Arc<str>),
197 Bytes(Arc<[u8]>),
199 List(Arc<[Value]>),
202 Map(Arc<[(MapKey, Value)]>),
205 Record(Arc<[Value]>),
208}
209
210pub(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 #[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 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 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 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 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 #[inline]
303 pub fn str(s: impl AsRef<str>) -> Self {
304 Value::Str(Arc::from(s.as_ref()))
305 }
306
307 #[inline]
309 pub fn bytes(b: impl AsRef<[u8]>) -> Self {
310 Value::Bytes(Arc::from(b.as_ref()))
311 }
312
313 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 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 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 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 #[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 #[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 #[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 #[inline]
567 pub fn heap_size(&self) -> usize {
568 self.heap_size_limited().unwrap_or(usize::MAX)
569 }
570
571 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 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}