Skip to content

Commit

Permalink
feat(rdf): add nquads parsing to owned model
Browse files Browse the repository at this point in the history
  • Loading branch information
amimart committed Feb 5, 2024
1 parent c2acec0 commit 4b8a3e8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 11 deletions.
10 changes: 1 addition & 9 deletions packages/okp4-rdf/src/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use itertools::Itertools;
use rio_api::model::{GraphName, NamedNode, Quad, Subject, Term};
use std::slice::Iter;

#[derive(Clone)]
#[derive(Clone, Debug, PartialEq)]
pub struct Dataset<'a> {
quads: Vec<Quad<'a>>,
}
Expand Down Expand Up @@ -37,14 +37,6 @@ impl<'a> Dataset<'a> {
}
}

impl<'a> From<&'a [Quad<'a>]> for Dataset<'a> {
fn from(quads: &'a [Quad<'a>]) -> Self {
Self {
quads: quads.to_vec(),
}
}
}

#[derive(Copy, Clone)]
pub struct QuadPattern<'a> {
subject: Option<Subject<'a>>,
Expand Down
42 changes: 40 additions & 2 deletions packages/okp4-rdf/src/serde.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::owned_model::OwnedQuad;
use rio_api::formatter::TriplesFormatter;
use rio_api::model::{Quad, Triple};
use rio_api::parser::{QuadsParser, TriplesParser};
Expand All @@ -7,12 +8,26 @@ use rio_turtle::{
};
use rio_xml::{RdfXmlError, RdfXmlFormatter, RdfXmlParser};
use std::io::{self, BufRead};
use thiserror::Error;

pub struct TripleReader<R: BufRead> {
parser: TriplesParserKind<R>,
}

pub struct TripleWriter<W: std::io::Write> {
pub struct NQuadsReader<R: BufRead> {
parser: NQuadsParser<R>,
}

#[derive(Error, Debug)]
pub enum NQuadsReadError {
#[error("RDF Star notation not supported")]
RDFStarUnsupported,

#[error("Couldn't parse rdf: {0}")]
Parse(#[from] TurtleError),
}

pub struct TripleWriter<W: io::Write> {
writer: TriplesWriterKind<W>,
}

Expand All @@ -24,7 +39,7 @@ pub enum TriplesParserKind<R: BufRead> {
NQuads(NQuadsParser<R>),
}

pub enum TriplesWriterKind<W: std::io::Write> {
pub enum TriplesWriterKind<W: io::Write> {
NTriples(NTriplesFormatter<W>),
Turtle(TurtleFormatter<W>),
RdfXml(io::Result<RdfXmlFormatter<W>>),
Expand Down Expand Up @@ -76,6 +91,29 @@ impl<R: BufRead> TripleReader<R> {
}
}

impl<R: BufRead> NQuadsReader<R> {
pub fn new(src: R) -> Self {
NQuadsReader {
parser: NQuadsParser::new(src),
}
}

pub fn read_all<'a>(&mut self) -> Result<Vec<OwnedQuad>, NQuadsReadError> {
let mut quads = vec![];

self.parser
.parse_all(&mut |quad| -> Result<(), NQuadsReadError> {
quads.push(
quad.try_into()
.map_err(|_| NQuadsReadError::RDFStarUnsupported)?,
);
Ok(())
})?;

Ok(quads)
}
}

impl<W: io::Write> TripleWriter<W> {
pub fn new(format: &DataFormat, dst: W) -> Self {
TripleWriter {
Expand Down

0 comments on commit 4b8a3e8

Please sign in to comment.