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)]
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 for index in 0..entries.len() {
215 for earlier in 0..index {
216 if entries[index].0 == entries[earlier].0 {
217 return true;
218 }
219 }
220 }
221 false
222}
223
224impl Value {
225 #[inline]
231 pub fn wire_tag(&self) -> u8 {
232 match self {
233 Value::Unit => 0,
234 Value::Bool(_) => 1,
235 Value::Int(_) => 2,
236 Value::Float(_) => 3,
237 Value::Pid(_) => 4,
238 Value::Message(_) => 5,
239 Value::Cap(_) => 6,
240 Value::Str(_) => 7,
241 Value::Bytes(_) => 8,
242 Value::List(_) => 9,
243 Value::Map(_) => 10,
244 Value::Record(_) => 11,
245 }
246 }
247
248 pub fn map_get(&self, key: &MapKey) -> Option<&Value> {
250 match self {
251 Value::Map(entries) => entries
252 .iter()
253 .find(|(existing, _)| existing == key)
254 .map(|(_, value)| value),
255 _ => None,
256 }
257 }
258
259 pub fn try_map(entries: Vec<(MapKey, Value)>) -> Option<Self> {
262 if entries.len() > MAX_MAP_LEN || map_has_duplicate_key(&entries) {
263 return None;
264 }
265 let value = Value::Map(Arc::from(entries));
266 if value.within_nesting_limit() {
267 Some(value)
268 } else {
269 None
270 }
271 }
272
273 pub fn try_list(items: Vec<Value>) -> Option<Self> {
277 if items.len() > MAX_LIST_LEN {
278 return None;
279 }
280 let value = Value::List(Arc::from(items));
281 if value.within_nesting_limit() {
282 Some(value)
283 } else {
284 None
285 }
286 }
287
288 pub fn try_record(fields: Vec<Value>) -> Option<Self> {
291 if fields.len() > MAX_RECORD_LEN {
292 return None;
293 }
294 let value = Value::Record(Arc::from(fields));
295 if value.within_nesting_limit() {
296 Some(value)
297 } else {
298 None
299 }
300 }
301
302 #[inline]
304 pub fn str(s: impl AsRef<str>) -> Self {
305 Value::Str(Arc::from(s.as_ref()))
306 }
307
308 #[inline]
310 pub fn bytes(b: impl AsRef<[u8]>) -> Self {
311 Value::Bytes(Arc::from(b.as_ref()))
312 }
313
314 pub(crate) fn within_nesting_limit(&self) -> bool {
319 fn walk(value: &Value, depth: u32) -> bool {
320 if depth > super::MAX_VALUE_DEPTH {
321 return false;
322 }
323 match value {
324 Value::Message(message) => walk(message.payload.as_ref(), depth + 1),
325 Value::List(items) | Value::Record(items) => {
326 items.iter().all(|item| walk(item, depth + 1))
327 }
328 Value::Map(entries) => entries.iter().all(|(_, value)| walk(value, depth + 1)),
329 _ => true,
330 }
331 }
332 walk(self, 0)
333 }
334
335 pub(crate) fn map_caps<E: Clone>(
343 &self,
344 depth: u32,
345 too_nested: &E,
346 on_cap: &mut impl FnMut(CapId) -> Result<CapId, E>,
347 on_message: &mut impl FnMut(&mut Message) -> Result<(), E>,
348 ) -> Result<Value, E> {
349 if depth > super::MAX_VALUE_DEPTH {
350 return Err(too_nested.clone());
351 }
352 match self {
353 Value::Cap(id) if id.is_none() => Ok(Value::Cap(*id)),
354 Value::Cap(id) => Ok(Value::Cap(on_cap(*id)?)),
355 Value::Message(message) => {
356 let payload =
357 message
358 .payload
359 .map_caps(depth + 1, too_nested, on_cap, on_message)?;
360 let mut next = message.clone().with_payload(payload);
361 on_message(&mut next)?;
362 Ok(Value::Message(next))
363 }
364 Value::List(items) => {
365 let mut next = Vec::with_capacity(items.len());
366 for item in items.iter() {
367 next.push(item.map_caps(depth + 1, too_nested, on_cap, on_message)?);
368 }
369 Value::try_list(next).ok_or_else(|| too_nested.clone())
370 }
371 Value::Map(entries) => {
372 let mut next = Vec::with_capacity(entries.len());
373 for (key, value) in entries.iter() {
374 next.push((
375 key.clone(),
376 value.map_caps(depth + 1, too_nested, on_cap, on_message)?,
377 ));
378 }
379 Value::try_map(next).ok_or_else(|| too_nested.clone())
380 }
381 Value::Record(fields) => {
382 let mut next = Vec::with_capacity(fields.len());
383 for field in fields.iter() {
384 next.push(field.map_caps(depth + 1, too_nested, on_cap, on_message)?);
385 }
386 Value::try_record(next).ok_or_else(|| too_nested.clone())
387 }
388 other => Ok(other.clone()),
389 }
390 }
391
392 pub(crate) fn stamp_unset_envelopes(
399 &self,
400 depth: u32,
401 sender_if_unset: u64,
402 mint: &mut impl FnMut() -> u64,
403 ) -> Option<Value> {
404 if depth > super::MAX_VALUE_DEPTH {
405 return None;
406 }
407 match self {
408 Value::Message(message) => {
409 let payload =
410 message
411 .payload
412 .stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?;
413 let mut next = message.clone().with_payload(payload);
414 if next.sender == 0 && sender_if_unset != 0 {
415 next.sender = sender_if_unset;
416 }
417 if next.request_id == 0 {
418 next.request_id = mint();
419 }
420 Some(Value::Message(next))
421 }
422 Value::List(items) => {
423 let mut next = Vec::with_capacity(items.len());
424 for item in items.iter() {
425 next.push(item.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?);
426 }
427 Value::try_list(next)
428 }
429 Value::Map(entries) => {
430 let mut next = Vec::with_capacity(entries.len());
431 for (key, value) in entries.iter() {
432 next.push((
433 key.clone(),
434 value.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?,
435 ));
436 }
437 Value::try_map(next)
438 }
439 Value::Record(fields) => {
440 let mut next = Vec::with_capacity(fields.len());
441 for field in fields.iter() {
442 next.push(field.stamp_unset_envelopes(depth + 1, sender_if_unset, mint)?);
443 }
444 Value::try_record(next)
445 }
446 other => Some(other.clone()),
447 }
448 }
449
450 pub(crate) fn contains_live_cap(&self, depth: u32) -> bool {
456 if depth > super::MAX_VALUE_DEPTH {
457 return true;
458 }
459 match self {
460 Value::Cap(id) => !id.is_none(),
461 Value::Message(message) => {
462 !message.reply_cap.is_none() || message.payload.contains_live_cap(depth + 1)
463 }
464 Value::List(items) | Value::Record(items) => {
465 items.iter().any(|item| item.contains_live_cap(depth + 1))
466 }
467 Value::Map(entries) => entries
468 .iter()
469 .any(|(_, value)| value.contains_live_cap(depth + 1)),
470 _ => false,
471 }
472 }
473
474 #[inline]
478 pub fn is_truthy(&self) -> bool {
479 match self {
480 Value::Unit | Value::Bool(false) | Value::Int(0) => false,
481 Value::Str(s) if s.is_empty() => false,
482 Value::Bytes(b) if b.is_empty() => false,
483 Value::List(items) | Value::Record(items) if items.is_empty() => false,
484 Value::Map(entries) if entries.is_empty() => false,
485 _ => true,
486 }
487 }
488
489 #[inline]
495 pub fn as_int(&self) -> Option<i64> {
496 match self {
497 Value::Int(i) => Some(*i),
498 Value::Bool(b) => Some(*b as i64),
499 _ => None,
500 }
501 }
502
503 #[inline]
504 pub fn as_pid(&self) -> Option<u64> {
505 match self {
506 Value::Pid(p) => Some(*p),
507 _ => None,
508 }
509 }
510
511 #[inline]
512 pub fn as_cap(&self) -> Option<CapId> {
513 match self {
514 Value::Cap(c) => Some(*c),
515 _ => None,
516 }
517 }
518
519 #[inline]
520 pub fn as_message(&self) -> Option<&Message> {
521 match self {
522 Value::Message(m) => Some(m),
523 _ => None,
524 }
525 }
526
527 #[inline]
528 pub fn as_str(&self) -> Option<&str> {
529 match self {
530 Value::Str(s) => Some(s.as_ref()),
531 _ => None,
532 }
533 }
534
535 #[inline]
536 pub fn as_bytes(&self) -> Option<&[u8]> {
537 match self {
538 Value::Bytes(b) => Some(b.as_ref()),
539 Value::Str(s) => Some(s.as_bytes()),
540 _ => None,
541 }
542 }
543
544 #[inline]
555 pub fn memory_size(&self) -> usize {
556 match self.heap_size_limited() {
557 Some(heap) => std::mem::size_of::<Self>().saturating_add(heap),
558 None => usize::MAX,
559 }
560 }
561
562 #[inline]
568 pub fn heap_size(&self) -> usize {
569 self.heap_size_limited().unwrap_or(usize::MAX)
570 }
571
572 fn heap_size_limited(&self) -> Option<usize> {
578 fn walk(value: &Value, depth: u32) -> Option<usize> {
579 let mut extra = 0usize;
580 let mut cursor = value;
581 let mut depth = depth;
582 loop {
583 match cursor {
584 Value::Message(message) => {
585 if depth >= super::MAX_VALUE_DEPTH {
586 return None;
587 }
588 extra = extra.checked_add(std::mem::size_of::<Value>())?;
589 cursor = message.payload.as_ref();
590 depth += 1;
591 }
592 Value::List(items) | Value::Record(items) => {
593 if depth >= super::MAX_VALUE_DEPTH {
594 return None;
595 }
596 let slots = items.len().checked_mul(std::mem::size_of::<Value>())?;
597 extra = extra.checked_add(slots)?;
598 for item in items.iter() {
599 extra = extra.checked_add(walk(item, depth + 1)?)?;
600 }
601 return Some(extra);
602 }
603 Value::Map(entries) => {
604 if depth >= super::MAX_VALUE_DEPTH {
605 return None;
606 }
607 let slots = entries.len().checked_mul(std::mem::size_of::<Value>())?;
608 extra = extra.checked_add(slots)?;
609 for (key, value) in entries.iter() {
610 if let MapKey::Str(text) = key {
611 extra = extra.checked_add(text.len())?;
612 }
613 extra = extra.checked_add(walk(value, depth + 1)?)?;
614 }
615 return Some(extra);
616 }
617 Value::Str(s) => return extra.checked_add(s.len()),
618 Value::Bytes(b) => return extra.checked_add(b.len()),
619 Value::Unit
620 | Value::Bool(_)
621 | Value::Int(_)
622 | Value::Float(_)
623 | Value::Pid(_)
624 | Value::Cap(_) => return Some(extra),
625 }
626 }
627 }
628 walk(self, 0)
629 }
630
631 pub fn type_name(&self) -> &'static str {
632 match self {
633 Value::Unit => "unit",
634 Value::Bool(_) => "bool",
635 Value::Int(_) => "int",
636 Value::Float(_) => "float",
637 Value::Pid(_) => "pid",
638 Value::Message(_) => "message",
639 Value::Cap(_) => "cap",
640 Value::Str(_) => "str",
641 Value::Bytes(_) => "bytes",
642 Value::List(_) => "list",
643 Value::Map(_) => "map",
644 Value::Record(_) => "record",
645 }
646 }
647}
648
649impl fmt::Display for Value {
650 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
651 match self {
652 Value::Unit => write!(f, "()"),
653 Value::Bool(b) => write!(f, "{b}"),
654 Value::Int(i) => write!(f, "{i}"),
655 Value::Float(x) => write!(f, "{x}"),
656 Value::Pid(p) => write!(f, "flow#{p}"),
657 Value::Message(m) => write!(f, "{m}"),
658 Value::Cap(c) => write!(f, "{c}"),
659 Value::Str(s) => write!(f, "{s}"),
660 Value::Bytes(b) => write!(f, "bytes[{}]", b.len()),
661 Value::List(items) => {
662 write!(f, "[")?;
663 for (index, item) in items.iter().enumerate() {
664 if index > 0 {
665 write!(f, ", ")?;
666 }
667 write!(f, "{item}")?;
668 }
669 write!(f, "]")
670 }
671 Value::Map(entries) => {
672 write!(f, "{{")?;
673 for (index, (key, value)) in entries.iter().enumerate() {
674 if index > 0 {
675 write!(f, ", ")?;
676 }
677 match key {
678 MapKey::Int(n) => write!(f, "{n}")?,
679 MapKey::Str(text) => write!(f, "{text}")?,
680 }
681 write!(f, ": {value}")?;
682 }
683 write!(f, "}}")
684 }
685 Value::Record(fields) => {
686 write!(f, "rec(")?;
687 for (index, field) in fields.iter().enumerate() {
688 if index > 0 {
689 write!(f, ", ")?;
690 }
691 write!(f, "{field}")?;
692 }
693 write!(f, ")")
694 }
695 }
696 }
697}
698
699impl From<i64> for Value {
700 fn from(v: i64) -> Self {
701 Value::Int(v)
702 }
703}
704impl From<i32> for Value {
705 fn from(v: i32) -> Self {
706 Value::Int(i64::from(v))
707 }
708}
709impl From<u64> for Value {
710 fn from(v: u64) -> Self {
713 let n = match i64::try_from(v) {
714 Ok(n) => n,
715 Err(_) => i64::MAX,
716 };
717 Value::Int(n)
718 }
719}
720impl From<bool> for Value {
721 fn from(v: bool) -> Self {
722 Value::Bool(v)
723 }
724}
725impl From<f64> for Value {
726 fn from(v: f64) -> Self {
727 Value::Float(v)
728 }
729}
730impl From<Message> for Value {
731 fn from(m: Message) -> Self {
732 Value::Message(m)
733 }
734}
735impl From<CapId> for Value {
736 fn from(c: CapId) -> Self {
737 Value::Cap(c)
738 }
739}
740impl From<&str> for Value {
741 fn from(s: &str) -> Self {
742 Value::str(s)
743 }
744}
745impl From<String> for Value {
746 fn from(s: String) -> Self {
747 Value::Str(Arc::from(s))
748 }
749}
750impl From<&[u8]> for Value {
751 fn from(b: &[u8]) -> Self {
752 Value::bytes(b)
753 }
754}
755impl From<Vec<u8>> for Value {
756 fn from(b: Vec<u8>) -> Self {
757 Value::Bytes(Arc::from(b))
758 }
759}
760
761#[cfg(test)]
762mod tests {
763 use super::*;
764
765 #[test]
766 fn nesting_stops_at_the_decoder_ceiling() {
767 let mut value = Value::Int(1);
768 for _ in 0..16 {
769 value = Value::Message(Message::new(0, 1, 1, value));
770 }
771 assert!(value.within_nesting_limit());
772 value = Value::Message(Message::new(0, 1, 1, value));
773 assert!(!value.within_nesting_limit());
774 }
775
776 #[test]
777 fn message_is_truthy_and_round_trips_helpers() {
778 let m = Message::new(7, 99, 10, 1u64);
779 let v = Value::Message(m.clone());
780 assert!(v.is_truthy());
781 assert_eq!(v.as_message(), Some(&m));
782 assert_eq!(v.type_name(), "message");
783 assert_eq!(m.payload.as_ref(), &Value::Int(1));
784 }
785
786 #[test]
787 fn authenticate_stamps_sender_and_reply_cap() {
788 let reply = CapId::from_raw(7);
789 let m = Message::new(999, 1, 2, 3u64).authenticate(42, reply);
790 assert_eq!(m.sender, 42);
791 assert_eq!(m.reply_cap, reply);
792 assert_eq!(m.request_id, 1);
793 }
794
795 #[test]
796 fn str_payload_is_charged_on_the_hop() {
797 let hop = Value::Message(Message::new(1, 1, 1, Value::str("hello")));
798 assert!(hop.heap_size() >= 5);
799 }
800
801 #[test]
802 fn nested_message_heap_counts_each_envelope_until_the_ceiling() {
803 let word = std::mem::size_of::<Value>();
804 let mut value = Value::str("hello");
805 for _ in 0..16 {
806 value = Value::Message(Message::new(0, 1, 1, value));
807 }
808 assert!(value.within_nesting_limit());
809 assert_eq!(value.heap_size(), 16 * word + 5);
810 assert_eq!(value.memory_size(), word + 16 * word + 5);
811 let blob = Value::Message(Message::new(0, 1, 1, Value::bytes(vec![0u8; 50_000])));
812 assert_eq!(blob.heap_size(), word + 50_000);
813 value = Value::Message(Message::new(0, 1, 1, value));
814 assert!(!value.within_nesting_limit());
815 assert_eq!(value.heap_size(), usize::MAX);
816 assert_eq!(value.memory_size(), usize::MAX);
817 }
818
819 #[test]
820 fn a_long_message_chain_sizes_without_recursing_off_the_stack() {
821 let mut value = Value::Int(1);
822 for _ in 0..10_000 {
823 value = Value::Message(Message::new(0, 1, 1, value));
824 }
825 assert!(!value.within_nesting_limit());
826 assert_eq!(value.heap_size(), usize::MAX);
827 assert_eq!(value.memory_size(), usize::MAX);
828 }
829
830 #[test]
831 fn cap_is_truthy() {
832 let cap = CapId::from_raw(3);
833 assert!(Value::Cap(cap).is_truthy());
834 assert_eq!(Value::Cap(cap).as_cap(), Some(cap));
835 }
836
837 #[test]
838 fn str_and_bytes_helpers() {
839 let s = Value::str("hi");
840 assert_eq!(s.as_str(), Some("hi"));
841 assert_eq!(s.type_name(), "str");
842 assert!(s.is_truthy());
843 assert!(!Value::str("").is_truthy());
844
845 let b = Value::bytes([1u8, 2, 3]);
846 assert_eq!(b.as_bytes(), Some(&[1, 2, 3][..]));
847 assert_eq!(b.type_name(), "bytes");
848 assert!(b.is_truthy());
849 assert!(!Value::bytes([]).is_truthy());
850
851 assert_eq!(s.as_bytes(), Some(b"hi".as_slice()));
852 }
853
854 #[test]
855 fn u64_above_i64_max_saturates() {
856 assert_eq!(Value::from(u64::MAX), Value::Int(i64::MAX));
857 assert_eq!(Value::from(4u64), Value::Int(4));
858 }
859
860 #[test]
861 fn str_eq_compares_content() {
862 assert_eq!(Value::str("a"), Value::from("a".to_owned()));
863 assert_ne!(Value::str("a"), Value::str("b"));
864 assert_eq!(Value::bytes([9]), Value::from(vec![9u8]));
865 }
866}