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, Other,
} }
#[allow(clippy::cognitive_complexity)] fn expand_line(
fn expand(options: &Options) -> UResult<()> { buf: &mut Vec<u8>,
output: &mut BufWriter<std::io::Stdout>,
ts: &[usize],
options: &Options,
) -> std::io::Result<()> {
use self::CharType::*; 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 col = 0;
let mut byte = 0; let mut byte = 0;
let mut init = true; 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 // now dump out either spaces if we're expanding, or a literal tab if we're not
if init || !options.iflag { if init || !options.iflag {
if nts <= options.tspaces.len() { if nts <= options.tspaces.len() {
output output.write_all(options.tspaces[..nts].as_bytes())?;
.write_all(options.tspaces[..nts].as_bytes())
.map_err_context(|| "failed to write output".to_string())?;
} else { } else {
output output.write_all(" ".repeat(nts).as_bytes())?;
.write_all(" ".repeat(nts).as_bytes())
.map_err_context(|| "failed to write output".to_string())?;
}; };
} else { } else {
output output.write_all(&buf[byte..byte + nbytes])?;
.write_all(&buf[byte..byte + nbytes])
.map_err_context(|| "failed to write output".to_string())?;
} }
} }
_ => { _ => {
@ -457,19 +444,33 @@ fn expand(options: &Options) -> UResult<()> {
init = false; init = false;
} }
output output.write_all(&buf[byte..byte + nbytes])?;
.write_all(&buf[byte..byte + nbytes])
.map_err_context(|| "failed to write output".to_string())?;
} }
} }
byte += nbytes; // advance the pointer byte += nbytes; // advance the pointer
} }
output output.flush()?;
.flush()
.map_err_context(|| "failed to write output".to_string())?;
buf.truncate(0); // clear the buffer 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(()) Ok(())