Skip to main content

try_decode

Function try_decode 

Source
pub fn try_decode<E: PluginEvent>(
    name: &str,
    payload: &[u8],
) -> Option<Result<E, DecodeError>>
Expand description

Subscriber-side helper: if name names event E, decode payload into it; otherwise None (the event is for a different subscriber). Folds the name-gate the guest would otherwise write by hand in on-event into one call.

The name match is exact (case-sensitive, no prefix matching); when it fails the payload is not looked at.

ยงExamples

use lattice_plugin_sdk::{PluginEvent, try_decode};
use serde::{Deserialize, Serialize};

/// A project finished indexing.
#[derive(Debug, PartialEq, Serialize, Deserialize, PluginEvent)]
#[event(name = "indexer.indexed")]
struct Indexed { files: u32 }

let payload = Indexed { files: 3 }.encode();
match try_decode::<Indexed>("indexer.indexed", &payload) {
    Some(Ok(ev)) => assert_eq!(ev.files, 3),
    Some(Err(e)) => panic!("our event, but a bad payload: {e}"),
    None => panic!("not our event"),
}
// Some other plugin's event: not decoded at all.
assert_eq!(try_decode::<Indexed>("git.hunks-changed", &payload), None);
// Our name, garbage bytes: a typed error.
assert!(matches!(try_decode::<Indexed>("indexer.indexed", &[0xc1]), Some(Err(_))));