sophia_api/
parser.rs

1//! API for parsing RDF syntaxes.
2
3use crate::source::{QuadSource, TripleSource};
4
5/// A parser takes some data of type `T`,
6/// and returns a [`TripleSource`].
7pub trait TripleParser<T> {
8    /// The source produced by this parser
9    type Source: TripleSource;
10
11    /// Parses data into a triple source.
12    fn parse(&self, data: T) -> Self::Source;
13
14    /// Convenient shortcut method for parsing strings.
15    ///
16    /// It may not be available on some exotic parsers,
17    /// but will be automatically supported for parsers supporting any
18    /// [`BufRead`] or [`Read`].
19    ///
20    /// [`BufRead`]: std::io::BufRead
21    /// [`Read`]: std::io::Read
22    fn parse_str<'t>(&self, txt: &'t str) -> Self::Source
23    where
24        &'t str: IntoParsable<Target = T>,
25    {
26        self.parse(txt.into_parsable())
27    }
28}
29
30/// A parser takes some data of type `T`,
31/// and returns a [`QuadSource`].
32pub trait QuadParser<T> {
33    /// The source produced by this parser
34    type Source: QuadSource;
35
36    /// Parses data into a quad source.
37    fn parse(&self, data: T) -> Self::Source;
38
39    /// Convenient shortcut method for parsing strings.
40    ///
41    /// It may not be available on some exotic parsers,
42    /// but will be automatically supported for parsers supporting any
43    /// [`BufRead`] or [`Read`].
44    ///
45    /// [`BufRead`]: std::io::BufRead
46    /// [`Read`]: std::io::Read
47    fn parse_str<'t>(&self, txt: &'t str) -> Self::Source
48    where
49        &'t str: IntoParsable<Target = T>,
50    {
51        self.parse(txt.into_parsable())
52    }
53}
54
55/// Utility trait to support [`TripleParser::parse_str`] and [`QuadParser::parse_str`].
56pub trait IntoParsable {
57    /// The parsable type this type can be converted to.
58    type Target;
59    /// Convert into the parsable target type
60    fn into_parsable(self) -> Self::Target;
61}
62impl<'a> IntoParsable for &'a str {
63    type Target = &'a [u8];
64    fn into_parsable(self) -> Self::Target {
65        self.as_bytes()
66    }
67}
68
69/// Define convenience module-level functions for a parser implementation supporting BufRead.
70#[macro_export]
71macro_rules! def_mod_functions_for_bufread_parser {
72    ($parser_type: ident, $parser_trait: ident) => {
73        /// Convenience function for parsing a BufRead with the default parser.
74        pub fn parse_bufread<B: std::io::BufRead>(
75            bufread: B,
76        ) -> <$parser_type as $crate::parser::$parser_trait<B>>::Source {
77            $parser_type::default().parse(bufread)
78        }
79
80        /// Convenience function for parsing a str with the default parser.
81        pub fn parse_str(
82            txt: &str,
83        ) -> <$parser_type as $crate::parser::$parser_trait<&[u8]>>::Source {
84            $parser_type::default().parse_str(txt)
85        }
86    };
87}