### Parallel N-Triples parsing from a file
Source: https://docs.rs/oxttl/latest/src/oxttl/ntriples.rs.html
This example demonstrates how to parse an N-Triples file in parallel. It splits the file into chunks and processes them concurrently using Rayon. Note: This example is marked `no_run` as it requires file system operations.
```rust
use oxrdf::vocab::rdf;
use oxrdf::NamedNodeRef;
use oxttl::NTriplesParser;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
# let path = tempfile::NamedTempFile::new()?;
# std::fs::write(&path, r#
```
--------------------------------
### OxTTL Usage Example
Source: https://docs.rs/oxttl/latest/index.html
This example demonstrates how to use the TurtleParser to count the number of 'Person' entities in a Turtle file.
```APIDOC
## OxTTL Usage Example
### Description
This example demonstrates how to use the `TurtleParser` to count the number of 'Person' entities in a Turtle file.
### Method
N/A (Code Example)
### Endpoint
N/A (Code Example)
### Request Body
N/A (Code Example)
### Request Example
```rust
use oxrdf::{NamedNodeRef, vocab::rdf};
use oxttl::TurtleParser;
let file = b"@base .\n@prefix schema: .\n a schema:Person ;\n schema:name \"Foo\".\n a schema:Person ;\n schema:name \"Bar\".";
let schema_person = NamedNodeRef::new("http://schema.org/Person").unwrap();
let mut count = 0;
for triple in TurtleParser::new().for_reader(file.as_ref()) {
let triple = triple.unwrap();
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
### Response
N/A (Code Example)
### Response Example
N/A (Code Example)
```
--------------------------------
### Serialize N-Triples asynchronously
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.TokioAsyncWriterNTriplesSerializer.html
Example demonstrating how to initialize the serializer and write a triple to an asynchronous writer.
```rust
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut serializer = NTriplesSerializer::new().for_tokio_async_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?
)).await?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
```
--------------------------------
### Handle Triples Start in Rust N3 Parser
Source: https://docs.rs/oxttl/latest/src/oxttl/terse.rs.html
Begins the parsing of triples. It handles different starting tokens for triples, including '}', '[', and IRI references.
```rust
match token {
N3Token::Punctuation("}") => {
self.recognize_next(TokenOrLineJump::Token(token), context, results, errors)
// Early end
}
N3Token::Punctuation("[") => {
self.cur_subject.push(BlankNode::default().into());
self.stack
.push(TriGState::TriplesBlankNodePropertyListCurrent);
self
}
N3Token::IriRef(iri) => {
self.cur_subject.push(NamedNode::new_unchecked(iri).into());
self.stack.push(TriGState::PredicateObjectList);
self
}
N3Token::PrefixedName {
prefix,
local,
might_be_invalid_iri,
} => match resolve_local_name(
prefix,
&local,
```
--------------------------------
### Serialize a quad using LowLevelTriGSerializer
Source: https://docs.rs/oxttl/latest/oxttl/trig/struct.LowLevelTriGSerializer.html
Example demonstrating how to initialize a serializer, write a quad, and finalize the output buffer.
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
let mut buf = Vec::new();
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.low_level();
serializer.serialize_quad(
QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
),
&mut buf,
)?;
serializer.finish(&mut buf)?;
assert_eq!(
b"@prefix schema: .\n {\n\t a schema:Person .\n}\n",
buf.as_slice()
);
```
--------------------------------
### Handle N3 Document Start
Source: https://docs.rs/oxttl/latest/src/oxttl/n3.rs.html
Manages the initial state of an N3 document, expecting directives or triples. It pushes subsequent states onto the stack based on the first token encountered.
```rust
N3State::N3Doc => {
self.stack.push(N3State::N3Doc);
match token {
N3Token::PlainKeyword(k) if k.eq_ignore_ascii_case("base") => {
self.stack.push(N3State::BaseExpectIri);
return self;
}
N3Token::PlainKeyword(k) if k.eq_ignore_ascii_case("prefix") => {
self.stack.push(N3State::PrefixExpectPrefix);
return self;
}
N3Token::LangTag {
language: "prefix", #[cfg(
feature = "rdf-12"
)] direction: None
} => {
self.stack.push(N3State::N3DocExpectDot);
self.stack.push(N3State::PrefixExpectPrefix);
return self;
}
N3Token::LangTag {
language: "base", #[cfg(
feature = "rdf-12"
)] direction: None
} => {
self.stack.push(N3State::N3DocExpectDot);
self.stack.push(N3State::BaseExpectIri);
return self;
}
_ => {
self.stack.push(N3State::N3DocExpectDot);
self.stack.push(N3State::Triples);
}
}
}
```
--------------------------------
### Serialize a triple with LowLevelNTriplesSerializer
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.LowLevelNTriplesSerializer.html
Example demonstrating how to use the low-level serializer to write a triple to a buffer.
```rust
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut buf = Vec::new();
let mut serializer = NTriplesSerializer::new().low_level();
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
), &mut buf)?;
assert_eq!(
b" .\n",
buf.as_slice()
);
```
--------------------------------
### Handle AnnotationBlock State (Annotation Start) in Rust
Source: https://docs.rs/oxttl/latest/src/oxttl/terse.rs.html
Processes the start of an annotation block using '{|', potentially creating a new reifier if not already specified. Requires the 'rdf-12' feature.
```rust
#[cfg(feature = "rdf-12")]
N3Token::Punctuation("{|") => {
let reifier = if with_reifier {
self.cur_reifier.last().unwrap().clone()
} else {
let reifier = BlankNode::default();
results.push(Quad::new(
reifier.clone(),
rdf::REIFIES,
Triple::new(
self.cur_subject.last().unwrap().clone(),
self.cur_predicate.last().unwrap().clone(),
self.cur_object.last().unwrap().clone(),
),
self.cur_graph.clone(),
));
reifier.into()
};
self.cur_subject.push(reifier);
self.stack.push(TriGState::AnnotationEnd { with_reifier });
}
```
--------------------------------
### Initialize N-Triples Serializer for Writer
Source: https://docs.rs/oxttl/latest/src/oxttl/ntriples.rs.html
Creates a new N-Triples serializer configured to write to a given `Write` implementation. The example shows setting up a serializer for a `Vec`.
```rust
pub fn for_writer(self, writer: W) -> WriterNTriplesSerializer {
WriterNTriplesSerializer {
writer,
low_level_writer: self.low_level(),
}
}
```
--------------------------------
### Serialize a Triple with WriterNTriplesSerializer
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.WriterNTriplesSerializer.html
Example of creating a serializer for a writer, serializing a triple, and finishing the process to retrieve the written data. Ensure necessary imports are present.
```rust
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut serializer = NTriplesSerializer::new().for_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?
))?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
```
--------------------------------
### TurtleParser Usage
Source: https://docs.rs/oxttl/latest/oxttl
Example demonstrating how to use the TurtleParser to iterate over triples in a Turtle-formatted byte stream.
```APIDOC
## TurtleParser Usage
### Description
This example shows how to initialize a `TurtleParser` and iterate through triples from a reader to count specific RDF types.
### Code Example
```rust
use oxrdf::{NamedNodeRef, vocab::rdf};
use oxttl::TurtleParser;
let file = b"@base .
@prefix schema: .
a schema:Person ;
schema:name \"Foo\" .
a schema:Person ;
schema:name \"Bar\" .";
let schema_person = NamedNodeRef::new(\"http://schema.org/Person\").unwrap();
let mut count = 0;
for triple in TurtleParser::new().for_reader(file.as_ref()) {
let triple = triple.unwrap();
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
```
--------------------------------
### Initialize TokioAsyncWriterTurtleSerializer
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.TokioAsyncWriterTurtleSerializer.html
Use TurtleSerializer::for_tokio_async_writer to build a serializer for asynchronous Tokio writers. This example demonstrates setting a prefix and serializing a single triple.
```rust
use oxrdf::vocab::rdf;
use oxrdf::{NamedNodeRef, TripleRef};
use oxttl::TurtleSerializer;
let mut serializer = TurtleSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.for_tokio_async_writer(Vec::new());
serializer
.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
))
.await?;
assert_eq!(
b"@prefix schema: .\n a schema:Person .\n",
serializer.finish().await?.as_slice()
);
```
--------------------------------
### Parse N-Quads asynchronously
Source: https://docs.rs/oxttl/latest/oxttl/nquads/struct.TokioAsyncReaderNQuadsParser.html
Example demonstrating how to count occurrences of a specific RDF type using the asynchronous parser.
```rust
use oxrdf::{NamedNodeRef, vocab::rdf};
use oxttl::NQuadsParser;
let file = r#" .
"Foo" .
.
"Bar" ."#;
let schema_person = NamedNodeRef::new("http://schema.org/Person")?;
let mut count = 0;
let mut parser = NQuadsParser::new().for_tokio_async_reader(file.as_bytes());
while let Some(triple) = parser.next().await {
let triple = triple?;
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
--------------------------------
### Initialize N-Triples Serializer for Async Writer
Source: https://docs.rs/oxttl/latest/src/oxttl/ntriples.rs.html
Creates a new N-Triples serializer for asynchronous writing to an `AsyncWrite` implementation. This example uses `tokio::io::AsyncWrite` and demonstrates serializing a triple asynchronously.
```rust
# #[tokio::main(flavor = "current_thread")]
# async fn main() -> Result<(), Box> {
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut serializer = NTriplesSerializer::new().for_tokio_async_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
)).await?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
# Ok(())
# }
```
--------------------------------
### Handle Wrapped Graph Start in Rust N3 Parser
Source: https://docs.rs/oxttl/latest/src/oxttl/terse.rs.html
Initiates the parsing of a wrapped graph structure. Expects an opening '{' token and transitions the parser state to handle triples within the graph.
```rust
if token == N3Token::Punctuation("{") {
self.stack.push(TriGState::WrappedGraphPossibleEnd);
self.stack.push(TriGState::Triples);
self
} else {
self.error(errors, "The GRAPH keyword should be followed by a graph name and a value in '{'")
}
```
--------------------------------
### Lexer Constructor
Source: https://docs.rs/oxttl/latest/src/oxttl/toolkit/lexer.rs.html
Creates a new `Lexer` instance. Requires a `TokenRecognizer`, input data buffer, buffer size limits, and optional line comment start sequence.
```rust
pub fn new(
parser: R,
data: B,
is_ending: bool,
min_buffer_size: usize,
max_buffer_size: usize,
line_comment_start: Option<&'static [u8]>,
) -> Self {
Self {
parser,
data,
position: Position {
line_start_buffer_offset: 0,
buffer_offset: 0,
global_offset: 0,
global_line: 0,
},
previous_position: Position {
line_start_buffer_offset: 0,
buffer_offset: 0,
global_offset: 0,
global_line: 0,
},
is_ending,
min_buffer_size,
max_buffer_size,
line_comment_start,
}
}
```
--------------------------------
### Handle N3Token::Punctuation('<<')
Source: https://docs.rs/oxttl/latest/src/oxttl/terse.rs.html
Handles the reified triple start token '<<'. This pushes multiple states onto the stack to manage the parsing of a reified triple, including its object, subject, and the reifier.
```rust
#[cfg(feature = "rdf-12")]
N3Token::Punctuation("<<") => {
self.stack.push(TriGState::ExpectDot);
self.stack.push(TriGState::MaybePredicateObjectList);
self.stack.push(TriGState::SubjectReifiedTripleEnd);
self.stack.push(TriGState::EndOfReifiedTripleBeforeReifier);
self.stack
.push(TriGState::ReifiedTripleObject { is_reified: true });
self.stack.push(TriGState::Verb);
self.stack
.push(TriGState::ReifiedTripleSubject { is_reified: true });
self
}
```
--------------------------------
### Serialize Triple to N-Triples
Source: https://docs.rs/oxttl/latest/src/oxttl/ntriples.rs.html
Serializes a single RDF triple into N-Triples format and writes it to the underlying writer. This example demonstrates serializing a person triple and finishing the serializer to get the output.
```rust
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut serializer = NTriplesSerializer::new().for_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
))?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
# Result::<_, Box>::Ok(())
```
--------------------------------
### TriGSerializer Initialization and Basic Usage
Source: https://docs.rs/oxttl/latest/oxttl/trig/struct.TriGSerializer.html
Demonstrates how to create a new TriGSerializer, set prefixes, and serialize a single quad.
```APIDOC
## TriGSerializer
A TriG serializer.
### Method
`new()`
### Description
Builds a new `TriGSerializer`.
### Request Example
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")?;
```
### Response Example
```rust
// Serializer instance is returned
```
```
--------------------------------
### Accessing prefixes during Turtle parsing
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.ReaderTurtleParser.html
Shows how to retrieve declared prefixes during the parsing of a Turtle file. Prefixes are initially empty and get populated as they are encountered in the file. This example uses `TurtleParser::new().for_reader()` and checks prefixes before and after reading a triple.
```rust
use oxttl::TurtleParser;
let file = r#"@base .
@prefix schema: .
a schema:Person ;
schema:name "Foo" ."#;
let mut parser = TurtleParser::new().for_reader(file.as_bytes());
assert!(parser.prefixes().collect::>().is_empty()); // No prefix at the beginning
parser.next().unwrap()?; // We read the first triple
assert_eq!(
parser.prefixes().collect::>(),
[("schema", "http://schema.org/")]
); // There are now prefixes
//
```
--------------------------------
### TurtleParser::new
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.TurtleParser.html
Initializes a new TurtleParser with default settings.
```APIDOC
## TurtleParser::new
### Description
Builds a new `TurtleParser`.
### Method
`new()`
### Endpoint
N/A (Struct method)
### Request Example
```rust
use oxttl::TurtleParser;
let parser = TurtleParser::new();
```
### Response
#### Success Response (Self)
- `Self` (TurtleParser) - A new instance of TurtleParser.
```
--------------------------------
### Get error cause (Deprecated)
Source: https://docs.rs/oxttl/latest/oxttl/struct.TurtleSyntaxError.html
Deprecated method for getting the error cause. Replaced by Error::source.
```rust
fn cause(&self) -> Option<&dyn Error>
```
--------------------------------
### Configure Base IRI and Prefixes
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.TurtleSerializer.html
Demonstrates setting a base IRI and multiple prefixes before serializing triples.
```rust
use oxrdf::vocab::rdf;
use oxrdf::{NamedNodeRef, TripleRef};
use oxttl::TurtleSerializer;
let mut serializer = TurtleSerializer::new()
.with_base_iri("http://example.com")?
.with_prefix("ex", "http://example.com/ns#")?
.for_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com/me")?,
rdf::TYPE,
NamedNodeRef::new("http://example.com/ns#Person")?,
))?;
assert_eq!(
b"@base .\n@prefix ex: .\n a ex:Person .\n",
serializer.finish()?.as_slice()
);
```
--------------------------------
### Get error description (Deprecated)
Source: https://docs.rs/oxttl/latest/oxttl/struct.TurtleSyntaxError.html
Deprecated method for getting an error description. Use the Display implementation or to_string() instead.
```rust
fn description(&self) -> &str
```
--------------------------------
### Initialize and Use WriterTriGSerializer
Source: https://docs.rs/oxttl/latest/oxttl/trig/struct.WriterTriGSerializer.html
Demonstrates how to initialize a WriterTriGSerializer with prefixes, serialize a quad, and finish the writing process. Ensure the writer implementation supports the `Write` trait.
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.for_writer(Vec::new());
serializer.serialize_quad(QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
))?;
assert_eq!(
b"@prefix schema: .\n {\n\t a schema:Person .\n}\n",
serializer.finish()?.as_slice()
);
```
--------------------------------
### Get Base IRI from N3 Slice
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.SliceN3Parser.html
Shows how to get the base IRI during N3 parsing from a byte slice. The base IRI is initially None and set once encountered in the input.
```rust
use oxttl::N3Parser;
let file = r"@base .
@prefix schema: .
a schema:Person ;
schema:name \"Foo\" .";
let mut parser = N3Parser::new().for_slice(file);
assert!(parser.base_iri().is_none()); // No base at the beginning because none has been given to the parser.
parser.next().unwrap()?; // We read the first triple
assert_eq!(parser.base_iri(), Some("http://example.com/")); // There is now a base IRI.
```
--------------------------------
### Writing a Turtle File with LowLevelTurtleSerializer
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.LowLevelTurtleSerializer.html
Demonstrates how to use the LowLevelTurtleSerializer to write a Turtle file. This involves setting up prefixes, serializing triples, and finishing the output. Ensure necessary imports are included.
```rust
use oxrdf::vocab::rdf;
use oxrdf::{NamedNodeRef, TripleRef};
use oxttl::TurtleSerializer;
let mut buf = Vec::new();
let mut serializer = TurtleSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.low_level();
serializer.serialize_triple(
TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
),
&mut buf,
)?;
serializer.finish(&mut buf)?;
assert_eq!(
b"@prefix schema: .\n a schema:Person .\n",
buf.as_slice()
);
```
--------------------------------
### VZip Implementation
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.TurtleParser.html
Documentation for the `VZip` implementation and its `vzip` method.
```APIDOC
## impl VZip for T
### Description
Implementation of `VZip` for type `T` where `V` implements `MultiLane`.
### Method
Implicit (associated function)
### Endpoint
N/A (Implementation detail)
### fn vzip(self) -> V
#### Description
Creates a `VZip` structure.
#### Method
Implicit (associated function)
#### Parameters
- **self** (VZip) - The value to create a `VZip` from.
#### Response
- **V** - The resulting `VZip` structure.
```
--------------------------------
### Initialize and Use TokioAsyncWriterTriGSerializer
Source: https://docs.rs/oxttl/latest/oxttl/trig/struct.TokioAsyncWriterTriGSerializer.html
Demonstrates how to initialize a TriGSerializer for Tokio's async writer, set prefixes, serialize a quad, and finish the process to retrieve the underlying writer. Requires the `async-tokio` feature.
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.for_tokio_async_writer(Vec::new());
serializer
.serialize_quad(QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
))
.await?;
assert_eq!(
b"@prefix schema: .\n {\n\t a schema:Person .\n}\n",
serializer.finish().await?.as_slice()
);
```
--------------------------------
### Get error message
Source: https://docs.rs/oxttl/latest/oxttl/struct.TurtleSyntaxError.html
Retrieves the error message as a string slice.
```rust
pub fn message(&self) -> &str
```
--------------------------------
### Recognize Variable
Source: https://docs.rs/oxttl/latest/src/oxttl/lexer.rs.html
Parses a variable starting with '?' followed by a local name.
```rust
fn recognize_variable<'a>(
&self,
data: &'a [u8],
is_ending: bool,
) -> Option<(usize, Result, TokenRecognizerError>)> {
// [36] QUICK_VAR_NAME ::= "?" PN_LOCAL
let (consumed, result) = self.recognize_optional_pn_local(&data[1..], is_ending)?;
Some((
consumed + 1,
result.and_then(|(name, _)| {
if name.is_empty() {
Err((0..consumed, "A variable name is not allowed to be empty").into())
} else {
Ok(N3Token::Variable(name))
}
}),
))
}
```
--------------------------------
### TryFrom and TryInto Implementations
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.SliceN3Parser.html
Details conversion traits that may fail.
```APIDOC
### impl TryFrom for T
where U: Into,
#### type Error = Infallible
The type returned in the event of a conversion error.
#### fn try_from(value: U) -> Result>::Error>
Performs the conversion.
### impl TryInto for T
where U: TryFrom,
#### type Error = >::Error
The type returned in the event of a conversion error.
#### fn try_into(self) -> Result>::Error>
Performs the conversion.
```
--------------------------------
### GET /base_iri
Source: https://docs.rs/oxttl/latest/src/oxttl/n3.rs.html
Retrieves the base IRI currently configured in the parser context.
```APIDOC
## GET /base_iri
### Description
Returns the base IRI associated with the current parser context if it has been set.
### Method
GET
### Response
#### Success Response (200)
- **base_iri** (Option) - The base IRI string if present, otherwise null.
```
--------------------------------
### Generic Any Implementation
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.N3Quad.html
Gets the TypeId of a value, useful for dynamic type checking.
```rust
fn type_id(&self) -> TypeId
```
--------------------------------
### Serialize Quads with TriGSerializer
Source: https://docs.rs/oxttl/latest/src/oxttl/trig.rs.html
Demonstrates initializing a serializer, adding prefixes, and writing quads to a buffer.
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.for_writer(Vec::new());
serializer.serialize_quad(QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
))?;
assert_eq!(
b"@prefix schema: .\n {\n\t a schema:Person .\n}\n",
serializer.finish()?.as_slice()
);
# Result::<_, Box>::Ok(())
```
--------------------------------
### Initialize and Use WriterTurtleSerializer
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.WriterTurtleSerializer.html
Demonstrates how to initialize a TurtleSerializer for a writer, set prefixes, serialize a triple, and finish the process. Ensure prefixes are correctly defined and the writer implementation is suitable.
```rust
use oxrdf::vocab::rdf;
use oxrdf::{NamedNodeRef, TripleRef};
use oxttl::TurtleSerializer;
let mut serializer = TurtleSerializer::new()
.with_prefix("schema", "http://schema.org/")?
.for_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
))?;
assert_eq!(
b"@prefix schema: .\n a schema:Person .\n",
serializer.finish()?.as_slice()
);
```
--------------------------------
### TryInto Conversion
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.N3PrefixesIter.html
Documentation for the try_into conversion method.
```APIDOC
## fn try_into(self) -> Result>::Error>
### Description
Performs the conversion from one type to another, returning a Result to handle potential failure.
### Method
Function Call
### Parameters
- **self** (T) - Required - The source instance to convert.
```
--------------------------------
### Serialize Triple using NTriplesSerializer
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.NTriplesSerializer.html
Demonstrates how to create an NTriplesSerializer, write a triple to a writer, and finish the serialization. Requires the `oxrdf` crate.
```rust
use oxrdf::{NamedNodeRef, TripleRef};
use oxrdf::vocab::rdf;
use oxttl::NTriplesSerializer;
let mut serializer = NTriplesSerializer::new().for_writer(Vec::new());
serializer.serialize_triple(TripleRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
))?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
```
--------------------------------
### TriGSerializer with TokioAsyncWriter
Source: https://docs.rs/oxttl/latest/src/oxttl/trig.rs.html
Example of using TriGSerializer with Tokio's asynchronous writer to serialize RDF quads.
```APIDOC
## TriGSerializer with TokioAsyncWriter
### Description
This example demonstrates how to use the `TriGSerializer` with `TokioAsyncWriter` to asynchronously write RDF quads to a buffer.
### Method
`TriGSerializer::new().for_tokio_async_writer(Vec::new()).serialize_quad(...).await`
### Endpoint
N/A (In-memory serialization)
### Parameters
None directly for this method call, but the serializer can be configured with prefixes.
### Request Example
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::TriGSerializer;
// Assuming this is within an async function
let mut serializer = TriGSerializer::new()
.with_prefix("schema", "http://schema.org/")? // Configure a prefix
.for_tokio_async_writer(Vec::new()); // Initialize for async writing
serializer
.serialize_quad(QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
))
.await?; // Serialize a quad asynchronously
// Finish the serialization and get the writer
let result = serializer.finish().await?;
```
### Response
#### Success Response (200)
Returns the underlying writer (e.g., `Vec`) containing the serialized TriG data.
#### Response Example
```rust
// The content of the Vec would be:
// @prefix schema: .
// {
// a schema:Person .
// }
```
```
--------------------------------
### ReaderTurtleParser Usage Example
Source: https://docs.rs/oxttl/latest/oxttl/turtle/struct.ReaderTurtleParser.html
Demonstrates how to use ReaderTurtleParser to count entities of a specific type in a Turtle file.
```APIDOC
## ReaderTurtleParser Usage Example
### Description
Parses a Turtle file from a `Read` implementation and demonstrates counting entities of a specific type.
### Method
`TurtleParser::for_reader`
### Endpoint
N/A (Struct method)
### Parameters
None
### Request Body
None
### Request Example
```rust
use oxrdf::NamedNodeRef;
use oxrdf::vocab::rdf;
use oxttl::TurtleParser;
let file = r"@base .
@prefix schema: .
a schema:Person ;
schema:name \"Foo\".
a schema:Person ;
schema:name \"Bar\".";
let schema_person = NamedNodeRef::new("http://schema.org/Person")?;
let mut count = 0;
for triple in TurtleParser::new().for_reader(file.as_bytes()) {
let triple = triple?;
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
### Response
#### Success Response (200)
N/A (This is a code example, not an API endpoint response)
#### Response Example
N/A
```
--------------------------------
### SliceN3Parser Usage Example
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.SliceN3Parser.html
Demonstrates how to use SliceN3Parser to count the number of people in an N3 formatted string.
```APIDOC
## SliceN3Parser Usage Example
### Description
Parses a N3 file from a byte slice and demonstrates counting specific entities.
### Method
`N3Parser::new().for_slice(file)`
### Parameters
None directly for `for_slice`, it takes the file content as input.
### Request Example
```rust
use oxrdf::NamedNode;
use oxrdf::vocab::rdf;
use oxttl::n3::{N3Parser, N3Term};
let file = r"@base .
@prefix schema: .
a schema:Person ;
schema:name \"Foo\".
a schema:Person ;
schema:name \"Bar\".";
let rdf_type = N3Term::NamedNode(rdf::TYPE.into_owned());
let schema_person = N3Term::NamedNode(NamedNode::new("http://schema.org/Person")?);
let mut count = 0;
for triple in N3Parser::new().for_slice(file) {
let triple = triple?;
if triple.predicate == rdf_type && triple.object == schema_person {
count += 1;
}
}
assert_eq!(2, count);
```
### Response
This example does not directly return a value but modifies a counter based on parsed triples.
```
--------------------------------
### N3Parser Configuration and Parsing
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.N3Parser.html
Methods for initializing and configuring the N3Parser, including setting base IRIs, prefixes, and enabling lenient parsing modes.
```APIDOC
## N3Parser Configuration
### Description
Methods to configure the behavior of the N3Parser before initiating the parsing process.
### Methods
- **new()**: Builds a new N3Parser instance.
- **lenient(self)**: Configures the parser to skip some validations for faster parsing.
- **with_base_iri(self, base_iri)**: Sets the base IRI for the parser.
- **with_prefix(self, prefix_name, prefix_iri)**: Adds a prefix mapping to the parser.
### Parsing Methods
- **for_reader(self, reader: R)**: Parses N3 data from a standard Read implementation.
- **for_tokio_async_reader(self, reader: R)**: Parses N3 data from an async reader (requires `async-tokio` feature).
- **for_slice(self, slice: &[u8])**: Parses N3 data directly from a byte slice.
```
--------------------------------
### Get lower-level error source
Source: https://docs.rs/oxttl/latest/oxttl/struct.TurtleSyntaxError.html
Implements the Error trait's source method to return the underlying error, if any.
```rust
fn source(&self) -> Option<&(dyn Error + 'static)>
```
--------------------------------
### Build and Use TokioAsyncWriterNQuadsSerializer
Source: https://docs.rs/oxttl/latest/oxttl/nquads/struct.TokioAsyncWriterNQuadsSerializer.html
Demonstrates how to build a TokioAsyncWriterNQuadsSerializer using `NQuadsSerializer::new().for_tokio_async_writer()` and then serialize a quad. Ensure the 'async-tokio' feature is enabled. The `finish()` method returns the underlying writer.
```rust
use oxrdf::{NamedNodeRef, QuadRef};
use oxrdf::vocab::rdf;
use oxttl::NQuadsSerializer;
let mut serializer = NQuadsSerializer::new().for_tokio_async_writer(Vec::new());
serializer.serialize_quad(QuadRef::new(
NamedNodeRef::new("http://example.com#me")?,
rdf::TYPE,
NamedNodeRef::new("http://schema.org/Person")?,
NamedNodeRef::new("http://example.com")?,
)).await?;
assert_eq!(
b" .\n",
serializer.finish().as_slice()
);
```
--------------------------------
### Count triples with TokioAsyncReaderNTriplesParser
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.TokioAsyncReaderNTriplesParser.html
Example demonstrating how to use the parser to count occurrences of a specific RDF type in an N-Triples stream.
```rust
use oxrdf::{NamedNodeRef, vocab::rdf};
use oxttl::NTriplesParser;
let file = r#" .
"Foo" .
.
"Bar" ."#;
let schema_person = NamedNodeRef::new("http://schema.org/Person")?;
let mut count = 0;
let mut parser = NTriplesParser::new().for_tokio_async_reader(file.as_bytes());
while let Some(triple) = parser.next().await {
let triple = triple?;
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
--------------------------------
### Initialize N3 Parser
Source: https://docs.rs/oxttl/latest/src/oxttl/n3.rs.html
Factory method to create a new N3 parser instance with provided configuration and context.
```rust
1387 pub fn new_parser(
1388 data: B,
1389 is_ending: bool,
1390 unchecked: bool,
1391 base_iri: Option>,
1392 prefixes: HashMap>,
1393 ) -> Parser {
1394 Parser::new(
1395 Lexer::new(
1396 N3Lexer::new(N3LexerMode::N3, unchecked),
1397 data,
1398 is_ending,
1399 MIN_BUFFER_SIZE,
1400 MAX_BUFFER_SIZE,
1401 Some(b"#"),
1402 ),
1403 Self {
1404 stack: vec![N3State::N3Doc],
1405 terms: Vec::new(),
1406 predicates: Vec::new(),
1407 contexts: Vec::new(),
1408 },
1409 N3RecognizerContext {
1410 lexer_options: N3LexerOptions { base_iri },
1411 prefixes,
1412 },
1413 )
1414 }
```
--------------------------------
### Get error location
Source: https://docs.rs/oxttl/latest/oxttl/struct.TurtleSyntaxError.html
Retrieves the byte range (Range) indicating the error's location within the input file.
```rust
pub fn location(&self) -> Range
```
--------------------------------
### TryFrom and TryInto Implementations
Source: https://docs.rs/oxttl/latest/oxttl/nquads/struct.NQuadsSerializer.html
Provides functionality for attempting type conversions with error handling.
```APIDOC
## impl TryFrom for T
### Description
Provides a way to attempt conversion from type U into type T, returning a Result.
### Method
N/A (Trait implementation)
### Endpoint
N/A
### Parameters
None
### Request Example
None
### Response
#### Associated Type Error
- **Error** (Infallible) - The type returned in the event of a conversion error. In this case, it's Infallible, meaning conversion is guaranteed to succeed if the `Into` bound is met.
### Response Example
None
```
```APIDOC
#### fn try_from(value: U) -> Result>::Error>
### Description
Performs the conversion from value of type U to type T.
### Method
N/A (Method within TryFrom trait)
### Endpoint
N/A
### Parameters
- **value** (U) - Required - The value to convert.
### Request Example
None
### Response
- **Result** - Ok(T) if conversion is successful, Err(Error) otherwise.
### Response Example
None
```
```APIDOC
## impl TryInto for T
### Description
Provides a way to attempt conversion from type T into type U, returning a Result.
### Method
N/A (Trait implementation)
### Endpoint
N/A
### Parameters
None
### Request Example
None
### Response
#### Associated Type Error
- **Error** (type) - The type returned in the event of a conversion error, determined by the `TryFrom` implementation for U.
### Response Example
None
```
```APIDOC
#### fn try_into(self) -> Result>::Error>
### Description
Performs the conversion from self (type T) to type U.
### Method
N/A (Method within TryInto trait)
### Endpoint
N/A
### Parameters
None
### Request Example
None
### Response
- **Result** - Ok(U) if conversion is successful, Err(Error) otherwise.
### Response Example
None
```
--------------------------------
### NTriplesParser - New
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.NTriplesParser.html
Initializes a new NTriplesParser.
```APIDOC
## NTriplesParser - New
### Description
Builds a new `NTriplesParser`.
### Method
`new()`
### Endpoint
N/A (Constructor)
### Request Example
```rust
use oxttl::NTriplesParser;
let parser = NTriplesParser::new();
```
### Response
#### Success Response (200)
- **Self** (NTriplesParser) - A new instance of NTriplesParser.
### Response Example
```json
{
"message": "NTriplesParser instance created"
}
```
```
--------------------------------
### ReaderNTriplesParser Usage Example
Source: https://docs.rs/oxttl/latest/oxttl/ntriples/struct.ReaderNTriplesParser.html
Demonstrates how to use ReaderNTriplesParser to count RDF triples of a specific type (Person) from a given N-Triples string.
```APIDOC
## ReaderNTriplesParser
### Description
Parses a N-Triples file from a `Read` implementation. Can be built using `NTriplesParser::for_reader`.
### Example
```rust
use oxrdf::{NamedNodeRef, vocab::rdf};
use oxttl::NTriplesParser;
let file = r#" .
"Foo" .
.
"Bar" ."#;
let schema_person = NamedNodeRef::new("http://schema.org/Person")?;
let mut count = 0;
for triple in NTriplesParser::new().for_reader(file.as_bytes()) {
let triple = triple?;
if triple.predicate == rdf::TYPE && triple.object == schema_person.into() {
count += 1;
}
}
assert_eq!(2, count);
```
```
--------------------------------
### Get Base IRI from Parser Context
Source: https://docs.rs/oxttl/latest/src/oxttl/n3.rs.html
Retrieves the base IRI from the parser's context. This is useful when the N3 document has a @base directive.
```rust
pub fn base_iri(&self) -> Option<&str> {
self.parser
.context
.lexer_options
.base_iri
.as_ref()
.map(Iri::as_str)
}
```
--------------------------------
### Get Prefixes with LowLevelN3Parser
Source: https://docs.rs/oxttl/latest/oxttl/n3/struct.LowLevelN3Parser.html
Shows how to retrieve IRI prefixes from an N3 string using the LowLevelN3Parser. Prefixes are initially empty and updated after parsing.
```rust
use oxttl::N3Parser;
let file = r"@base .
@prefix schema: .
a schema:Person ;
schema:name \"Foo\" .";
let mut parser = N3Parser::new().low_level();
parser.extend_from_slice(file.as_bytes());
assert_eq!(parser.prefixes().collect::>(), []); // No prefix at the beginning
parser.parse_next().unwrap()?; // We read the first triple
assert_eq!(
parser.prefixes().collect::>(),
[("schema", "http://schema.org/")]
); // There are now prefixes
//
```