1use std::{borrow::Cow, fmt, hash::Hash};
2
3use crate::{BlankId, BlankIdBuf, RdfDisplay};
4use iri_rs::{Iri, IriBuf};
5
6mod r#ref;
7pub use r#ref::*;
8
9mod cow;
10pub use cow::*;
11
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14#[cfg_attr(feature = "serde", serde(untagged))]
15pub enum Id {
16 BlankId(BlankIdBuf),
17 Iri(IriBuf),
18}
19
20impl Id {
21 pub const fn iri(iri: IriBuf) -> Self {
22 Self::Iri(iri)
23 }
24
25 pub const fn blank_id(blank_id: BlankIdBuf) -> Self {
26 Self::BlankId(blank_id)
27 }
28
29 pub const fn is_iri(&self) -> bool {
30 matches!(self, Self::Iri(_))
31 }
32
33 pub const fn is_blank_id(&self) -> bool {
34 matches!(self, Self::BlankId(_))
35 }
36
37 pub fn as_iri(&self) -> Option<Iri<&str>> {
38 match self {
39 Self::Iri(iri) => Some(iri.as_ref()),
40 Self::BlankId(_) => None,
41 }
42 }
43
44 pub fn as_blank_id(&self) -> Option<&BlankId> {
45 match self {
46 Self::BlankId(b) => Some(b),
47 Self::Iri(_) => None,
48 }
49 }
50
51 pub fn into_iri(self) -> Option<IriBuf> {
52 match self {
53 Self::Iri(iri) => Some(iri),
54 Self::BlankId(_) => None,
55 }
56 }
57
58 pub fn into_blank_id(self) -> Option<BlankIdBuf> {
59 match self {
60 Self::BlankId(b) => Some(b),
61 Self::Iri(_) => None,
62 }
63 }
64
65 pub fn as_ref(&self) -> IdRef<'_> {
66 match self {
67 Self::BlankId(blank_id) => IdRef::BlankId(blank_id),
68 Self::Iri(iri) => IdRef::Iri(iri.as_ref()),
69 }
70 }
71
72 pub fn as_cow(&self) -> CowId<'_> {
73 match self {
74 Self::BlankId(blank_id) => CowId::BlankId(Cow::Borrowed(blank_id)),
75 Self::Iri(iri) => CowId::Iri(Cow::Borrowed(iri)),
76 }
77 }
78
79 pub fn into_cow(self) -> CowId<'static> {
80 match self {
81 Self::BlankId(blank_id) => CowId::BlankId(Cow::Owned(blank_id)),
82 Self::Iri(iri) => CowId::Iri(Cow::Owned(iri)),
83 }
84 }
85
86 pub const fn into_owned(self) -> Self {
87 self
88 }
89}
90
91impl From<IriBuf> for Id {
92 fn from(value: IriBuf) -> Self {
93 Self::Iri(value)
94 }
95}
96
97impl From<BlankIdBuf> for Id {
98 fn from(value: BlankIdBuf) -> Self {
99 Self::BlankId(value)
100 }
101}
102
103impl Hash for Id {
104 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
105 match self {
106 Self::BlankId(id) => {
107 state.write_u8(0);
108 id.hash(state);
109 }
110 Self::Iri(iri) => {
111 state.write_u8(1);
112 iri.hash(state);
113 }
114 }
115 }
116}
117
118impl fmt::Display for Id {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 match self {
121 Self::BlankId(id) => id.fmt(f),
122 Self::Iri(iri) => iri.fmt(f),
123 }
124 }
125}
126
127impl RdfDisplay for Id {
128 fn rdf_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129 match self {
130 Self::BlankId(id) => id.rdf_fmt(f),
131 Self::Iri(iri) => iri.rdf_fmt(f),
132 }
133 }
134}