tirea_contract/transport/
transcoder.rs

1//! Stream transcoder trait for protocol bridging.
2
3use std::marker::PhantomData;
4
5/// Stream transcoder: maps an input stream to an output stream.
6///
7/// Stateful, supports 1:N mapping and stream lifecycle hooks.
8/// Used for both directions (recv and send) of a protocol endpoint.
9pub trait Transcoder: Send {
10    /// Input item type consumed by this transcoder.
11    type Input: Send + 'static;
12    /// Output item type produced by this transcoder.
13    type Output: Send + 'static;
14
15    /// Events emitted before the input stream starts.
16    fn prologue(&mut self) -> Vec<Self::Output> {
17        Vec::new()
18    }
19
20    /// Map one input item to zero or more output items.
21    fn transcode(&mut self, item: &Self::Input) -> Vec<Self::Output>;
22
23    /// Events emitted after the input stream ends.
24    fn epilogue(&mut self) -> Vec<Self::Output> {
25        Vec::new()
26    }
27}
28
29/// Pass-through transcoder (no transformation).
30pub struct Identity<T>(PhantomData<T>);
31
32impl<T> Default for Identity<T> {
33    fn default() -> Self {
34        Self(PhantomData)
35    }
36}
37
38impl<T: Clone + Send + 'static> Transcoder for Identity<T> {
39    type Input = T;
40    type Output = T;
41
42    fn transcode(&mut self, item: &Self::Input) -> Vec<Self::Output> {
43        vec![item.clone()]
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn identity_passthrough() {
53        let mut t = Identity::<u32>::default();
54        assert_eq!(t.transcode(&42), vec![42]);
55    }
56}