Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Use stack-allocated trait object #16

Merged
merged 1 commit into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ use std::{
pub fn get_buffer(path: &Path) -> BufReader<File> {
return match File::open(&path) {
Ok(file) => BufReader::new(file),
Err(e) => panic!("Cannot open file '{:?}': '{}'.", path, e),
Err(e) => panic!("Cannot open file '{path:?}': '{e}'."),
};
}

// Parse RDF triples.
pub fn parse_ntriples(reader: Box<dyn BufRead>) -> NTriplesParser<Box<dyn BufRead>> {
// This function takes ownership of a generic type which implements `BufRead`.
pub fn parse_ntriples(reader: impl BufRead) -> NTriplesParser<impl BufRead> {
return NTriplesParser::new(reader);
}

Expand Down
13 changes: 9 additions & 4 deletions src/pass_second.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,15 @@ fn process_triple(triple: &Triple) -> Result<(), TurtleError> {

pub fn encrypt(log: &Logger, input: &Path, output: &Path, type_map_file: &Path) {
// Construct the buffer either from `stdio` or from an input file.
// This object is constructed on the heap: `Box` and is a `trait object` (a dynamic dispatch)
let buffer: Box<dyn BufRead> = match input.to_str().unwrap() {
"-" => Box::new(BufReader::new(std::io::stdin())),
_ => Box::new(io::get_buffer(input)),
//
// This object is constructed on the stack and is a `trait object`.
// The wide-pointer `buffer` will have a pointer to the vtable
// and pointer to data on the stack.
// Normally that would be done with `Box::new(std::io::stdin())` on the heap, but since the
// newest version in Rust that also works on the stack (life-time extensions).
let buffer: &mut dyn BufRead = match input.to_str().unwrap() {
"-" => &mut BufReader::new(std::io::stdin()),
_ => &mut io::get_buffer(input),
};

let mut triples = io::parse_ntriples(buffer);
Expand Down