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