hydro_lang/networking/
mod.rs

1//! Types for configuring network channels with serialization formats, transports, etc.
2
3use std::marker::PhantomData;
4
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7
8use crate::live_collections::stream::networking::{deserialize_bincode, serialize_bincode};
9
10#[sealed::sealed]
11trait SerKind<T: ?Sized> {
12    fn serialize_thunk(is_demux: bool) -> syn::Expr;
13
14    fn deserialize_thunk(tagged: Option<&syn::Type>) -> syn::Expr;
15}
16
17/// Serialize items using the [`bincode`] crate.
18pub enum Bincode {}
19
20#[sealed::sealed]
21impl<T: Serialize + DeserializeOwned> SerKind<T> for Bincode {
22    fn serialize_thunk(is_demux: bool) -> syn::Expr {
23        serialize_bincode::<T>(is_demux)
24    }
25
26    fn deserialize_thunk(tagged: Option<&syn::Type>) -> syn::Expr {
27        deserialize_bincode::<T>(tagged)
28    }
29}
30
31/// An unconfigured serialization backend.
32pub enum NoSer {}
33
34#[sealed::sealed]
35trait TransportKind {}
36
37/// Send items across a length-delimited TCP channel.
38pub enum Tcp {}
39
40#[sealed::sealed]
41impl TransportKind for Tcp {}
42
43/// A networking backend implementation that supports items of type `T`.
44#[sealed::sealed]
45pub trait NetworkFor<T: ?Sized> {
46    /// Generates serialization logic for sending `T`.
47    fn serialize_thunk(is_demux: bool) -> syn::Expr;
48
49    /// Generates deserialization logic for receiving `T`.
50    fn deserialize_thunk(tagged: Option<&syn::Type>) -> syn::Expr;
51}
52
53/// A network channel configuration with `T` as transport backend and `S` as the serialization
54/// backend.
55pub struct NetworkingConfig<Tr: ?Sized, S: ?Sized> {
56    _phantom: (PhantomData<Tr>, PhantomData<S>),
57}
58
59impl<Tr: ?Sized, S: ?Sized> NetworkingConfig<Tr, S> {
60    /// Configures the network channel to use [`bincode`] to serialize items.
61    pub const fn bincode(self) -> NetworkingConfig<Tr, Bincode> {
62        NetworkingConfig {
63            _phantom: (PhantomData, PhantomData),
64        }
65    }
66}
67
68#[sealed::sealed]
69impl<Tr: ?Sized, S: ?Sized, T: ?Sized> NetworkFor<T> for NetworkingConfig<Tr, S>
70where
71    Tr: TransportKind,
72    S: SerKind<T>,
73{
74    fn serialize_thunk(is_demux: bool) -> syn::Expr {
75        S::serialize_thunk(is_demux)
76    }
77
78    fn deserialize_thunk(tagged: Option<&syn::Type>) -> syn::Expr {
79        S::deserialize_thunk(tagged)
80    }
81}
82
83/// A network channel that uses length-delimited TCP for transport.
84pub const TCP: NetworkingConfig<Tcp, NoSer> = NetworkingConfig {
85    _phantom: (PhantomData, PhantomData),
86};