Skip to main content

byteflow/bytecode/
pattern.rs

1//! Structural payload match for selective receive.
2//!
3//! [`super::Opcode::ReceiveMatchEq`] compares an `Int`.
4//! [`super::Opcode::ReceiveMatchValue`] compares the hop payload to any
5//! [`super::Value`] (`Str`, `Bytes`, `Bool`, `Float`, nested `Message`, …).
6//! Equality is [`PartialEq`]: `NaN` does not match `NaN`. This is not a
7//! guard language and not a tuple/map matcher.
8
9use super::value::Value;
10
11/// `true` when `hop` is a [`Value::Message`] with `tag` and a payload equal
12/// to `expected`.
13pub fn payload_matches(tag: u16, expected: &Value, hop: &Value) -> bool {
14    match hop.as_message() {
15        Some(message) => message.tag == tag && message.payload.as_ref() == expected,
16        None => false,
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn str_payload_skips_a_different_body() {
26        let hop_no = Value::Message(crate::Message::new(1, 1, 2, Value::str("no")));
27        let hop_yes = Value::Message(crate::Message::new(1, 2, 2, Value::str("xyz")));
28        let want = Value::str("xyz");
29        assert!(!payload_matches(2, &want, &hop_no));
30        assert!(payload_matches(2, &want, &hop_yes));
31        assert!(!payload_matches(9, &want, &hop_yes));
32    }
33
34    #[test]
35    fn receive_skips_a_different_string() -> Result<(), Box<dyn std::error::Error>> {
36        use crate::{FlowOutcome, Program, Runtime, Value};
37
38        let mut program = Program::new("pat");
39        let sender = program.function("sender", 1, |f| {
40            let parent = f.reg(0);
41            let bad = f.load_str("no");
42            let bad_msg = f.hop_fresh(2, bad);
43            f.send(parent, bad_msg);
44            let good = f.load_str("xyz");
45            let good_msg = f.hop_fresh(2, good);
46            f.send(parent, good_msg);
47            f.return_(good);
48        });
49        program.function("main", 0, |f| {
50            let me = f.self_cap();
51            let _child = f.spawn(sender, &[me]);
52            let tag = f.load_i32(2);
53            let want = f.load_str("xyz");
54            let got = f.receive_match_value(tag, want);
55            let out = f.hop_payload(got);
56            f.return_(out);
57        });
58        let rt = Runtime::with_natives(program.build(), crate::std_native_table())?;
59        let main = match rt.function_index("main") {
60            Some(index) => index,
61            None => return Err("missing main".into()),
62        };
63        let outcome = rt.spawn(main, &[])?.join();
64        rt.shutdown();
65        match outcome {
66            FlowOutcome::Completed(Value::Str(s)) if s.as_ref() == "xyz" => Ok(()),
67            other => Err(format!("pattern receive got {other:?}").into()),
68        }
69    }
70}