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 252ee3c commit 0ceaf09
Showing 1 changed file with 9 additions and 4 deletions.
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

0 comments on commit 0ceaf09

Please sign in to comment.