From 6cf559798468d2512486361386ee2ba02ca68a79 Mon Sep 17 00:00:00 2001 From: Nordine Bittich Date: Sun, 1 Dec 2024 21:41:13 +0100 Subject: [PATCH] add prefixes api --- README.md | 10 +++++++++- src/turtle/turtle_doc.rs | 21 ++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1fb9fe0..2a6ce6b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # turtle parser + transforms a turtle string to a TurtleDoc ## Work in progress @@ -8,14 +9,16 @@ - Comments are filtered ## Todo + - error handling -- iri as described in the spec +- iri as described in the spec - cleanup - Jena like api ### Example #### Input + ```turtle @prefix foaf: . [ foaf:name "Alice" ] foaf:knows [ @@ -26,7 +29,9 @@ foaf:mbox ] . ``` + #### Output + ```turtle "Alice"^^. "Bob"^^. @@ -39,11 +44,14 @@ ``` #### Input + ```turtle @prefix : . :a :b ( "apple" "banana" ) . ``` + #### Output + ```turtle "apple"^^. "banana"^^. diff --git a/src/turtle/turtle_doc.rs b/src/turtle/turtle_doc.rs index 2e25f21..3fe7d00 100644 --- a/src/turtle/turtle_doc.rs +++ b/src/turtle/turtle_doc.rs @@ -170,7 +170,26 @@ impl<'a> TurtleDoc<'a> { })?; (buf.as_str(), well_known_prefix).try_into() } - + pub fn add_prefixes( + &mut self, + prefixes: BTreeMap, + ) -> Result<(), TurtleDocError> { + let base = self.base.unwrap_or(""); + let mut prefixes: BTreeMap, Cow> = prefixes + .into_iter() + .map(|(k, v)| (Cow::Owned(k), Cow::Owned(v))) + .collect(); + for (_, prefix) in prefixes.iter_mut() { + let iri = IRI::try_from(prefix.as_ref()).map_err(|e| TurtleDocError { + message: e.to_string(), + })?; + if iri.is_relative() { + *prefix = Cow::Owned(format!("{base}{prefix}")); + } + } + self.prefixes.extend(prefixes); + Ok(()) + } pub fn add_statement(&mut self, subject: Node<'a>, predicate: Node<'a>, object: Node<'a>) { let stmt = Statement { subject,