rdf_model/alloc/
heap_term.rs1extern crate alloc;
4
5use crate::{Term, TermKind};
6use alloc::{
7 borrow::Cow,
8 string::{String, ToString},
9};
10
11#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
13#[cfg_attr(
14 feature = "borsh",
15 derive(borsh::BorshSerialize, borsh::BorshDeserialize)
16)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum HeapTerm {
19 Iri(String),
20 BNode(String),
21 Literal(String),
22 LiteralWithDatatype(String, String),
23 LiteralWithLanguage(String, String),
24}
25
26impl HeapTerm {
27 pub fn iri(value: impl AsRef<str>) -> Self {
28 Self::Iri(String::from(value.as_ref()))
29 }
30
31 pub fn bnode(id: impl AsRef<str>) -> Self {
32 Self::BNode(String::from(id.as_ref()))
33 }
34
35 pub fn literal(value: impl AsRef<str>) -> Self {
36 Self::Literal(String::from(value.as_ref()))
37 }
38
39 pub fn literal_with_language(value: impl AsRef<str>, language: impl AsRef<str>) -> Self {
40 Self::LiteralWithLanguage(
41 String::from(value.as_ref()),
42 String::from(language.as_ref()),
43 )
44 }
45
46 pub fn literal_with_datatype(value: impl AsRef<str>, datatype: impl AsRef<str>) -> Self {
47 Self::LiteralWithDatatype(
48 String::from(value.as_ref()),
49 String::from(datatype.as_ref()),
50 )
51 }
52}
53
54impl Term for HeapTerm {
55 fn kind(&self) -> TermKind {
56 match self {
57 Self::Iri(_) => TermKind::Iri,
58 Self::BNode(_) => TermKind::BNode,
59 Self::Literal(_)
60 | Self::LiteralWithLanguage(_, _)
61 | Self::LiteralWithDatatype(_, _) => TermKind::Literal,
62 }
63 }
64
65 fn as_str(&self) -> Cow<str> {
66 match self {
67 Self::Iri(s) => Cow::Borrowed(s),
68 Self::BNode(s) => Cow::Borrowed(s),
69 Self::Literal(s)
70 | Self::LiteralWithLanguage(s, _)
71 | Self::LiteralWithDatatype(s, _) => Cow::Borrowed(s),
72 }
73 }
74}
75
76impl From<&dyn Term> for HeapTerm {
77 fn from(term: &dyn Term) -> Self {
78 match term.kind() {
79 TermKind::Iri => Self::iri(term.as_str()),
80 TermKind::BNode => Self::bnode(term.as_str()),
81 TermKind::Literal => Self::literal(term.as_str()), }
83 }
84}
85
86impl From<&str> for HeapTerm {
87 fn from(value: &str) -> Self {
88 Self::literal(value)
89 }
90}
91
92impl From<String> for HeapTerm {
93 fn from(value: String) -> Self {
94 Self::literal(&value)
95 }
96}