cloudevents/event/
data.rs

1use serde_json::Value;
2use std::convert::TryFrom;
3use std::fmt;
4use std::fmt::Formatter;
5use std::str;
6
7/// Event [data attribute](https://github.com/cloudevents/spec/blob/master/spec.md#event-data) representation
8#[derive(PartialEq, Eq, Debug, Clone)]
9pub enum Data {
10    /// Event has a binary payload
11    Binary(Vec<u8>),
12    /// Event has a non-json string payload
13    String(String),
14    /// Event has a json payload
15    Json(serde_json::Value),
16}
17
18pub(crate) fn is_json_content_type(ct: &str) -> bool {
19    ct.starts_with("application/json") || ct.starts_with("text/json") || ct.ends_with("+json")
20}
21
22impl From<serde_json::Value> for Data {
23    fn from(value: Value) -> Self {
24        Data::Json(value)
25    }
26}
27
28impl From<Vec<u8>> for Data {
29    fn from(value: Vec<u8>) -> Self {
30        Data::Binary(value)
31    }
32}
33
34impl From<String> for Data {
35    fn from(value: String) -> Self {
36        Data::String(value)
37    }
38}
39
40impl From<&str> for Data {
41    fn from(value: &str) -> Self {
42        Data::String(String::from(value))
43    }
44}
45
46impl TryFrom<Data> for serde_json::Value {
47    type Error = serde_json::Error;
48
49    fn try_from(value: Data) -> Result<Self, Self::Error> {
50        match value {
51            Data::Binary(v) => Ok(serde_json::from_slice(&v)?),
52            Data::Json(v) => Ok(v),
53            Data::String(s) => Ok(serde_json::from_str(&s)?),
54        }
55    }
56}
57
58impl TryFrom<Data> for Vec<u8> {
59    type Error = serde_json::Error;
60
61    fn try_from(value: Data) -> Result<Self, Self::Error> {
62        match value {
63            Data::Binary(v) => Ok(v),
64            Data::Json(v) => Ok(serde_json::to_vec(&v)?),
65            Data::String(s) => Ok(s.into_bytes()),
66        }
67    }
68}
69
70impl TryFrom<Data> for String {
71    type Error = std::string::FromUtf8Error;
72
73    fn try_from(value: Data) -> Result<Self, Self::Error> {
74        match value {
75            Data::Binary(v) => Ok(String::from_utf8(v)?),
76            Data::Json(v) => Ok(v.to_string()),
77            Data::String(s) => Ok(s),
78        }
79    }
80}
81
82impl fmt::Display for Data {
83    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
84        match self {
85            Data::Binary(vec) => write!(f, "Binary data: {:?}", str::from_utf8(vec).unwrap()),
86            Data::String(s) => write!(f, "String data: {}", s),
87            Data::Json(j) => write!(f, "Json data: {}", j),
88        }
89    }
90}