From 9652a464351b1b84cb77723afee9e703c97bfc50 Mon Sep 17 00:00:00 2001 From: Nicolas Musset Date: Mon, 23 Aug 2021 14:56:57 +0900 Subject: [PATCH] On-stack dynamic dispatch to avoid boxing --- src/main.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 788f17c..778395c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,9 +16,17 @@ fn main() -> Result<(), Box> { ) .get_matches(); - let reader: Box = match matches.value_of("input") { - Some(path) => Box::new(File::open(path)?), - None => Box::new(std::io::stdin()), + // Note: on-stack dynamic dispatch + let (mut file, mut stdin); + let reader: &mut dyn Read = match matches.value_of("input") { + Some(path) => { + file = File::open(path)?; + &mut file + } + None => { + stdin = std::io::stdin(); + &mut stdin + } }; let replaced_indent = matches.value_of("indentation").map(|value| { @@ -50,9 +58,17 @@ fn main() -> Result<(), Box> { output = windows_output_default_file.as_deref().or(output); - let writer: Box = match output { - Some(file) => Box::new(File::create(file)?), - None => Box::new(std::io::stdout()), + // Note: on-stack dynamic dispatch + let (mut file, mut stdout); + let writer: &mut dyn Write = match output { + Some(filename) => { + file = File::create(filename)?; + &mut file + }, + None => { + stdout = std::io::stdout(); + &mut stdout + }, }; let mut reader = BufReader::new(reader);