1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-09-15 11:36:16 +00:00

expand: move logic to expand a single line into its own function

This commit is contained in:
clint 2023-11-08 23:36:46 -05:00
parent 3411c25112
commit fc00b6bfc9

View file

@ -366,21 +366,14 @@ enum CharType {
Other,
}
#[allow(clippy::cognitive_complexity)]
fn expand(options: &Options) -> UResult<()> {
fn expand_line(
buf: &mut Vec<u8>,
output: &mut BufWriter<std::io::Stdout>,
ts: &[usize],
options: &Options,
) -> std::io::Result<()> {
use self::CharType::*;
let mut output = BufWriter::new(stdout());
let ts = options.tabstops.as_ref();
let mut buf = Vec::new();
for file in &options.files {
let mut fh = open(file)?;
while match fh.read_until(b'\n', &mut buf) {
Ok(s) => s > 0,
Err(_) => buf.is_empty(),
} {
let mut col = 0;
let mut byte = 0;
let mut init = true;
@ -428,18 +421,12 @@ fn expand(options: &Options) -> UResult<()> {
// now dump out either spaces if we're expanding, or a literal tab if we're not
if init || !options.iflag {
if nts <= options.tspaces.len() {
output
.write_all(options.tspaces[..nts].as_bytes())
.map_err_context(|| "failed to write output".to_string())?;
output.write_all(options.tspaces[..nts].as_bytes())?;
} else {
output
.write_all(" ".repeat(nts).as_bytes())
.map_err_context(|| "failed to write output".to_string())?;
output.write_all(" ".repeat(nts).as_bytes())?;
};
} else {
output
.write_all(&buf[byte..byte + nbytes])
.map_err_context(|| "failed to write output".to_string())?;
output.write_all(&buf[byte..byte + nbytes])?;
}
}
_ => {
@ -457,19 +444,33 @@ fn expand(options: &Options) -> UResult<()> {
init = false;
}
output
.write_all(&buf[byte..byte + nbytes])
.map_err_context(|| "failed to write output".to_string())?;
output.write_all(&buf[byte..byte + nbytes])?;
}
}
byte += nbytes; // advance the pointer
}
output
.flush()
.map_err_context(|| "failed to write output".to_string())?;
output.flush()?;
buf.truncate(0); // clear the buffer
Ok(())
}
fn expand(options: &Options) -> UResult<()> {
let mut output = BufWriter::new(stdout());
let ts = options.tabstops.as_ref();
let mut buf = Vec::new();
for file in &options.files {
let mut fh = open(file)?;
while match fh.read_until(b'\n', &mut buf) {
Ok(s) => s > 0,
Err(_) => buf.is_empty(),
} {
expand_line(&mut buf, &mut output, ts, options)
.map_err_context(|| "failed to write output".to_string())?;
}
}
Ok(())