rdf-reader-jsonld 0.4.1

A JSON-LD file reader for RDF.rs knowledge graphs.
Documentation
// This is free and unencumbered software released into the public domain.

use crate::{JsonldReaderResult, JsonldTriple};
use futures::Stream;
use oxjsonld::{JsonLdParser, TokioAsyncReaderJsonLdParser};
use rdf_reader::StreamIter;
use tokio::{io::AsyncRead, runtime::Handle};

/// A reader for the JSON-LD text format.
pub struct JsonldReader<T: AsyncRead + Unpin + Send + 'static> {
    pub(crate) parser: TokioAsyncReaderJsonLdParser<T>,
    pub(crate) handle: Handle,
}

impl<T: AsyncRead + Unpin + Send + 'static> From<T> for JsonldReader<T> {
    /// Creates a JSON-LD reader for an `AsyncRead` source.
    fn from(input: T) -> Self {
        Self {
            parser: JsonLdParser::new().for_tokio_async_reader(input),
            handle: Handle::current(),
        }
    }
}

impl<T: AsyncRead + Unpin + Send + 'static> JsonldReader<T> {
    pub fn into_stream(mut self) -> impl Stream<Item = JsonldReaderResult<JsonldTriple>> {
        async_stream::stream! {
            while let Some(input) = self.parser.next().await {
                yield match input {
                    Ok(triple) => Ok(triple.into()),
                    Err(err) => Err(err),
                }
            }
        }
    }
}

impl<T: AsyncRead + Unpin + Send + 'static> IntoIterator for JsonldReader<T> {
    type Item = JsonldReaderResult<JsonldTriple>;
    type IntoIter = StreamIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        let handle = self.handle.clone();
        StreamIter::new(self.into_stream(), handle)
    }
}