1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::event::{ExtensionValue, UriReference};
use chrono::{DateTime, Utc};
use std::convert::TryInto;
use std::fmt;
use url::Url;

/// Union type representing a [CloudEvent context attribute type](https://github.com/cloudevents/spec/blob/v1.0/spec.md#type-system).
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum MessageAttributeValue {
    Boolean(bool),
    Integer(i64),
    String(String),
    Binary(Vec<u8>),
    Uri(Url),
    UriRef(UriReference),
    DateTime(DateTime<Utc>),
}

impl TryInto<DateTime<Utc>> for MessageAttributeValue {
    type Error = super::Error;

    fn try_into(self) -> Result<DateTime<Utc>, Self::Error> {
        match self {
            MessageAttributeValue::DateTime(d) => Ok(d),
            v => Ok(DateTime::<Utc>::from(DateTime::parse_from_rfc3339(
                v.to_string().as_ref(),
            )?)),
        }
    }
}

impl TryInto<Url> for MessageAttributeValue {
    type Error = super::Error;

    fn try_into(self) -> Result<Url, Self::Error> {
        match self {
            MessageAttributeValue::Uri(u) => Ok(u),
            v => Ok(Url::parse(v.to_string().as_ref())?),
        }
    }
}

impl fmt::Display for MessageAttributeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MessageAttributeValue::Boolean(b) => write!(f, "{}", b),
            MessageAttributeValue::Integer(i) => write!(f, "{}", i),
            MessageAttributeValue::String(s) => write!(f, "{}", s),
            MessageAttributeValue::Binary(v) => write!(f, "{}", base64::encode(v)),
            MessageAttributeValue::Uri(u) => write!(f, "{}", u),
            MessageAttributeValue::UriRef(u) => write!(f, "{}", u),
            MessageAttributeValue::DateTime(d) => write!(f, "{}", d.to_rfc3339()),
        }
    }
}

impl From<ExtensionValue> for MessageAttributeValue {
    fn from(that: ExtensionValue) -> Self {
        match that {
            ExtensionValue::String(s) => MessageAttributeValue::String(s),
            ExtensionValue::Boolean(b) => MessageAttributeValue::Boolean(b),
            ExtensionValue::Integer(i) => MessageAttributeValue::Integer(i),
        }
    }
}

impl From<MessageAttributeValue> for ExtensionValue {
    fn from(that: MessageAttributeValue) -> Self {
        match that {
            MessageAttributeValue::Integer(i) => ExtensionValue::Integer(i),
            MessageAttributeValue::Boolean(b) => ExtensionValue::Boolean(b),
            v => ExtensionValue::String(v.to_string()),
        }
    }
}