Files
tools/publish/src/rdf/conversion.rs
T

80 lines
2.3 KiB
Rust
Raw Normal View History

2026-06-23 21:55:52 -04:00
use oxigraph::model::{NamedNode, Quad, Term};
use oxigraph::model::vocab::{rdf, xsd};
2026-06-30 19:25:15 -04:00
use oxilangtag::LanguageTag;
2026-06-23 21:55:52 -04:00
2026-06-30 19:25:15 -04:00
pub enum LanguageCondition {
ExactMatch(LanguageTag<String>),
RelaxedMatch(LanguageTag<String>),
Untagged,
}
pub fn quad_into_term(quad: Quad) -> Term {
quad.object
}
pub fn english() -> LanguageCondition {
LanguageCondition::RelaxedMatch(LanguageTag::parse("en".to_string()).unwrap())
}
pub fn language_matches(term: &Term, condition: &LanguageCondition) -> bool {
if let Term::Literal(literal) = term {
let tag = literal.language()
.map(LanguageTag::parse_and_normalize)
.and_then(Result::ok);
match (tag, condition) {
(Some(language), LanguageCondition::ExactMatch(expectation)) |
(Some(language), LanguageCondition::RelaxedMatch(expectation)) => language == *expectation,
(None, LanguageCondition::RelaxedMatch(_)) => true,
(None, LanguageCondition::Untagged) => true,
_ => false,
}
} else {
false
}
2026-06-23 21:55:52 -04:00
}
2026-06-29 15:20:02 -04:00
pub fn term_to_named_node(term: &Term) -> Option<&NamedNode> {
2026-06-23 21:55:52 -04:00
if let Term::NamedNode(node) = term {
Some(node)
} else {
None
}
}
2026-06-30 19:25:15 -04:00
pub fn term_into_string(term: Term) -> Option<String> {
term_as_str(&term).map(String::from)
}
pub fn term_as_str(term: &Term) -> Option<&str> {
2026-06-23 21:55:52 -04:00
if let Term::Literal(literal) = term {
match literal.datatype() {
xsd::STRING | xsd::NORMALIZED_STRING | rdf::LANG_STRING | rdf::DIR_LANG_STRING => {
Some(literal.value())
}
_ => None,
}
} else {
None
}
}
2026-06-29 15:20:02 -04:00
pub fn term_to_boolean(term: &Term) -> Option<bool> {
2026-06-23 21:55:52 -04:00
if let Term::Literal(literal) = term {
if literal.datatype() == xsd::BOOLEAN {
literal.value().parse().ok()
} else {
None
}
} else {
None
}
}
2026-06-29 15:20:02 -04:00
pub fn term_to_u64(term: &Term) -> Option<u64> {
2026-06-23 21:55:52 -04:00
if let Term::Literal(literal) = term &&
2026-06-29 15:20:02 -04:00
(literal.datatype() == xsd::NON_NEGATIVE_INTEGER || literal.datatype() == xsd::INTEGER) {
2026-06-23 21:55:52 -04:00
let value: u64 = literal.value().parse().expect("Failed to parse u64 from ontology. It ought to be a non-negative integer.");
Some(value)
} else { None }
}