cloudevents/message/
types.rs

1use crate::event::{ExtensionValue, UriReference};
2use base64::prelude::*;
3use chrono::{DateTime, Utc};
4use std::convert::TryInto;
5use std::fmt;
6use url::Url;
7
8/// Union type representing a [CloudEvent context attribute type](https://github.com/cloudevents/spec/blob/v1.0/spec.md#type-system).
9#[derive(PartialEq, Eq, Debug, Clone)]
10pub enum MessageAttributeValue {
11    Boolean(bool),
12    Integer(i64),
13    String(String),
14    Binary(Vec<u8>),
15    Uri(Url),
16    UriRef(UriReference),
17    DateTime(DateTime<Utc>),
18}
19
20impl TryInto<DateTime<Utc>> for MessageAttributeValue {
21    type Error = super::Error;
22
23    fn try_into(self) -> Result<DateTime<Utc>, Self::Error> {
24        match self {
25            MessageAttributeValue::DateTime(d) => Ok(d),
26            v => Ok(DateTime::<Utc>::from(DateTime::parse_from_rfc3339(
27                v.to_string().as_ref(),
28            )?)),
29        }
30    }
31}
32
33impl TryInto<Url> for MessageAttributeValue {
34    type Error = super::Error;
35
36    fn try_into(self) -> Result<Url, Self::Error> {
37        match self {
38            MessageAttributeValue::Uri(u) => Ok(u),
39            v => Ok(Url::parse(v.to_string().as_ref())?),
40        }
41    }
42}
43
44impl fmt::Display for MessageAttributeValue {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            MessageAttributeValue::Boolean(b) => write!(f, "{}", b),
48            MessageAttributeValue::Integer(i) => write!(f, "{}", i),
49            MessageAttributeValue::String(s) => write!(f, "{}", s),
50            MessageAttributeValue::Binary(v) => {
51                write!(f, "{}", BASE64_STANDARD.encode(v))
52            }
53            MessageAttributeValue::Uri(u) => write!(f, "{}", u),
54            MessageAttributeValue::UriRef(u) => write!(f, "{}", u),
55            MessageAttributeValue::DateTime(d) => {
56                write!(f, "{}", d.to_rfc3339())
57            }
58        }
59    }
60}
61
62impl From<ExtensionValue> for MessageAttributeValue {
63    fn from(that: ExtensionValue) -> Self {
64        match that {
65            ExtensionValue::String(s) => MessageAttributeValue::String(s),
66            ExtensionValue::Boolean(b) => MessageAttributeValue::Boolean(b),
67            ExtensionValue::Integer(i) => MessageAttributeValue::Integer(i),
68        }
69    }
70}
71
72impl From<MessageAttributeValue> for ExtensionValue {
73    fn from(that: MessageAttributeValue) -> Self {
74        match that {
75            MessageAttributeValue::Integer(i) => ExtensionValue::Integer(i),
76            MessageAttributeValue::Boolean(b) => ExtensionValue::Boolean(b),
77            v => ExtensionValue::String(v.to_string()),
78        }
79    }
80}