JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Unified stack `GetValue` implementation

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨325f5af

⁨giterated-models/src/message.rs⁩ - ⁨1900⁩ bytes
Raw
1 use serde::Serialize;
2
3 use crate::{
4 object::{AnyObject, GiteratedObject},
5 operation::{AnyOperation, GiteratedOperation},
6 };
7 use std::fmt::Debug;
8
9 #[derive(Serialize)]
10 #[serde(bound(deserialize = "O: GiteratedObject, V: GiteratedOperation<O>"))]
11 pub struct GiteratedMessage<O: GiteratedObject, V: GiteratedOperation<O>> {
12 #[serde(with = "string")]
13 pub object: O,
14 pub operation: String,
15 pub payload: V,
16 }
17
18 #[allow(unused)]
19 mod string {
20 use std::fmt::Display;
21 use std::str::FromStr;
22
23 use serde::{de, Deserialize, Deserializer, Serializer};
24
25 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
26 where
27 T: Display,
28 S: Serializer,
29 {
30 serializer.collect_str(value)
31 }
32
33 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
34 where
35 T: FromStr,
36 T::Err: Display,
37 D: Deserializer<'de>,
38 {
39 String::deserialize(deserializer)?
40 .parse()
41 .map_err(de::Error::custom)
42 }
43 }
44
45 impl GiteratedMessage<AnyObject, AnyOperation> {
46 pub fn try_into<O: GiteratedObject, V: GiteratedOperation<O>>(
47 &self,
48 ) -> Result<GiteratedMessage<O, V>, ()> {
49 let object = O::from_object_str(&self.object.0).map_err(|_| ())?;
50 let payload = serde_json::from_slice::<V>(&self.payload.0).map_err(|_| ())?;
51
52 Ok(GiteratedMessage {
53 object,
54 operation: self.operation.clone(),
55 payload,
56 })
57 }
58 }
59
60 impl<V: GiteratedOperation<O> + Debug, O: GiteratedObject + Debug> Debug
61 for GiteratedMessage<O, V>
62 {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("GiteratedMessage")
65 .field("object", &self.object)
66 .field("operation", &self.operation)
67 .field("payload", &self.payload)
68 .finish()
69 }
70 }
71