ruma_events/poll/unstable_start/
content_serde.rs
1use ruma_common::{serde::from_raw_json_value, EventId};
2use serde::{de, ser::SerializeStruct, Deserialize, Deserializer, Serialize};
3use serde_json::value::RawValue as RawJsonValue;
4
5use super::{
6 NewUnstablePollStartEventContent, NewUnstablePollStartEventContentWithoutRelation,
7 ReplacementUnstablePollStartEventContent, UnstablePollStartContentBlock,
8 UnstablePollStartEventContent,
9};
10use crate::room::message::{deserialize_relation, Relation};
11
12impl<'de> Deserialize<'de> for UnstablePollStartEventContent {
13 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
14 where
15 D: Deserializer<'de>,
16 {
17 let json = Box::<RawJsonValue>::deserialize(deserializer)?;
18
19 let mut deserializer = serde_json::Deserializer::from_str(json.get());
20 let relates_to: Option<Relation<NewUnstablePollStartEventContentWithoutRelation>> =
21 deserialize_relation(&mut deserializer).map_err(de::Error::custom)?;
22 let UnstablePollStartEventContentDeHelper { poll_start, text } =
23 from_raw_json_value(&json)?;
24
25 let c = match relates_to {
26 Some(Relation::Replacement(relates_to)) => {
27 ReplacementUnstablePollStartEventContent { poll_start, text, relates_to }.into()
28 }
29 rel => {
30 let poll_start = poll_start
31 .ok_or_else(|| de::Error::missing_field("org.matrix.msc3381.poll.start"))?;
32 let relates_to = rel
33 .map(|r| r.try_into().expect("Relation::Replacement has already been handled"));
34 NewUnstablePollStartEventContent { poll_start, text, relates_to }.into()
35 }
36 };
37
38 Ok(c)
39 }
40}
41
42#[derive(Debug, Deserialize)]
43struct UnstablePollStartEventContentDeHelper {
44 #[serde(rename = "org.matrix.msc3381.poll.start")]
45 poll_start: Option<UnstablePollStartContentBlock>,
46
47 #[serde(rename = "org.matrix.msc1767.text")]
48 text: Option<String>,
49}
50
51impl Serialize for ReplacementUnstablePollStartEventContent {
52 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
53 where
54 S: serde::Serializer,
55 {
56 let len = 2 + self.poll_start.is_some() as usize + self.text.is_some() as usize;
57
58 let mut state =
59 serializer.serialize_struct("ReplacementUnstablePollStartEventContent", len)?;
60
61 if let Some(poll_start) = &self.poll_start {
62 state.serialize_field("org.matrix.msc3381.poll.start", poll_start)?;
63 }
64 if let Some(text) = &self.text {
65 state.serialize_field("org.matrix.msc1767.text", text)?;
66 }
67
68 state.serialize_field("m.new_content", &self.relates_to.new_content)?;
69 state.serialize_field(
70 "m.relates_to",
71 &ReplacementRelatesTo { event_id: &self.relates_to.event_id },
72 )?;
73
74 state.end()
75 }
76}
77
78#[derive(Debug, Serialize)]
79#[serde(tag = "rel_type", rename = "m.replace")]
80struct ReplacementRelatesTo<'a> {
81 event_id: &'a EventId,
82}