Skip to main content

barter_integration/socket/
update.rs

1use serde::{Deserialize, Serialize};
2
3/// Socket lifecycle events wrapping stream items.
4#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
5pub enum SocketUpdate<Sink, T> {
6    /// Socket connected, providing the sink for sending data.
7    Connected(Sink),
8    /// Socket disconnected, reconnection in progress.
9    Reconnecting,
10    /// Data item received from the socket.
11    Item(T),
12}
13
14impl<Sink, T> From<T> for SocketUpdate<Sink, T> {
15    fn from(value: T) -> Self {
16        Self::Item(value)
17    }
18}
19
20impl<Sink, T> SocketUpdate<Sink, T> {
21    /// Maps the item using the provided function.
22    pub fn map<F, O>(self, op: F) -> SocketUpdate<Sink, O>
23    where
24        F: FnOnce(T) -> O,
25    {
26        match self {
27            SocketUpdate::Connected(sink) => SocketUpdate::Connected(sink),
28            SocketUpdate::Reconnecting => SocketUpdate::Reconnecting,
29            SocketUpdate::Item(item) => SocketUpdate::Item(op(item)),
30        }
31    }
32}
33
34impl<Sink, T, E> SocketUpdate<Sink, Result<T, E>> {
35    /// Maps the Ok value of a Result item.
36    pub fn map_ok<F, O>(self, op: F) -> SocketUpdate<Sink, Result<O, E>>
37    where
38        F: FnOnce(T) -> O,
39    {
40        match self {
41            SocketUpdate::Connected(sink) => SocketUpdate::Connected(sink),
42            SocketUpdate::Reconnecting => SocketUpdate::Reconnecting,
43            SocketUpdate::Item(result) => SocketUpdate::Item(result.map(op)),
44        }
45    }
46
47    /// Maps the Err value of a Result item.
48    pub fn map_err<F, O>(self, op: F) -> SocketUpdate<Sink, Result<T, O>>
49    where
50        F: FnOnce(E) -> O,
51    {
52        match self {
53            SocketUpdate::Connected(sink) => SocketUpdate::Connected(sink),
54            SocketUpdate::Reconnecting => SocketUpdate::Reconnecting,
55            SocketUpdate::Item(result) => SocketUpdate::Item(result.map_err(op)),
56        }
57    }
58}