ruma_events/
state_key.rs

1use serde::{
2    de::{
3        Deserialize, Deserializer, Unexpected, {self},
4    },
5    Serialize, Serializer,
6};
7
8/// A type that can be used as the `state_key` for event types where that field is always empty.
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
10#[allow(clippy::exhaustive_structs)]
11pub struct EmptyStateKey;
12
13impl AsRef<str> for EmptyStateKey {
14    fn as_ref(&self) -> &str {
15        ""
16    }
17}
18
19impl<'de> Deserialize<'de> for EmptyStateKey {
20    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
21    where
22        D: Deserializer<'de>,
23    {
24        let s = ruma_common::serde::deserialize_cow_str(deserializer)?;
25        if s.is_empty() {
26            Ok(EmptyStateKey)
27        } else {
28            Err(de::Error::invalid_value(Unexpected::Str(&s), &"an empty string"))
29        }
30    }
31}
32
33impl Serialize for EmptyStateKey {
34    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
35    where
36        S: Serializer,
37    {
38        serializer.serialize_str("")
39    }
40}