Skip to content

Commit c43308e

Browse files
committed
read entire file in at once, if it's small.
1 parent d507e52 commit c43308e

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

src/main.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use std::{
22
fmt::Write,
33
fs::{File, OpenOptions},
4-
io::{BufRead, BufReader, StdoutLock},
4+
io::{BufRead, BufReader, BufWriter, Read, StdoutLock},
55
};
66

7-
use anyhow::Context;
7+
use anyhow::{Context, Ok};
88
use clap::Parser;
99
use scoreman::{
1010
backend::errors::{
@@ -23,17 +23,23 @@ use crate::cli_args::Cli;
2323
// this
2424
//
2525
// Not very high priority, because it is not that slow.
26-
fn get_lines(input_path: &str) -> anyhow::Result<Vec<String>> {
27-
if input_path == "-" {
26+
fn get_lines(path: &str) -> anyhow::Result<Vec<String>> {
27+
if path == "-" {
2828
let mut f = std::io::stdin();
29-
let lines: Vec<String> = BufReader::new(&mut f).lines().map(|x| x.unwrap()).collect();
30-
Ok(lines)
31-
} else {
32-
let f =
33-
File::open(input_path).with_context(|| format!("Failed to open file {input_path}"))?;
29+
let lines = BufReader::new(&mut f).lines().map(|x| x.unwrap()).collect();
30+
return Ok(lines);
31+
}
3432

35-
let lines: Vec<String> = BufReader::new(&f).lines().map(|x| x.unwrap()).collect();
33+
let mut file = File::open(path).with_context(|| format!("Failed to open file {path}"))?;
34+
let size = file.metadata().map(|m| m.len()).unwrap_or(0);
35+
if size > 1024 * 1024 * 500 {
36+
let lines = BufReader::new(&mut file).lines().map(|x| x.unwrap()).collect();
3637
Ok(lines)
38+
} else {
39+
let mut string = String::new();
40+
string.reserve_exact(size as usize);
41+
file.read_to_string(&mut string)?;
42+
Ok(string.lines().map(|x| x.to_string()).collect())
3743
}
3844
}
3945

0 commit comments

Comments
 (0)