1use std::str::FromStr;
2
3use dcbor::prelude::*;
4use url::Url;
5
6use crate::{Error, Result, tags};
7
8#[derive(Clone, Debug, Eq, PartialEq, Hash)]
20pub struct URI(String);
21
22impl URI {
23 pub fn new(uri: impl Into<String>) -> Result<Self> {
27 let uri = uri.into();
28 if Url::parse(&uri).is_ok() {
29 Ok(Self(uri))
30 } else {
31 Err(Error::invalid_data("URI", "invalid URI format"))
32 }
33 }
34}
35
36impl FromStr for URI {
38 type Err = Error;
39
40 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
41 Self::new(s)
42 }
43}
44
45impl AsRef<str> for URI {
47 fn as_ref(&self) -> &str { &self.0 }
48}
49
50impl AsRef<String> for URI {
52 fn as_ref(&self) -> &String { &self.0 }
53}
54
55impl AsRef<URI> for URI {
57 fn as_ref(&self) -> &URI { self }
58}
59
60impl CBORTagged for URI {
62 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_URI]) }
63}
64
65impl From<URI> for CBOR {
67 fn from(value: URI) -> Self { value.tagged_cbor() }
68}
69
70impl CBORTaggedEncodable for URI {
72 fn untagged_cbor(&self) -> CBOR { self.0.clone().into() }
73}
74
75impl TryFrom<CBOR> for URI {
77 type Error = dcbor::Error;
78
79 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
80 Self::from_tagged_cbor(cbor)
81 }
82}
83
84impl CBORTaggedDecodable for URI {
86 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
87 let uri: String = cbor.try_into()?;
88 Ok(Self::new(uri)?)
89 }
90}
91
92impl std::fmt::Display for URI {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 write!(f, "{}", self.0)
96 }
97}
98
99impl TryFrom<&str> for URI {
101 type Error = Error;
102
103 fn try_from(uri: &str) -> std::result::Result<Self, Self::Error> {
104 Self::new(uri)
105 }
106}
107
108impl TryFrom<String> for URI {
110 type Error = Error;
111
112 fn try_from(uri: String) -> std::result::Result<Self, Self::Error> {
113 Self::try_from(uri.as_str())
114 }
115}
116
117impl From<URI> for String {
119 fn from(uri: URI) -> Self { uri.0 }
120}
121
122impl From<&URI> for String {
124 fn from(uri: &URI) -> Self { uri.0.clone() }
125}