Skip to content

Commit

Permalink
refactor: stack-allocated trait object for buffers (#16)
Browse files Browse the repository at this point in the history
Signed-off-by: Gabriel Nützi <gnuetzi@gmail.com>
  • Loading branch information
gabyx authored and supermaxiste committed Jun 24, 2024
1 parent 292eb63 commit 993facb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
5 changes: 3 additions & 2 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,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, config: &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 config = io::parse_config(config);
Expand Down

0 comments on commit 993facb

Please sign in to comment.