Skip to content

Commit 01b4dd7

Browse files
vtronkocorneliusroemer
authored andcommitted
Fix #100: allow line-buffered input
1 parent 2d287b9 commit 01b4dd7

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

src/cli.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ w - match full words only
5757
*/
5858
pub flags: Option<String>,
5959

60+
#[arg(short = 'l', long = "line-buffered", default_value_t = false)]
61+
/// Buffered mode. Doesn't support multiline matching
62+
pub line_buffered: bool,
63+
6064
/// The regexp or string (if using `-F`) to search for.
6165
pub find: String,
6266

src/input.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
use crate::Result;
12
use memmap2::{Mmap, MmapOptions};
23
use std::{
34
fs::File,
45
io::{stdin, Read},
56
path::PathBuf,
67
};
78

8-
use crate::error::Result;
9-
109
#[derive(Debug, PartialEq)]
1110
pub(crate) enum Source {
1211
Stdin,

src/main.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use clap::Parser;
88
use memmap2::MmapMut;
99
use std::{
1010
fs,
11-
io::{stdout, Write},
11+
io::{stdout, BufRead, Write},
1212
ops::DerefMut,
1313
path::PathBuf,
1414
process,
@@ -43,6 +43,34 @@ fn try_main() -> Result<()> {
4343
Source::from_stdin()
4444
};
4545

46+
if options.line_buffered && sources == Source::from_stdin() {
47+
let stdin = std::io::stdin();
48+
let stdout = std::io::stdout();
49+
let mut handle = stdout.lock();
50+
51+
let mut buffer = String::new();
52+
53+
loop {
54+
let mut read_handle = stdin.lock();
55+
let bytes_read = read_handle.read_line(&mut buffer)?;
56+
57+
// .lock()
58+
// .read_line(&mut buffer)
59+
// .expect("Error reading from standard input");
60+
if bytes_read == 0 {
61+
break;
62+
}
63+
let replaced = replacer.replace(buffer.as_bytes());
64+
handle
65+
.write_all(replaced.as_ref())
66+
.expect("Error writing to standard output");
67+
handle.flush().expect("Error flushing output");
68+
buffer.clear();
69+
}
70+
71+
return Ok(());
72+
}
73+
4674
let mut mmaps = Vec::new();
4775
for source in sources.iter() {
4876
let mmap = match source {

0 commit comments

Comments
 (0)