cloudevents/event/
extensions.rs

1use serde::{Deserialize, Serialize, Serializer};
2use std::convert::From;
3use std::fmt;
4
5#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
6#[serde(untagged)]
7/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
8pub enum ExtensionValue {
9    /// Represents a [`String`] value.
10    String(String),
11    /// Represents a [`bool`] value.
12    Boolean(bool),
13    /// Represents an integer [`i64`] value.
14    Integer(i64),
15}
16
17impl From<&str> for ExtensionValue {
18    fn from(s: &str) -> Self {
19        ExtensionValue::String(String::from(s))
20    }
21}
22
23impl From<String> for ExtensionValue {
24    fn from(s: String) -> Self {
25        ExtensionValue::String(s)
26    }
27}
28
29impl From<bool> for ExtensionValue {
30    fn from(s: bool) -> Self {
31        ExtensionValue::Boolean(s)
32    }
33}
34
35impl From<i64> for ExtensionValue {
36    fn from(s: i64) -> Self {
37        ExtensionValue::Integer(s)
38    }
39}
40
41impl ExtensionValue {
42    pub fn from_string<S>(s: S) -> Self
43    where
44        S: Into<String>,
45    {
46        ExtensionValue::from(s.into())
47    }
48
49    pub fn from_i64<S>(s: S) -> Self
50    where
51        S: Into<i64>,
52    {
53        ExtensionValue::from(s.into())
54    }
55
56    pub fn from_bool<S>(s: S) -> Self
57    where
58        S: Into<bool>,
59    {
60        ExtensionValue::from(s.into())
61    }
62}
63
64impl fmt::Display for ExtensionValue {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            ExtensionValue::String(s) => f.write_str(s),
68            ExtensionValue::Boolean(b) => f.serialize_bool(*b),
69            ExtensionValue::Integer(i) => f.serialize_i64(*i),
70        }
71    }
72}