Skip to main content

clankerdiff_protocol/shared/
event.rs

1use super::{
2    ProtocolError, RemoteError,
3    message::{decode_json, encode_json},
4};
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use std::convert::Infallible;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub enum Event<T> {
10    Initialize {
11        protocol_version: u32,
12        repository_root: String,
13    },
14    Document(T),
15    RequestResult(Result<(), RemoteError>),
16    Health {
17        error: Option<RemoteError>,
18    },
19    Error(RemoteError),
20}
21
22impl<T> Event<T> {
23    pub fn map<U>(self, document: impl FnOnce(T) -> U) -> Event<U> {
24        let Ok(event) = self.try_map(|value| Ok::<_, Infallible>(document(value)));
25        event
26    }
27
28    pub fn try_map<U, E>(self, document: impl FnOnce(T) -> Result<U, E>) -> Result<Event<U>, E> {
29        Ok(match self {
30            Self::Document(value) => Event::Document(document(value)?),
31            Self::Initialize {
32                protocol_version,
33                repository_root,
34            } => Event::Initialize {
35                protocol_version,
36                repository_root,
37            },
38            Self::RequestResult(result) => Event::RequestResult(result),
39            Self::Health { error } => Event::Health { error },
40            Self::Error(error) => Event::Error(error),
41        })
42    }
43}
44
45impl<T: Serialize> Event<T> {
46    pub fn encode(&self) -> Result<String, ProtocolError> {
47        encode_json(self)
48    }
49}
50
51impl<T: DeserializeOwned> Event<T> {
52    pub fn decode(text: &str) -> Result<Self, ProtocolError> {
53        decode_json(text)
54    }
55}