Multi-Template Dispatch

AnyMessage reads the generated header layout and dispatches on the template ID. Prefer AnyMessage::try_decode at untrusted boundaries (returns Result). Bare AnyMessage::decode is the same implementation today; keep using try_* naming for consistency with the three-tier trust boundary.

#![allow(unused)]
fn main() {
pub fn demo_any_message() -> Result<(), Box<dyn std::error::Error>> {
    let mut hb = [0u8; HeartbeatEncoder::compute_length_with_header()];
    let hb_len = HeartbeatEncoder::compute_length_with_header();
    let nanos: u64 = 1_700_000_000_000_000_000;
    let _hb_len = HeartbeatEncoder::try_wrap_and_apply_header(&mut hb, 0)
        .unwrap()
        .fixed(&HeartbeatFixedFields {
            sequence: 1,
            timestamp: nanos,
        })
        .encoded_length_with_header();

    let note_body = b"hello AnyMessage";
    let note_len = NoteEncoder::compute_length_with_header(note_body.len());
    const NOTE_PAD: usize = 64;
    assert!(note_len <= NOTE_PAD);
    let mut note_storage = [0u8; NOTE_PAD];
    let note = &mut note_storage[..note_len];
    let note_written = NoteEncoder::try_wrap_and_apply_header(note, 0)?
        .fixed(&NoteFixedFields { note_id: 99 })
        .body(note_body)?
        .encoded_length_with_header();
    assert_eq!(note_written, note_len);

    // Concatenate framed messages (each includes its own SBE header).
    let mut stream = Vec::new();
    stream.extend_from_slice(&hb[..hb_len]);
    stream.extend_from_slice(&note[..note_written]);

    let mut offset = 0usize;
    let mut saw_heartbeat = false;
    let mut saw_note = false;
    while offset < stream.len() {
        match AnyMessage::try_decode(&stream, offset)? {
            AnyMessage::Heartbeat(d) => {
                assert_eq!(d.sequence(), 1);
                offset += d.encoded_length_with_header()?;
                saw_heartbeat = true;
            }
            AnyMessage::Note(d) => {
                assert_eq!(d.note_id(), 99);
                let (body, complete) = d.into_body()?;
                assert_eq!(body, note_body);
                offset += complete.encoded_length() + NoteDecoder::HEADER_LENGTH;
                saw_note = true;
            }
            AnyMessage::Car(_) => return Err("unexpected Car in this demo stream".into()),
            AnyMessage::Quote(_) => return Err("unexpected Quote in this demo stream".into()),
            AnyMessage::Unknown { .. } => {
                return Err("unexpected Unknown template".into());
            }
        }
    }
    assert!(saw_heartbeat && saw_note);
    Ok(())
}
}

(This code comes from the sbe-feature-tour sample crate.)