From 8e862b86dd49354d49921086315dd07509470a62 Mon Sep 17 00:00:00 2001 From: Tyler Date: Fri, 2 Jul 2021 14:24:01 -0700 Subject: [PATCH] More minor cleanup. - Runs rustfmt. - Speel check help-text --- src/uu/dd/src/conversion_tables.rs | 4 - src/uu/dd/src/datastructures.rs | 63 +- src/uu/dd/src/dd.rs | 1149 +++++++---------- .../src/dd_unit_tests/block_unblock_tests.rs | 204 ++- .../dd/src/dd_unit_tests/conv_sync_tests.rs | 4 +- .../dd/src/dd_unit_tests/conversion_tests.rs | 27 +- src/uu/dd/src/dd_unit_tests/mod.rs | 16 +- src/uu/dd/src/dd_unit_tests/sanity_tests.rs | 50 +- src/uu/dd/src/parseargs.rs | 928 ++++++------- src/uu/dd/src/parseargs/unit_tests.rs | 284 ++-- 10 files changed, 1107 insertions(+), 1622 deletions(-) diff --git a/src/uu/dd/src/conversion_tables.rs b/src/uu/dd/src/conversion_tables.rs index 755331eed..a3b9a81c0 100644 --- a/src/uu/dd/src/conversion_tables.rs +++ b/src/uu/dd/src/conversion_tables.rs @@ -39,7 +39,6 @@ pub const ASCII_LCASE_TO_UCASE: ConversionTable = [ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, - ]; pub const ASCII_TO_EBCDIC: ConversionTable = [ @@ -137,7 +136,6 @@ pub const ASCII_TO_IBM_UCASE_TO_LCASE: ConversionTable = [ 0xdc, 0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; - pub const ASCII_TO_IBM_LCASE_TO_UCASE: ConversionTable = [ 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, 0x16, 0x05, 0x25, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, @@ -176,7 +174,6 @@ pub const EBCDIC_TO_ASCII: ConversionTable = [ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; - pub const EBCDIC_TO_ASCII_UCASE_TO_LCASE: ConversionTable = [ 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, 0x16, 0x05, 0x25, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, @@ -214,4 +211,3 @@ pub const EBCDIC_TO_ASCII_LCASE_TO_UCASE: ConversionTable = [ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; - diff --git a/src/uu/dd/src/datastructures.rs b/src/uu/dd/src/datastructures.rs index cb720aeb7..42026c5b3 100644 --- a/src/uu/dd/src/datastructures.rs +++ b/src/uu/dd/src/datastructures.rs @@ -3,8 +3,7 @@ use crate::conversion_tables::*; use std::error::Error; use std::time; -pub struct ProgUpdate -{ +pub struct ProgUpdate { pub reads_complete: u64, pub reads_partial: u64, pub writes_complete: u64, @@ -14,16 +13,13 @@ pub struct ProgUpdate pub duration: time::Duration, } -pub struct ReadStat -{ +pub struct ReadStat { pub reads_complete: u64, pub reads_partial: u64, pub records_truncated: u32, } -impl std::ops::AddAssign for ReadStat -{ - fn add_assign(&mut self, other: Self) - { +impl std::ops::AddAssign for ReadStat { + fn add_assign(&mut self, other: Self) { *self = Self { reads_complete: self.reads_complete + other.reads_complete, reads_partial: self.reads_partial + other.reads_partial, @@ -32,16 +28,13 @@ impl std::ops::AddAssign for ReadStat } } -pub struct WriteStat -{ +pub struct WriteStat { pub writes_complete: u64, pub writes_partial: u64, pub bytes_total: u128, } -impl std::ops::AddAssign for WriteStat -{ - fn add_assign(&mut self, other: Self) - { +impl std::ops::AddAssign for WriteStat { + fn add_assign(&mut self, other: Self) { *self = Self { writes_complete: self.writes_complete + other.writes_complete, writes_partial: self.writes_partial + other.writes_partial, @@ -53,8 +46,7 @@ impl std::ops::AddAssign for WriteStat type Cbs = usize; /// Stores all Conv Flags that apply to the input -pub struct IConvFlags -{ +pub struct IConvFlags { pub ctable: Option<&'static ConversionTable>, pub block: Option, pub unblock: Option, @@ -65,8 +57,7 @@ pub struct IConvFlags /// Stores all Conv Flags that apply to the output #[derive(Debug, PartialEq)] -pub struct OConvFlags -{ +pub struct OConvFlags { pub sparse: bool, pub excl: bool, pub nocreat: bool, @@ -76,8 +67,7 @@ pub struct OConvFlags } /// Stores all Flags that apply to the input -pub struct IFlags -{ +pub struct IFlags { pub cio: bool, pub direct: bool, pub directory: bool, @@ -97,8 +87,7 @@ pub struct IFlags } /// Stores all Flags that apply to the output -pub struct OFlags -{ +pub struct OFlags { pub append: bool, pub cio: bool, pub direct: bool, @@ -119,8 +108,7 @@ pub struct OFlags /// The value of the status cl-option. /// Controls printing of transfer stats #[derive(Copy, Clone, Debug, PartialEq)] -pub enum StatusLevel -{ +pub enum StatusLevel { Progress, Noxfer, None, @@ -130,38 +118,35 @@ pub enum StatusLevel /// Defaults to Reads(N) /// if iflag=count_bytes /// then becomes Bytes(N) -pub enum CountType -{ +pub enum CountType { Reads(usize), Bytes(usize), } #[derive(Debug)] -pub enum InternalError -{ +pub enum InternalError { WrongInputType, WrongOutputType, InvalidConvBlockUnblockCase, } -impl std::fmt::Display for InternalError -{ +impl std::fmt::Display for InternalError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self - { - Self::WrongInputType | - Self::WrongOutputType => - write!(f, "Internal dd error: Wrong Input/Output data type"), - Self::InvalidConvBlockUnblockCase => - write!(f, "Internal dd error: Invalid Conversion, Block, or Unblock data"), + match self { + Self::WrongInputType | Self::WrongOutputType => { + write!(f, "Internal dd error: Wrong Input/Output data type") + } + Self::InvalidConvBlockUnblockCase => write!( + f, + "Internal dd error: Invalid Conversion, Block, or Unblock data" + ), } } } impl Error for InternalError {} -pub mod options -{ +pub mod options { pub const INFILE: &'static str = "if"; pub const OUTFILE: &'static str = "of"; pub const IBS: &'static str = "ibs"; diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index fe43be397..64bedc828 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -23,22 +23,22 @@ use parseargs::Matches; mod conversion_tables; use conversion_tables::*; -use clap::{self, crate_version}; use byte_unit::Byte; +use clap::{self, crate_version}; use debug_print::debug_println; use gcd::Gcd; +#[cfg(unix)] +use libc; use signal_hook::consts::signal; use std::cmp; use std::convert::TryInto; -use std::error::Error; use std::env; -use std::fs::{File, OpenOptions, }; -use std::io::{self, Read, Write, Seek, }; -#[cfg(unix)] -use libc; +use std::error::Error; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Seek, Write}; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; -use std::sync::{Arc, atomic::AtomicUsize, mpsc, atomic::Ordering, }; +use std::sync::{atomic::AtomicUsize, atomic::Ordering, mpsc, Arc}; use std::thread; use std::time; @@ -48,8 +48,7 @@ const BUF_INIT_BYTE: u8 = 0xDD; const RTN_SUCCESS: i32 = 0; const RTN_FAILURE: i32 = 1; -struct Input -{ +struct Input { src: R, non_ascii: bool, ibs: usize, @@ -59,10 +58,8 @@ struct Input iflags: IFlags, } -impl Input -{ - fn new(matches: &Matches) -> Result> - { +impl Input { + fn new(matches: &Matches) -> Result> { let ibs = parseargs::parse_ibs(matches)?; let non_ascii = parseargs::parse_input_non_ascii(matches)?; let xfer_stats = parseargs::parse_status_level(matches)?; @@ -81,8 +78,7 @@ impl Input iflags, }; - if let Some(amt) = skip - { + if let Some(amt) = skip { let mut buf = vec![BUF_INIT_BYTE; amt]; i.force_fill(&mut buf, amt)?; @@ -92,57 +88,43 @@ impl Input } } -fn make_unix_iflags(oflags: &IFlags) -> Option -{ +fn make_unix_iflags(oflags: &IFlags) -> Option { let mut flag = 0; - if oflags.direct - { + if oflags.direct { flag |= libc::O_DIRECT; } - if oflags.directory - { + if oflags.directory { flag |= libc::O_DIRECTORY; } - if oflags.dsync - { + if oflags.dsync { flag |= libc::O_DSYNC; } - if oflags.noatime - { + if oflags.noatime { flag |= libc::O_NOATIME; } - if oflags.noctty - { + if oflags.noctty { flag |= libc::O_NOCTTY; } - if oflags.nofollow - { + if oflags.nofollow { flag |= libc::O_NOFOLLOW; } - if oflags.nonblock - { + if oflags.nonblock { flag |= libc::O_NONBLOCK; } - if oflags.sync - { + if oflags.sync { flag |= libc::O_SYNC; } - if flag != 0 - { + if flag != 0 { Some(flag) - } - else - { + } else { None } } -impl Input -{ - fn new(matches: &Matches) -> Result> - { +impl Input { + fn new(matches: &Matches) -> Result> { let ibs = parseargs::parse_ibs(matches)?; let non_ascii = parseargs::parse_input_non_ascii(matches)?; let xfer_stats = parseargs::parse_status_level(matches)?; @@ -151,17 +133,13 @@ impl Input let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?; let count = parseargs::parse_count(&iflags, matches)?; - if let Some(fname) = matches.value_of("if") - { - let mut src = - { + if let Some(fname) = matches.value_of("if") { + let mut src = { let mut opts = OpenOptions::new(); opts.read(true); - if cfg!(unix) - { - if let Some(libc_flags) = make_unix_iflags(&iflags) - { + if cfg!(unix) { + if let Some(libc_flags) = make_unix_iflags(&iflags) { opts.custom_flags(libc_flags); } } @@ -169,8 +147,7 @@ impl Input opts.open(fname)? }; - if let Some(amt) = skip - { + if let Some(amt) = skip { let amt: u64 = amt.try_into()?; src.seek(io::SeekFrom::Start(amt))?; } @@ -186,78 +163,57 @@ impl Input }; Ok(i) - } - else - { + } else { Err(Box::new(InternalError::WrongInputType)) } - } } -impl Read for Input -{ - fn read(&mut self, buf: &mut [u8]) -> io::Result - { +impl Read for Input { + fn read(&mut self, buf: &mut [u8]) -> io::Result { let mut base_idx = 0; let tlen = buf.len(); - loop - { - match self.src.read(&mut buf[base_idx..]) - { - Ok(0) => - return Ok(base_idx), - Ok(rlen) if self.iflags.fullblock => - { + loop { + match self.src.read(&mut buf[base_idx..]) { + Ok(0) => return Ok(base_idx), + Ok(rlen) if self.iflags.fullblock => { base_idx += rlen; - if base_idx >= tlen - { - return Ok(tlen) + if base_idx >= tlen { + return Ok(tlen); } - }, - Ok(len) => - return Ok(len), - Err(e) if e.kind() == io::ErrorKind::Interrupted => - continue, - Err(_) if self.cflags.noerror => - return Ok(base_idx), - Err(e) => - return Err(e), + } + Ok(len) => return Ok(len), + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(_) if self.cflags.noerror => return Ok(base_idx), + Err(e) => return Err(e), } } } } -impl Input -{ +impl Input { /// Fills a given buffer. /// Reads in increments of 'self.ibs'. /// The start of each ibs-sized read follows the previous one. - fn fill_consecutive(&mut self, buf: &mut Vec) -> Result> - { + fn fill_consecutive(&mut self, buf: &mut Vec) -> Result> { let mut reads_complete = 0; let mut reads_partial = 0; let mut base_idx = 0; - while base_idx < buf.len() - { - let next_blk = cmp::min(base_idx+self.ibs, buf.len()); + while base_idx < buf.len() { + let next_blk = cmp::min(base_idx + self.ibs, buf.len()); - match self.read(&mut buf[base_idx..next_blk])? - { - rlen if rlen == self.ibs => - { + match self.read(&mut buf[base_idx..next_blk])? { + rlen if rlen == self.ibs => { base_idx += rlen; reads_complete += 1; - }, - rlen if rlen > 0 => - { + } + rlen if rlen > 0 => { base_idx += rlen; reads_partial += 1; - }, - _ => - break, + } + _ => break, } } @@ -267,36 +223,30 @@ impl Input reads_partial, records_truncated: 0, }) - } + } /// Fills a given buffer. /// Reads in increments of 'self.ibs'. /// The start of each ibs-sized read is aligned to multiples of ibs; remaing space is filled with the 'pad' byte. - fn fill_blocks(&mut self, buf: &mut Vec, pad: u8) -> Result> - { + fn fill_blocks(&mut self, buf: &mut Vec, pad: u8) -> Result> { let mut reads_complete = 0; let mut reads_partial = 0; let mut base_idx = 0; - while base_idx < buf.len() - { - let next_blk = cmp::min(base_idx+self.ibs, buf.len()); + while base_idx < buf.len() { + let next_blk = cmp::min(base_idx + self.ibs, buf.len()); let plen = next_blk - base_idx; - match self.read(&mut buf[base_idx..next_blk])? - { - 0 => - break, - rlen if rlen < plen => - { + match self.read(&mut buf[base_idx..next_blk])? { + 0 => break, + rlen if rlen < plen => { reads_partial += 1; - let padding = vec![pad; plen-rlen]; - buf.splice(base_idx+rlen..next_blk, padding.into_iter()); - }, - _ => - { + let padding = vec![pad; plen - rlen]; + buf.splice(base_idx + rlen..next_blk, padding.into_iter()); + } + _ => { reads_complete += 1; - }, + } } // TODO: Why does this cause the conv=sync tests to hang? // let rlen = self.read(&mut buf[base_idx..next_blk])?; @@ -324,26 +274,23 @@ impl Input reads_partial, records_truncated: 0, }) - } + } /// Force-fills a buffer, ignoring zero-length reads which would otherwise be /// interpreted as EOF. /// Note: This will not return unless the source (eventually) produces /// enough bytes to meet target_len. - fn force_fill(&mut self, buf: &mut [u8], target_len: usize) -> Result> - { + fn force_fill(&mut self, buf: &mut [u8], target_len: usize) -> Result> { let mut base_idx = 0; - while base_idx < target_len - { + while base_idx < target_len { base_idx += self.read(&mut buf[base_idx..target_len])?; } - Ok(base_idx) + Ok(base_idx) } } -struct Output -{ +struct Output { dst: W, obs: usize, cflags: OConvFlags, @@ -351,8 +298,7 @@ struct Output } impl Output { - fn new(matches: &Matches) -> Result> - { + fn new(matches: &Matches) -> Result> { let obs = parseargs::parse_obs(matches)?; let cflags = parseargs::parse_conv_flag_output(matches)?; let oflags = parseargs::parse_oflags(matches)?; @@ -360,86 +306,69 @@ impl Output { let dst = io::stdout(); Ok(Output { - dst, - obs, - cflags, - oflags, + dst, + obs, + cflags, + oflags, }) } - fn fsync(&mut self) -> io::Result<()> - { + fn fsync(&mut self) -> io::Result<()> { self.dst.flush() } - fn fdatasync(&mut self) -> io::Result<()> - { + fn fdatasync(&mut self) -> io::Result<()> { self.dst.flush() } } -fn make_unix_oflags(oflags: &OFlags) -> Option -{ +fn make_unix_oflags(oflags: &OFlags) -> Option { let mut flag = 0; // oflag=FLAG - if oflags.append - { + if oflags.append { flag |= libc::O_APPEND; } - if oflags.direct - { + if oflags.direct { flag |= libc::O_DIRECT; } - if oflags.directory - { + if oflags.directory { flag |= libc::O_DIRECTORY; } - if oflags.dsync - { + if oflags.dsync { flag |= libc::O_DSYNC; } - if oflags.noatime - { + if oflags.noatime { flag |= libc::O_NOATIME; } - if oflags.noctty - { + if oflags.noctty { flag |= libc::O_NOCTTY; } - if oflags.nofollow - { + if oflags.nofollow { flag |= libc::O_NOFOLLOW; } - if oflags.nonblock - { + if oflags.nonblock { flag |= libc::O_NONBLOCK; } - if oflags.sync - { + if oflags.sync { flag |= libc::O_SYNC; } - if flag != 0 - { + if flag != 0 { Some(flag) - } - else - { + } else { None } } impl Output { - fn new(matches: &Matches) -> Result> - { + fn new(matches: &Matches) -> Result> { let obs = parseargs::parse_obs(matches)?; let cflags = parseargs::parse_conv_flag_output(matches)?; let oflags = parseargs::parse_oflags(matches)?; let seek = parseargs::parse_seek_amt(&obs, &oflags, matches)?; - if let Some(fname) = matches.value_of("of") - { + if let Some(fname) = matches.value_of("of") { let mut dst = { let mut opts = OpenOptions::new(); opts.write(true) @@ -449,10 +378,8 @@ impl Output { // 'create_new' overrides 'create' .create_new(cflags.excl && !cflags.nocreat); - if cfg!(unix) - { - if let Some(libc_flags) = make_unix_oflags(&oflags) - { + if cfg!(unix) { + if let Some(libc_flags) = make_unix_oflags(&oflags) { opts.custom_flags(libc_flags); } } @@ -460,8 +387,7 @@ impl Output { opts.open(fname)? }; - if let Some(amt) = seek - { + if let Some(amt) = seek { let amt: u64 = amt.try_into()?; dst.seek(io::SeekFrom::Start(amt))?; } @@ -472,9 +398,7 @@ impl Output { cflags, oflags, }) - } - else - { + } else { // The following error should only occur if someone // mistakenly calls Output::::new() without checking // if 'of' has been provided. In this case, @@ -483,96 +407,76 @@ impl Output { } } - fn fsync(&mut self) -> io::Result<()> - { + fn fsync(&mut self) -> io::Result<()> { self.dst.flush()?; self.dst.sync_all() } - fn fdatasync(&mut self) -> io::Result<()> - { + fn fdatasync(&mut self) -> io::Result<()> { self.dst.flush()?; self.dst.sync_data() } } -impl Seek for Output -{ - fn seek(&mut self, pos: io::SeekFrom) -> io::Result - { +impl Seek for Output { + fn seek(&mut self, pos: io::SeekFrom) -> io::Result { self.dst.seek(pos) } } -impl Write for Output -{ - fn write(&mut self, buf: &[u8]) -> io::Result - { +impl Write for Output { + fn write(&mut self, buf: &[u8]) -> io::Result { #[inline] - fn is_sparse(buf: &[u8]) -> bool - { - buf.iter() - .all(|&e| e == 0u8) + fn is_sparse(buf: &[u8]) -> bool { + buf.iter().all(|&e| e == 0u8) } // ----------------------------- - if self.cflags.sparse && is_sparse(buf) - { - let seek_amt: i64 = buf.len() - .try_into() - .expect("Internal dd Error: Seek amount greater than signed 64-bit integer"); + if self.cflags.sparse && is_sparse(buf) { + let seek_amt: i64 = buf + .len() + .try_into() + .expect("Internal dd Error: Seek amount greater than signed 64-bit integer"); self.dst.seek(io::SeekFrom::Current(seek_amt))?; Ok(buf.len()) - } - else - { + } else { self.dst.write(buf) } } - fn flush(&mut self) -> io::Result<()> - { + fn flush(&mut self) -> io::Result<()> { self.dst.flush() } } -impl Write for Output -{ - fn write(&mut self, buf: &[u8]) -> io::Result - { +impl Write for Output { + fn write(&mut self, buf: &[u8]) -> io::Result { self.dst.write(buf) } - fn flush(&mut self) -> io::Result<()> - { + fn flush(&mut self) -> io::Result<()> { self.dst.flush() } } -impl Output -{ - fn write_blocks(&mut self, buf: Vec) -> io::Result - { +impl Output { + fn write_blocks(&mut self, buf: Vec) -> io::Result { let mut writes_complete = 0; let mut writes_partial = 0; let mut base_idx = 0; - while base_idx < buf.len() - { - let next_blk = cmp::min(base_idx+self.obs, buf.len()); + while base_idx < buf.len() { + let next_blk = cmp::min(base_idx + self.obs, buf.len()); let plen = next_blk - base_idx; - match self.write(&buf[base_idx..next_blk])? - { - wlen if wlen < plen => - { + match self.write(&buf[base_idx..next_blk])? { + wlen if wlen < plen => { writes_partial += 1; base_idx += wlen; - }, - wlen => - { + } + wlen => { writes_complete += 1; base_idx += wlen; - }, + } } } @@ -581,34 +485,28 @@ impl Output writes_partial, bytes_total: base_idx.try_into().unwrap_or(0u128), }) - } + } } -impl Output -{ - fn write_blocks(&mut self, buf: Vec) -> io::Result - { +impl Output { + fn write_blocks(&mut self, buf: Vec) -> io::Result { let mut writes_complete = 0; let mut writes_partial = 0; let mut base_idx = 0; - while base_idx < buf.len() - { - let next_blk = cmp::min(base_idx+self.obs, buf.len()); + while base_idx < buf.len() { + let next_blk = cmp::min(base_idx + self.obs, buf.len()); let plen = next_blk - base_idx; - match self.write(&buf[base_idx..next_blk])? - { - wlen if wlen < plen => - { + match self.write(&buf[base_idx..next_blk])? { + wlen if wlen < plen => { writes_partial += 1; base_idx += wlen; - }, - wlen => - { + } + wlen => { writes_complete += 1; base_idx += wlen; - }, + } } } @@ -617,31 +515,27 @@ impl Output writes_partial, bytes_total: base_idx.try_into().unwrap_or(0u128), }) - } + } } /// Splits the content of buf into cbs-length blocks /// Appends padding as specified by conv=block and cbs=N -fn block(buf: Vec, cbs: usize, rstat: &mut ReadStat) -> Vec> -{ - let mut blocks = buf.split(| &e | e == '\n' as u8) - .fold(Vec::new(), | mut blocks, split | - { - let mut split = split.to_vec(); - if split.len() > cbs - { - rstat.records_truncated += 1; - } - split.resize(cbs, ' ' as u8); - blocks.push(split); +fn block(buf: Vec, cbs: usize, rstat: &mut ReadStat) -> Vec> { + let mut blocks = buf + .split(|&e| e == '\n' as u8) + .fold(Vec::new(), |mut blocks, split| { + let mut split = split.to_vec(); + if split.len() > cbs { + rstat.records_truncated += 1; + } + split.resize(cbs, ' ' as u8); + blocks.push(split); - blocks - }); + blocks + }); - if let Some(last) = blocks.last() - { - if last.iter().all(| &e | e == ' ' as u8) - { + if let Some(last) = blocks.last() { + if last.iter().all(|&e| e == ' ' as u8) { blocks.pop(); } } @@ -651,19 +545,16 @@ fn block(buf: Vec, cbs: usize, rstat: &mut ReadStat) -> Vec> /// Trims padding from each cbs-length partition of buf /// as specified by conv=unblock and cbs=N -fn unblock(buf: Vec, cbs: usize) -> Vec -{ +fn unblock(buf: Vec, cbs: usize) -> Vec { // Local Helper Fns ---------------------------------------------------- #[inline] - fn build_blocks(buf: Vec, cbs: usize) -> Vec> - { + fn build_blocks(buf: Vec, cbs: usize) -> Vec> { let mut blocks = Vec::new(); let mut curr = buf; let mut next; let mut width; - while !curr.is_empty() - { + while !curr.is_empty() { width = cmp::min(cbs, curr.len()); next = curr.split_off(width); @@ -677,20 +568,15 @@ fn unblock(buf: Vec, cbs: usize) -> Vec // --------------------------------------------------------------------- build_blocks(buf, cbs) .into_iter() - .fold(Vec::new(), | mut unblocks, mut block | { - let block = if let Some(last_char_idx) = block.iter().rposition(| &e | e != ' ' as u8) - { - block.truncate(last_char_idx+1); + .fold(Vec::new(), |mut unblocks, mut block| { + let block = if let Some(last_char_idx) = block.iter().rposition(|&e| e != ' ' as u8) { + block.truncate(last_char_idx + 1); block.push('\n' as u8); block - } - else if let Some(32u8/* ' ' as u8 */) = block.get(0) - { + } else if let Some(32u8 /* ' ' as u8 */) = block.get(0) { vec!['\n' as u8] - } - else - { + } else { block }; @@ -703,120 +589,94 @@ fn unblock(buf: Vec, cbs: usize) -> Vec .collect() } -fn conv_block_unblock_helper(mut buf: Vec, i: &mut Input, rstat: &mut ReadStat) -> Result, Box> -{ +fn conv_block_unblock_helper( + mut buf: Vec, + i: &mut Input, + rstat: &mut ReadStat, +) -> Result, Box> { // Local Predicate Fns ------------------------------------------------- #[inline] - fn should_block_then_conv(i: &Input) -> bool - { - !i.non_ascii - && i.cflags.block.is_some() + fn should_block_then_conv(i: &Input) -> bool { + !i.non_ascii && i.cflags.block.is_some() } #[inline] - fn should_conv_then_block(i: &Input) -> bool - { - i.non_ascii - && i.cflags.block.is_some() + fn should_conv_then_block(i: &Input) -> bool { + i.non_ascii && i.cflags.block.is_some() } #[inline] - fn should_unblock_then_conv(i: &Input) -> bool - { - !i.non_ascii - && i.cflags.unblock.is_some() + fn should_unblock_then_conv(i: &Input) -> bool { + !i.non_ascii && i.cflags.unblock.is_some() } #[inline] - fn should_conv_then_unblock(i: &Input) -> bool - { - i.non_ascii - && i.cflags.unblock.is_some() + fn should_conv_then_unblock(i: &Input) -> bool { + i.non_ascii && i.cflags.unblock.is_some() } - fn conv_only(i: &Input) -> bool - { - i.cflags.ctable.is_some() - && i.cflags.block.is_none() - && i.cflags.unblock.is_none() + fn conv_only(i: &Input) -> bool { + i.cflags.ctable.is_some() && i.cflags.block.is_none() && i.cflags.unblock.is_none() } // Local Helper Fns ---------------------------------------------------- #[inline] - fn apply_ct(buf: &mut [u8], ct: &ConversionTable) - { - for idx in 0..buf.len() - { + fn apply_ct(buf: &mut [u8], ct: &ConversionTable) { + for idx in 0..buf.len() { buf[idx] = ct[buf[idx] as usize]; } } // -------------------------------------------------------------------- - if conv_only(&i) - { // no block/unblock + if conv_only(&i) { + // no block/unblock let ct = i.cflags.ctable.unwrap(); apply_ct(&mut buf, &ct); Ok(buf) - } - else if should_block_then_conv(&i) - { // ascii input so perform the block first + } else if should_block_then_conv(&i) { + // ascii input so perform the block first let cbs = i.cflags.block.unwrap(); let mut blocks = block(buf, cbs, rstat); - if let Some(ct) = i.cflags.ctable - { - for buf in blocks.iter_mut() - { + if let Some(ct) = i.cflags.ctable { + for buf in blocks.iter_mut() { apply_ct(buf, &ct); } } - let blocks = blocks.into_iter() - .flatten() - .collect(); + let blocks = blocks.into_iter().flatten().collect(); Ok(blocks) - } - else if should_conv_then_block(&i) - { // Non-ascii so perform the conversion first + } else if should_conv_then_block(&i) { + // Non-ascii so perform the conversion first let cbs = i.cflags.block.unwrap(); - if let Some(ct) = i.cflags.ctable - { - apply_ct(&mut buf, &ct); + if let Some(ct) = i.cflags.ctable { + apply_ct(&mut buf, &ct); } - let blocks = block(buf, cbs, rstat) - .into_iter() - .flatten() - .collect(); + let blocks = block(buf, cbs, rstat).into_iter().flatten().collect(); Ok(blocks) - } - else if should_unblock_then_conv(&i) - { // ascii input so perform the unblock first + } else if should_unblock_then_conv(&i) { + // ascii input so perform the unblock first let cbs = i.cflags.unblock.unwrap(); let mut buf = unblock(buf, cbs); - if let Some(ct) = i.cflags.ctable - { - apply_ct(&mut buf, &ct); + if let Some(ct) = i.cflags.ctable { + apply_ct(&mut buf, &ct); } Ok(buf) - } - else if should_conv_then_unblock(&i) - { // Non-ascii input so perform the conversion first + } else if should_conv_then_unblock(&i) { + // Non-ascii input so perform the conversion first let cbs = i.cflags.unblock.unwrap(); - if let Some(ct) = i.cflags.ctable - { - apply_ct(&mut buf, &ct); + if let Some(ct) = i.cflags.ctable { + apply_ct(&mut buf, &ct); } let buf = unblock(buf, cbs); Ok(buf) - } - else - { + } else { // The following error should not happen, as it results from // insufficient command line data. This case should be caught // by the parser before making it this far. @@ -826,80 +686,72 @@ fn conv_block_unblock_helper(mut buf: Vec, i: &mut Input, rstat: } } -fn read_helper(i: &mut Input, bsize: usize) -> Result<(ReadStat, Vec), Box> -{ +fn read_helper( + i: &mut Input, + bsize: usize, +) -> Result<(ReadStat, Vec), Box> { // Local Predicate Fns ----------------------------------------------- #[inline] - fn is_conv(i: &Input) -> bool - { + fn is_conv(i: &Input) -> bool { i.cflags.ctable.is_some() } #[inline] - fn is_block(i: &Input) -> bool - { + fn is_block(i: &Input) -> bool { i.cflags.block.is_some() } #[inline] - fn is_unblock(i: &Input) -> bool - { + fn is_unblock(i: &Input) -> bool { i.cflags.unblock.is_some() } // Local Helper Fns ------------------------------------------------- #[inline] - fn perform_swab(buf: &mut [u8]) - { + fn perform_swab(buf: &mut [u8]) { let mut tmp; - for base in (1..buf.len()).step_by(2) - { + for base in (1..buf.len()).step_by(2) { tmp = buf[base]; - buf[base] = buf[base-1]; - buf[base-1] = tmp; + buf[base] = buf[base - 1]; + buf[base - 1] = tmp; } } - // ------------------------------------------------------------------ - // Read - let mut buf = vec![BUF_INIT_BYTE; bsize]; - let mut rstat = match i.cflags.sync - { - Some(ch) => - i.fill_blocks(&mut buf, ch)?, - _ => - i.fill_consecutive(&mut buf)?, - }; - // Return early if no data - if rstat.reads_complete == 0 && rstat.reads_partial == 0 - { - return Ok((rstat,buf)); - } + // ------------------------------------------------------------------ + // Read + let mut buf = vec![BUF_INIT_BYTE; bsize]; + let mut rstat = match i.cflags.sync { + Some(ch) => i.fill_blocks(&mut buf, ch)?, + _ => i.fill_consecutive(&mut buf)?, + }; + // Return early if no data + if rstat.reads_complete == 0 && rstat.reads_partial == 0 { + return Ok((rstat, buf)); + } - // Perform any conv=x[,x...] options - if i.cflags.swab - { - perform_swab(&mut buf); - } - if is_conv(&i) || is_block(&i) || is_unblock(&i) - { - let buf = conv_block_unblock_helper(buf, i, &mut rstat)?; - Ok((rstat, buf)) - } - else - { - Ok((rstat, buf)) - } + // Perform any conv=x[,x...] options + if i.cflags.swab { + perform_swab(&mut buf); + } + if is_conv(&i) || is_block(&i) || is_unblock(&i) { + let buf = conv_block_unblock_helper(buf, i, &mut rstat)?; + Ok((rstat, buf)) + } else { + Ok((rstat, buf)) + } } -fn print_io_lines(update: &ProgUpdate) -{ - eprintln!("{}+{} records in", update.reads_complete, update.reads_partial); - if update.records_truncated > 0 - { +fn print_io_lines(update: &ProgUpdate) { + eprintln!( + "{}+{} records in", + update.reads_complete, update.reads_partial + ); + if update.records_truncated > 0 { eprintln!("{} truncated records", update.records_truncated); } - eprintln!("{}+{} records out", update.writes_complete, update.writes_partial); + eprintln!( + "{}+{} records out", + update.writes_complete, update.writes_partial + ); } -fn make_prog_line(update: &ProgUpdate) -> String -{ +fn make_prog_line(update: &ProgUpdate) -> String { let btotal_metric = Byte::from_bytes(update.bytes_total) .get_appropriate_unit(false) .format(0); @@ -911,35 +763,34 @@ fn make_prog_line(update: &ProgUpdate) -> String .get_appropriate_unit(false) .format(1); - format!("{} bytes ({}, {}) copied, {:.1} s, {}/s", - update.bytes_total, - btotal_metric, - btotal_bin, - update.duration.as_secs_f64(), - xfer_rate - ).to_string() + format!( + "{} bytes ({}, {}) copied, {:.1} s, {}/s", + update.bytes_total, + btotal_metric, + btotal_bin, + update.duration.as_secs_f64(), + xfer_rate + ) + .to_string() } -fn reprint_prog_line(update: &ProgUpdate) -{ +fn reprint_prog_line(update: &ProgUpdate) { eprint!("\r{}", make_prog_line(update)); } -fn print_prog_line(update: &ProgUpdate) -{ +fn print_prog_line(update: &ProgUpdate) { eprintln!("{}", make_prog_line(update)); } -fn print_xfer_stats(update: &ProgUpdate) -{ +fn print_xfer_stats(update: &ProgUpdate) { print_io_lines(update); print_prog_line(update); - } /// Generate a progress updater that tracks progress, receives updates, and responds to signals. -fn gen_prog_updater(rx: mpsc::Receiver, xfer_stats: Option) -> impl Fn() -> () -{ +fn gen_prog_updater( + rx: mpsc::Receiver, + xfer_stats: Option, +) -> impl Fn() -> () { // -------------------------------------------------------------- - fn posixly_correct() -> bool - { + fn posixly_correct() -> bool { env::var("POSIXLY_CORRECT").is_ok() } // -------------------------------------------------------------- @@ -956,41 +807,38 @@ fn gen_prog_updater(rx: mpsc::Receiver, xfer_stats: Option - { + let update = match (rx.recv(), xfer_stats) { + (Ok(update), Some(StatusLevel::Progress)) => { reprint_prog_line(&update); update - }, - (Ok(update), _) => - { - update - }, + } + (Ok(update), _) => update, (Err(_), _) => - // recv only fails permenantly - break, + // recv only fails permenantly + { + break + } }; // Handle signals - match sigval.load(Ordering::Relaxed) - { - SIGUSR1_USIZE => - { + match sigval.load(Ordering::Relaxed) { + SIGUSR1_USIZE => { print_xfer_stats(&update); - }, - _ => {/* no signals recv'd */}, + } + _ => { /* no signals recv'd */ } }; } } @@ -1002,66 +850,60 @@ fn gen_prog_updater(rx: mpsc::Receiver, xfer_stats: Option usize -{ +fn calc_bsize(ibs: usize, obs: usize) -> usize { let gcd = Gcd::gcd(ibs, obs); - let lcm = (ibs/gcd)*obs; + let lcm = (ibs / gcd) * obs; lcm } /// Calculate the buffer size appropriate for this loop iteration, respecting /// a count=N if present. -fn calc_loop_bsize(count: &Option, rstat: &ReadStat, wstat: &WriteStat, ibs: usize, ideal_bsize: usize) -> usize -{ - match count - { - Some(CountType::Reads(rmax)) => - { +fn calc_loop_bsize( + count: &Option, + rstat: &ReadStat, + wstat: &WriteStat, + ibs: usize, + ideal_bsize: usize, +) -> usize { + match count { + Some(CountType::Reads(rmax)) => { let rmax: u64 = (*rmax).try_into().unwrap(); let rsofar = rstat.reads_complete + rstat.reads_partial; let rremain: usize = (rmax - rsofar).try_into().unwrap(); - cmp::min(ideal_bsize, rremain*ibs) - }, - Some(CountType::Bytes(bmax)) => - { + cmp::min(ideal_bsize, rremain * ibs) + } + Some(CountType::Bytes(bmax)) => { let bmax: u128 = (*bmax).try_into().unwrap(); let bremain: usize = (bmax - wstat.bytes_total).try_into().unwrap(); cmp::min(ideal_bsize, bremain) - }, - None => - ideal_bsize, + } + None => ideal_bsize, } } /// Decide if the current progress is below a count=N limit or return /// true if no such limit is set. -fn below_count_limit(count: &Option, rstat: &ReadStat, wstat: &WriteStat) -> bool -{ - match count - { - Some(CountType::Reads(n)) => - { +fn below_count_limit(count: &Option, rstat: &ReadStat, wstat: &WriteStat) -> bool { + match count { + Some(CountType::Reads(n)) => { let n = (*n).try_into().unwrap(); // debug_assert!(rstat.reads_complete + rstat.reads_partial >= n); rstat.reads_complete + rstat.reads_partial <= n - }, - Some(CountType::Bytes(n)) => - { + } + Some(CountType::Bytes(n)) => { let n = (*n).try_into().unwrap(); // debug_assert!(wstat.bytes_total >= n); wstat.bytes_total <= n - }, - None => - true, + } + None => true, } } /// Perform the copy/convert opertaions. Stdout version // Note: Some of dd's functionality depends on whether the output is actually a file. This breaks the Output abstraction, // and should be fixed in the future. -fn dd_stdout(mut i: Input, mut o: Output) -> Result<(), Box> -{ +fn dd_stdout(mut i: Input, mut o: Output) -> Result<(), Box> { let mut rstat = ReadStat { reads_complete: 0, reads_partial: 0, @@ -1081,100 +923,24 @@ fn dd_stdout(mut i: Input, mut o: Output) -> Result<(), tx }; - while below_count_limit(&i.count, &rstat, &wstat) - { + while below_count_limit(&i.count, &rstat, &wstat) { // Read/Write let loop_bsize = calc_loop_bsize(&i.count, &rstat, &wstat, i.ibs, bsize); - match read_helper(&mut i, loop_bsize)? - { - (ReadStat { reads_complete: 0, reads_partial: 0, .. }, _) => - break, - (rstat_update, buf) => - { + match read_helper(&mut i, loop_bsize)? { + ( + ReadStat { + reads_complete: 0, + reads_partial: 0, + .. + }, + _, + ) => break, + (rstat_update, buf) => { let wstat_update = o.write_blocks(buf)?; rstat += rstat_update; wstat += wstat_update; - }, - }; - // Update Prog - prog_tx.send(ProgUpdate { - reads_complete: rstat.reads_complete, - reads_partial: rstat.reads_partial, - writes_complete: wstat.writes_complete, - writes_partial: wstat.writes_partial, - bytes_total: wstat.bytes_total, - records_truncated: rstat.records_truncated, - duration: start.elapsed(), - })?; - } - - if o.cflags.fsync - { - o.fsync()?; - } - else if o.cflags.fdatasync - { - o.fdatasync()?; - } - - match i.xfer_stats - { - Some(StatusLevel::Noxfer) | - Some(StatusLevel::None) => {}, - _ => - print_xfer_stats(&ProgUpdate { - reads_complete: rstat.reads_complete, - reads_partial: rstat.reads_partial, - writes_complete: wstat.writes_complete, - writes_partial: wstat.writes_partial, - bytes_total: wstat.bytes_total, - records_truncated: rstat.records_truncated, - duration: start.elapsed(), - }), - } - Ok(()) -} - -/// Perform the copy/convert opertaions. File backed output version -// Note: Some of dd's functionality depends on whether the output is actually a file. This breaks the Output abstraction, -// and should be fixed in the future. -fn dd_fileout(mut i: Input, mut o: Output) -> Result<(), Box> -{ - let mut rstat = ReadStat { - reads_complete: 0, - reads_partial: 0, - records_truncated: 0, - }; - let mut wstat = WriteStat { - writes_complete: 0, - writes_partial: 0, - bytes_total: 0, - }; - let start = time::Instant::now(); - let bsize = calc_bsize(i.ibs, o.obs); - - let prog_tx = { - let (tx, rx) = mpsc::channel(); - thread::spawn(gen_prog_updater(rx, i.xfer_stats)); - tx - }; - - while below_count_limit(&i.count, &rstat, &wstat) - { - // Read/Write - let loop_bsize = calc_loop_bsize(&i.count, &rstat, &wstat, i.ibs, bsize); - match read_helper(&mut i, loop_bsize)? - { - (ReadStat { reads_complete: 0, reads_partial: 0, .. }, _) => - break, - (rstat_update, buf) => - { - let wstat_update = o.write_blocks(buf)?; - - rstat += rstat_update; - wstat += wstat_update; - }, + } }; // Update Prog prog_tx.send(ProgUpdate { @@ -1188,36 +954,103 @@ fn dd_fileout(mut i: Input, mut o: Output) -> Result<(), Box {}, - _ => - print_xfer_stats(&ProgUpdate { - reads_complete: rstat.reads_complete, - reads_partial: rstat.reads_partial, - writes_complete: wstat.writes_complete, - writes_partial: wstat.writes_partial, - bytes_total: wstat.bytes_total, - records_truncated: rstat.records_truncated, - duration: start.elapsed(), - }), + match i.xfer_stats { + Some(StatusLevel::Noxfer) | Some(StatusLevel::None) => {} + _ => print_xfer_stats(&ProgUpdate { + reads_complete: rstat.reads_complete, + reads_partial: rstat.reads_partial, + writes_complete: wstat.writes_complete, + writes_partial: wstat.writes_partial, + bytes_total: wstat.bytes_total, + records_truncated: rstat.records_truncated, + duration: start.elapsed(), + }), } Ok(()) } +/// Perform the copy/convert opertaions. File backed output version +// Note: Some of dd's functionality depends on whether the output is actually a file. This breaks the Output abstraction, +// and should be fixed in the future. +fn dd_fileout(mut i: Input, mut o: Output) -> Result<(), Box> { + let mut rstat = ReadStat { + reads_complete: 0, + reads_partial: 0, + records_truncated: 0, + }; + let mut wstat = WriteStat { + writes_complete: 0, + writes_partial: 0, + bytes_total: 0, + }; + let start = time::Instant::now(); + let bsize = calc_bsize(i.ibs, o.obs); -fn append_dashes_if_not_present(mut acc: Vec, s: &String) -> Vec -{ + let prog_tx = { + let (tx, rx) = mpsc::channel(); + thread::spawn(gen_prog_updater(rx, i.xfer_stats)); + tx + }; + + while below_count_limit(&i.count, &rstat, &wstat) { + // Read/Write + let loop_bsize = calc_loop_bsize(&i.count, &rstat, &wstat, i.ibs, bsize); + match read_helper(&mut i, loop_bsize)? { + ( + ReadStat { + reads_complete: 0, + reads_partial: 0, + .. + }, + _, + ) => break, + (rstat_update, buf) => { + let wstat_update = o.write_blocks(buf)?; + + rstat += rstat_update; + wstat += wstat_update; + } + }; + // Update Prog + prog_tx.send(ProgUpdate { + reads_complete: rstat.reads_complete, + reads_partial: rstat.reads_partial, + writes_complete: wstat.writes_complete, + writes_partial: wstat.writes_partial, + bytes_total: wstat.bytes_total, + records_truncated: rstat.records_truncated, + duration: start.elapsed(), + })?; + } + + if o.cflags.fsync { + o.fsync()?; + } else if o.cflags.fdatasync { + o.fdatasync()?; + } + + match i.xfer_stats { + Some(StatusLevel::Noxfer) | Some(StatusLevel::None) => {} + _ => print_xfer_stats(&ProgUpdate { + reads_complete: rstat.reads_complete, + reads_partial: rstat.reads_partial, + writes_complete: wstat.writes_complete, + writes_partial: wstat.writes_partial, + bytes_total: wstat.bytes_total, + records_truncated: rstat.records_truncated, + duration: start.elapsed(), + }), + } + Ok(()) +} + +fn append_dashes_if_not_present(mut acc: Vec, s: &String) -> Vec { if Some("--") == s.get(0..=1) { acc } else { @@ -1247,12 +1080,12 @@ macro_rules! unpack_or_rtn ( }}; ); -pub fn uumain(args: impl uucore::Args) -> i32 -{ - let dashed_args = args.collect_str(InvalidEncodingHandling::Ignore) - .accept_any() - .iter() - .fold(Vec::new(), append_dashes_if_not_present); +pub fn uumain(args: impl uucore::Args) -> i32 { + let dashed_args = args + .collect_str(InvalidEncodingHandling::Ignore) + .accept_any() + .iter() + .fold(Vec::new(), append_dashes_if_not_present); let matches = build_dd_app!() // TODO: usage, after_help @@ -1260,49 +1093,51 @@ pub fn uumain(args: impl uucore::Args) -> i32 //.after_help(...) .get_matches_from(dashed_args); - let result = match (matches.is_present(options::INFILE), matches.is_present(options::OUTFILE)) - { - (true, true) => - { - let (i, o) = unpack_or_rtn!(Input::::new(&matches), Output::::new(&matches)); + let result = match ( + matches.is_present(options::INFILE), + matches.is_present(options::OUTFILE), + ) { + (true, true) => { + let (i, o) = + unpack_or_rtn!(Input::::new(&matches), Output::::new(&matches)); - dd_fileout(i,o) - }, - (false, true) => - { - let (i, o) = unpack_or_rtn!(Input::::new(&matches), Output::::new(&matches)); + dd_fileout(i, o) + } + (false, true) => { + let (i, o) = unpack_or_rtn!( + Input::::new(&matches), + Output::::new(&matches) + ); - dd_fileout(i,o) - }, - (true, false) => - { - let (i, o) = unpack_or_rtn!(Input::::new(&matches), Output::::new(&matches)); + dd_fileout(i, o) + } + (true, false) => { + let (i, o) = unpack_or_rtn!( + Input::::new(&matches), + Output::::new(&matches) + ); - dd_stdout(i,o) - }, - (false, false) => - { - let (i, o) = unpack_or_rtn!(Input::::new(&matches), Output::::new(&matches)); + dd_stdout(i, o) + } + (false, false) => { + let (i, o) = unpack_or_rtn!( + Input::::new(&matches), + Output::::new(&matches) + ); - dd_stdout(i,o) - }, + dd_stdout(i, o) + } }; - match result - { - Ok(_) => - { - RTN_SUCCESS - }, - Err(e) => - { + match result { + Ok(_) => RTN_SUCCESS, + Err(e) => { debug_println!("dd exiting with error:\n\t{}", e); RTN_FAILURE - }, + } } } -pub fn uu_app() -> clap::App<'static, 'static> -{ +pub fn uu_app() -> clap::App<'static, 'static> { build_dd_app!() } @@ -1341,7 +1176,7 @@ macro_rules! build_dd_app ( clap::Arg::with_name(options::BS) .long(options::BS) .takes_value(true) - .help("bs=N (alternatively --bs N) specifies ibs=N and obs=N (default: 512). If ibs or obs are also specified, bs=N takes presedence. Multiplier strings permitted.") + .help("bs=N (alternatively --bs N) specifies ibs=N and obs=N (default: 512). If ibs or obs are also specified, bs=N takes precedence. Multiplier strings permitted.") ) .arg( clap::Arg::with_name(options::CBS) @@ -1353,25 +1188,25 @@ macro_rules! build_dd_app ( clap::Arg::with_name(options::SKIP) .long(options::SKIP) .takes_value(true) - .help("skip=N (alternatively --skip N) causes N ibs-sized records of input to be skipped before beginning copy/convert operations. See iflag=count_bytes if skipping N bytes is prefered. Multiplier strings permitted.") + .help("skip=N (alternatively --skip N) causes N ibs-sized records of input to be skipped before beginning copy/convert operations. See iflag=count_bytes if skipping N bytes is preferred. Multiplier strings permitted.") ) .arg( clap::Arg::with_name(options::SEEK) .long(options::SEEK) .takes_value(true) - .help("seek=N (alternatively --seek N) seeks N obs-sized records into output before beginning copy/convert operations. See oflag=seek_bytes if seeking N bytes is prefered. Multiplier strings permitted.") + .help("seek=N (alternatively --seek N) seeks N obs-sized records into output before beginning copy/convert operations. See oflag=seek_bytes if seeking N bytes is preferred. Multiplier strings permitted.") ) .arg( clap::Arg::with_name(options::COUNT) .long(options::COUNT) .takes_value(true) - .help("count=N (alternatively --count N) stop reading input after N ibs-sized read operations rather than proceeding until EOF. See iflag=count_bytes if stopping after N bytes is prefered. Multiplier strings permitted.") + .help("count=N (alternatively --count N) stop reading input after N ibs-sized read operations rather than proceeding until EOF. See iflag=count_bytes if stopping after N bytes is preferred. Multiplier strings permitted.") ) .arg( clap::Arg::with_name(options::STATUS) .long(options::STATUS) .takes_value(true) - .help("status=LEVEL (alternatively --status LEVEL) controls whether volume and performace stats are written to stderr. + .help("status=LEVEL (alternatively --status LEVEL) controls whether volume and performance stats are written to stderr. When unspecified, dd will print stats upon completion. An example is below. \t6+0 records in @@ -1380,12 +1215,13 @@ When unspecified, dd will print stats upon completion. An example is below. The first two lines are the 'volume' stats and the final line is the 'performance' stats. The volume stats indicate the number of complete and partial ibs-sized reads, or obs-sized writes that took place during the copy. The format of the volume stats is +. If records have been truncated (see conv=block), the volume stats will contain the number of truncated records. -Permissable LEVEL values are: -\t- progress: Print periodic performance stats as the copy proceedes. -\t- noxfer: Print final volume stats, but not performance stats. -\t- none: Do not print any stats. +Permissible LEVEL values are: +\t progress: Print periodic performance stats as the copy proceeds. +\t noxfer: Print final volume stats, but not performance stats. +\t none: Do not print any stats. + +Printing performance stats is also triggered by the INFO signal (where supported), or the USR1 signal. Setting the POSIXLY_CORRECT environment variable to any value (including an empty value) will cause the USR1 signal to be ignored. -Printing performance stats is also triggered by the INFO signal (where supported), or the USR1 signal. Setting the POSIXLY_CORRECT evnironment variable to any value (including an empty value) will cause the USR1 signal to be ignored. ") ) .arg( @@ -1395,31 +1231,32 @@ Printing performance stats is also triggered by the INFO signal (where supported .help("conv=CONV[,CONV] (alternatively --conv CONV[,CONV]) specifies a comma-separated list of conversion options or (for legacy reasons) file-flags. Conversion options and file flags may be intermixed. Conversion options: -\t- One of {ascii, ebcdic, ibm} will perform an encoding conversion. -\t\t- 'ascii' converts from EBCDIC to ASCII. This is the inverse of the 'ebcdic' option. -\t\t- 'ebcdic' converts from ASCII to EBCDIC. This is the inverse of the 'ascii' option. -\t\t- 'ibm' converts from ASCII to EBCDIC, appling the conventions for '[', ']' and '~' specified in POSIX. +\t One of {ascii, ebcdic, ibm} will perform an encoding conversion. +\t\t 'ascii' converts from EBCDIC to ASCII. This is the inverse of the 'ebcdic' option. +\t\t 'ebcdic' converts from ASCII to EBCDIC. This is the inverse of the 'ascii' option. +\t\t 'ibm' converts from ASCII to EBCDIC, applying the conventions for '[', ']' and '~' specified in POSIX. -\t- One of {ucase, lcase} will perform a case conversion. Works in conjuction with option {ascii, ebcdic, ibm} to infer input encoding. If no other conversion option is specified, input is assumed to be ascii. -\t\t- 'ucase' converts from lower-case to upper-case -\t\t- 'lcase' converts from upper-case to lower-case. +\t One of {ucase, lcase} will perform a case conversion. Works in conjunction with option {ascii, ebcdic, ibm} to infer input encoding. If no other conversion option is specified, input is assumed to be ascii. +\t\t 'ucase' converts from lower-case to upper-case +\t\t 'lcase' converts from upper-case to lower-case. -\t- One of {block, unblock}. Convert between lines terminated by newline characters, and fixed-width lines padded by spaces (without any newlines). Both the 'block' and 'unblock' options require cbs=BYTES be specified. -\t\t- 'block' for each newline less than the size indicated by cbs=BYTES, remove the newline and pad with spaces up to cbs. Lines longer than cbs are truncated. -\t\t- 'unblock' for each block of input of the size indicated by cbs=BYTES, remove right-trailing spaces and replace with a newline character. +\t One of {block, unblock}. Convert between lines terminated by newline characters, and fixed-width lines padded by spaces (without any newlines). Both the 'block' and 'unblock' options require cbs=BYTES be specified. +\t\t 'block' for each newline less than the size indicated by cbs=BYTES, remove the newline and pad with spaces up to cbs. Lines longer than cbs are truncated. +\t\t 'unblock' for each block of input of the size indicated by cbs=BYTES, remove right-trailing spaces and replace with a newline character. \t 'sparse' attempts to seek the output when an obs-sized block consists of only zeros. \t 'swab' swaps each adjacent pair of bytes. If an odd number of bytes is present, the final byte is omitted. \t 'sync' pad each ibs-sided block with zeros. If 'block' or 'unblock' is specified, pad with spaces instead. Flags: -\t- One of {excl, nocreat} -\t\t- 'excl' the output file must be created. Fail if the output file is already present. -\t\t- 'nocreat' the output file will not be created. Fail if the output file in not already present. -\t- 'notrunc' the output file will not be truncated. If this option is not present, output will be truncated when opened. -\t- 'noerror' all read errors will be ignored. If this option is not present, dd will only ignore Error::Interrupted. -\t- 'fdatasync' data will be written before finishing. -\t- 'fsync' data and metadata will be written before finishing. +\t One of {excl, nocreat} +\t\t 'excl' the output file must be created. Fail if the output file is already present. +\t\t 'nocreat' the output file will not be created. Fail if the output file in not already present. +\t 'notrunc' the output file will not be truncated. If this option is not present, output will be truncated when opened. +\t 'noerror' all read errors will be ignored. If this option is not present, dd will only ignore Error::Interrupted. +\t 'fdatasync' data will be written before finishing. +\t 'fsync' data and metadata will be written before finishing. + ") ) .arg( @@ -1429,24 +1266,25 @@ Flags: .help("iflag=FLAG[,FLAG] (alternatively --iflag FLAG[,FLAG]) a comma separated list of input flags which specify how the input source is treated. FLAG may be any of the input-flags or general-flags specified below. Input-Flags -\t- 'count_bytes' a value to count=N will be interpreted as bytes. -\t- 'skip_bytes' a value to skip=N will be interpreted as bytes. -\t- 'fullblock' wait for ibs bytes from each read. zero-length reads are still considered EOF. +\t 'count_bytes' a value to count=N will be interpreted as bytes. +\t 'skip_bytes' a value to skip=N will be interpreted as bytes. +\t 'fullblock' wait for ibs bytes from each read. zero-length reads are still considered EOF. General-Flags -\t- 'direct' -\t- 'directory' -\t- 'dsync' -\t- 'sync' -\t- 'nonblock' -\t- 'noatime' -\t- 'nocache' -\t- 'noctty' -\t- 'nofollow' +\t 'direct' use direct I/O for data. +\t 'directory' fail unless the given input (if used as an iflag) or output (if used as an oflag) is a directory. +\t 'dsync' use syncronized I/O for data. +\t 'sync' use syncronized I/O for data and metadata. +\t 'nonblock' use non-blocking I/O. +\t 'noatime' do not update access time. +\t 'nocache' request that OS drop cache. +\t 'noctty' do not assign a controlling tty. +\t 'nofollow' do not follow system links. Output-Flags -\t- 'append' open file in append mode. Consider setting conv=notrunc as well. -\t- 'seek_bytes' a value to seek=N will be interpreted as bytes. +\t 'append' open file in append mode. Consider setting conv=notrunc as well. +\t 'seek_bytes' a value to seek=N will be interpreted as bytes. + ") ) .arg( @@ -1456,19 +1294,20 @@ Output-Flags .help("oflag=FLAG[,FLAG] (alternatively --oflag FLAG[,FLAG]) a comma separated list of output flags which specify how the output source is treated. FLAG may be any of the output-flags or general-flags specified below. Output-Flags -\t- 'append' open file in append mode. Consider setting conv=notrunc as well. -\t- 'seek_bytes' a value to seek=N will be interpreted as bytes. +\t 'append' open file in append mode. Consider setting conv=notrunc as well. +\t 'seek_bytes' a value to seek=N will be interpreted as bytes. General-Flags -\t- 'direct' -\t- 'directory' -\t- 'dsync' -\t- 'sync' -\t- 'nonblock' -\t- 'noatime' -\t- 'nocache' -\t- 'noctty' -\t- 'nofollow' +\t 'direct' use direct I/O for data. +\t 'directory' fail unless the given input (if used as an iflag) or output (if used as an oflag) is a directory. +\t 'dsync' use syncronized I/O for data. +\t 'sync' use syncronized I/O for data and metadata. +\t 'nonblock' use non-blocking I/O. +\t 'noatime' do not update access time. +\t 'nocache' request that OS drop cache. +\t 'noctty' do not assign a controlling tty. +\t 'nofollow' do not follow system links. + ") ) }; diff --git a/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs b/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs index eba49f9d0..f52d68fd0 100644 --- a/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs +++ b/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs @@ -81,176 +81,176 @@ macro_rules! make_unblock_test ( ); #[test] -fn block_test_no_nl() -{ +fn block_test_no_nl() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8], - ]); + assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]); } #[test] -fn block_test_no_nl_short_record() -{ +fn block_test_no_nl_short_record() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8]; let res = block(buf, 8, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE],] + ); } #[test] -fn block_test_no_nl_trunc() -{ +fn block_test_no_nl_trunc() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8/*, 4u8*/], - ]); + assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8 /*, 4u8*/],]); assert_eq!(rs.records_truncated, 1); } #[test] -fn block_test_nl_gt_cbs_trunc() -{ +fn block_test_nl_gt_cbs_trunc() { let mut rs = rs!(); - let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8, NL, 0u8, 1u8, 2u8, 3u8, 4u8, NL, 5u8, 6u8, 7u8, 8u8]; + let buf = vec![ + 0u8, 1u8, 2u8, 3u8, 4u8, NL, 0u8, 1u8, 2u8, 3u8, 4u8, NL, 5u8, 6u8, 7u8, 8u8, + ]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8], - // vec![4u8, SPACE, SPACE, SPACE], - vec![0u8, 1u8, 2u8, 3u8], - // vec![4u8, SPACE, SPACE, SPACE], - vec![5u8, 6u8, 7u8, 8u8], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8], + // vec![4u8, SPACE, SPACE, SPACE], + vec![0u8, 1u8, 2u8, 3u8], + // vec![4u8, SPACE, SPACE, SPACE], + vec![5u8, 6u8, 7u8, 8u8], + ] + ); assert_eq!(rs.records_truncated, 2); } #[test] -fn block_test_surrounded_nl() -{ +fn block_test_surrounded_nl() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL, 4u8, 5u8, 6u8, 7u8, 8u8]; let res = block(buf, 8, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - vec![4u8, 5u8, 6u8, 7u8, 8u8, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], + vec![4u8, 5u8, 6u8, 7u8, 8u8, SPACE, SPACE, SPACE], + ] + ); } #[test] -fn block_test_multiple_nl_same_cbs_block() -{ +fn block_test_multiple_nl_same_cbs_block() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL, 4u8, NL, 5u8, 6u8, 7u8, 8u8, 9u8]; let res = block(buf, 8, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - vec![4u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], - vec![5u8, 6u8, 7u8, 8u8, 9u8, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], + vec![4u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], + vec![5u8, 6u8, 7u8, 8u8, 9u8, SPACE, SPACE, SPACE], + ] + ); } #[test] -fn block_test_multiple_nl_diff_cbs_block() -{ +fn block_test_multiple_nl_diff_cbs_block() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL, 4u8, 5u8, 6u8, 7u8, NL, 8u8, 9u8]; let res = block(buf, 8, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - vec![4u8, 5u8, 6u8, 7u8, SPACE, SPACE, SPACE, SPACE], - vec![8u8, 9u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], + vec![4u8, 5u8, 6u8, 7u8, SPACE, SPACE, SPACE, SPACE], + vec![8u8, 9u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], + ] + ); } #[test] -fn block_test_end_nl_diff_cbs_block() -{ +fn block_test_end_nl_diff_cbs_block() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8], - ]); + assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]); } #[test] -fn block_test_end_nl_same_cbs_block() -{ +fn block_test_end_nl_same_cbs_block() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, NL]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, SPACE] - ]); + assert_eq!(res, vec![vec![0u8, 1u8, 2u8, SPACE]]); } #[test] -fn block_test_double_end_nl() -{ +fn block_test_double_end_nl() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, NL, NL]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, SPACE], - vec![SPACE, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![vec![0u8, 1u8, 2u8, SPACE], vec![SPACE, SPACE, SPACE, SPACE],] + ); } #[test] -fn block_test_start_nl() -{ +fn block_test_start_nl() { let mut rs = rs!(); let buf = vec![NL, 0u8, 1u8, 2u8, 3u8]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![SPACE, SPACE, SPACE, SPACE], - vec![0u8, 1u8, 2u8, 3u8], - ]); + assert_eq!( + res, + vec![vec![SPACE, SPACE, SPACE, SPACE], vec![0u8, 1u8, 2u8, 3u8],] + ); } #[test] -fn block_test_double_surrounded_nl_no_trunc() -{ +fn block_test_double_surrounded_nl_no_trunc() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL, NL, 4u8, 5u8, 6u8, 7u8]; let res = block(buf, 8, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - vec![SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], - vec![4u8, 5u8, 6u8, 7u8, SPACE, SPACE, SPACE, SPACE], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], + vec![SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], + vec![4u8, 5u8, 6u8, 7u8, SPACE, SPACE, SPACE, SPACE], + ] + ); } #[test] -fn block_test_double_surrounded_nl_double_trunc() -{ +fn block_test_double_surrounded_nl_double_trunc() { let mut rs = rs!(); let buf = vec![0u8, 1u8, 2u8, 3u8, NL, NL, 4u8, 5u8, 6u8, 7u8, 8u8]; let res = block(buf, 4, &mut rs); - assert_eq!(res, vec![ - vec![0u8, 1u8, 2u8, 3u8], - vec![SPACE, SPACE, SPACE, SPACE], - vec![4u8, 5u8, 6u8, 7u8/*, 8u8*/], - ]); + assert_eq!( + res, + vec![ + vec![0u8, 1u8, 2u8, 3u8], + vec![SPACE, SPACE, SPACE, SPACE], + vec![4u8, 5u8, 6u8, 7u8 /*, 8u8*/], + ] + ); assert_eq!(rs.records_truncated, 1); } @@ -279,58 +279,51 @@ make_block_test!( ); #[test] -fn unblock_test_full_cbs() -{ +fn unblock_test_full_cbs() { let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8]; let res = unblock(buf, 8); - assert_eq!(res, - vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, NL], - ); + assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, NL],); } #[test] -fn unblock_test_all_space() -{ +fn unblock_test_all_space() { let buf = vec![SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE]; let res = unblock(buf, 8); - assert_eq!(res, - vec![NL], - ); + assert_eq!(res, vec![NL],); } #[test] -fn unblock_test_decoy_spaces() -{ +fn unblock_test_decoy_spaces() { let buf = vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8]; let res = unblock(buf, 8); - assert_eq!(res, - vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8, NL], + assert_eq!( + res, + vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8, NL], ); } #[test] -fn unblock_test_strip_single_cbs() -{ +fn unblock_test_strip_single_cbs() { let buf = vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE]; let res = unblock(buf, 8); - assert_eq!(res, - vec![0u8, 1u8, 2u8, 3u8, NL], - ); + assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, NL],); } #[test] -fn unblock_test_strip_multi_cbs() -{ +fn unblock_test_strip_multi_cbs() { let buf = vec![ vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], vec![0u8, 1u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE], vec![0u8, 1u8, 2u8, SPACE, SPACE, SPACE, SPACE, SPACE], vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE], - ].into_iter().flatten().collect::>(); + ] + .into_iter() + .flatten() + .collect::>(); let res = unblock(buf, 8); @@ -339,7 +332,10 @@ fn unblock_test_strip_multi_cbs() vec![0u8, 1u8, NL], vec![0u8, 1u8, 2u8, NL], vec![0u8, 1u8, 2u8, 3u8, NL], - ].into_iter().flatten().collect::>(); + ] + .into_iter() + .flatten() + .collect::>(); assert_eq!(res, exp); } diff --git a/src/uu/dd/src/dd_unit_tests/conv_sync_tests.rs b/src/uu/dd/src/dd_unit_tests/conv_sync_tests.rs index 2195b1b84..177aee1a5 100644 --- a/src/uu/dd/src/dd_unit_tests/conv_sync_tests.rs +++ b/src/uu/dd/src/dd_unit_tests/conv_sync_tests.rs @@ -99,7 +99,9 @@ make_sync_test!( make_sync_test!( deadbeef_16_delayed, "deadbeef-16-delayed", - LazyReader { src: File::open("./test-resources/deadbeef-16.test").unwrap() }, + LazyReader { + src: File::open("./test-resources/deadbeef-16.test").unwrap() + }, Some(0u8), 16, 32, diff --git a/src/uu/dd/src/dd_unit_tests/conversion_tests.rs b/src/uu/dd/src/dd_unit_tests/conversion_tests.rs index a1a7ad892..e9f17e8d4 100644 --- a/src/uu/dd/src/dd_unit_tests/conversion_tests.rs +++ b/src/uu/dd/src/dd_unit_tests/conversion_tests.rs @@ -129,14 +129,16 @@ make_conv_test!( ); #[test] -fn all_valid_ascii_ebcdic_ascii_roundtrip_conv_test() -{ +fn all_valid_ascii_ebcdic_ascii_roundtrip_conv_test() { // ASCII->EBCDIC let test_name = "all-valid-ascii-to-ebcdic"; let tmp_fname_ae = format!("./test-resources/FAILED-{}.test", test_name); let i = Input { - src: File::open("./test-resources/all-valid-ascii-chars-37eff01866ba3f538421b30b7cbefcac.test").unwrap(), + src: File::open( + "./test-resources/all-valid-ascii-chars-37eff01866ba3f538421b30b7cbefcac.test", + ) + .unwrap(), non_ascii: false, ibs: 128, xfer_stats: None, @@ -152,7 +154,7 @@ fn all_valid_ascii_ebcdic_ascii_roundtrip_conv_test() oflags: DEFAULT_OFLAGS, }; - dd_fileout(i,o).unwrap(); + dd_fileout(i, o).unwrap(); // EBCDIC->ASCII let test_name = "all-valid-ebcdic-to-ascii"; @@ -175,13 +177,18 @@ fn all_valid_ascii_ebcdic_ascii_roundtrip_conv_test() oflags: DEFAULT_OFLAGS, }; - dd_fileout(i,o).unwrap(); + dd_fileout(i, o).unwrap(); // Final Comparison let res = File::open(&tmp_fname_ea).unwrap(); - let spec = File::open("./test-resources/all-valid-ascii-chars-37eff01866ba3f538421b30b7cbefcac.test").unwrap(); + let spec = + File::open("./test-resources/all-valid-ascii-chars-37eff01866ba3f538421b30b7cbefcac.test") + .unwrap(); - assert_eq!(res.metadata().unwrap().len(), spec.metadata().unwrap().len()); + assert_eq!( + res.metadata().unwrap().len(), + spec.metadata().unwrap().len() + ); let res = BufReader::new(res); let spec = BufReader::new(spec); @@ -189,10 +196,8 @@ fn all_valid_ascii_ebcdic_ascii_roundtrip_conv_test() let res = BufReader::new(res); // Check all bytes match - for (b_res, b_spec) in res.bytes().zip(spec.bytes()) - { - assert_eq!(b_res.unwrap(), - b_spec.unwrap()); + for (b_res, b_spec) in res.bytes().zip(spec.bytes()) { + assert_eq!(b_res.unwrap(), b_spec.unwrap()); } fs::remove_file(&tmp_fname_ae).unwrap(); diff --git a/src/uu/dd/src/dd_unit_tests/mod.rs b/src/uu/dd/src/dd_unit_tests/mod.rs index cb514e33d..a1780204c 100644 --- a/src/uu/dd/src/dd_unit_tests/mod.rs +++ b/src/uu/dd/src/dd_unit_tests/mod.rs @@ -1,13 +1,13 @@ use super::*; -mod sanity_tests; -mod conversion_tests; mod block_unblock_tests; mod conv_sync_tests; +mod conversion_tests; +mod sanity_tests; +use std::fs; use std::io::prelude::*; use std::io::BufReader; -use std::fs; const DEFAULT_CFO: OConvFlags = OConvFlags { sparse: false, @@ -55,15 +55,12 @@ const DEFAULT_OFLAGS: OFlags = OFlags { seek_bytes: false, }; -struct LazyReader -{ +struct LazyReader { src: R, } -impl Read for LazyReader -{ - fn read(&mut self, buf: &mut [u8]) -> io::Result - { +impl Read for LazyReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { let reduced = cmp::max(buf.len() / 2, 1); self.src.read(&mut buf[..reduced]) } @@ -143,4 +140,3 @@ macro_rules! make_spec_test ( } }; ); - diff --git a/src/uu/dd/src/dd_unit_tests/sanity_tests.rs b/src/uu/dd/src/dd_unit_tests/sanity_tests.rs index f423af212..2024ea12e 100644 --- a/src/uu/dd/src/dd_unit_tests/sanity_tests.rs +++ b/src/uu/dd/src/dd_unit_tests/sanity_tests.rs @@ -115,7 +115,7 @@ make_io_test!( non_ascii: false, ibs: 531, xfer_stats: None, - count: Some(CountType::Bytes(32*1024)), + count: Some(CountType::Bytes(32 * 1024)), cflags: icf!(), iflags: DEFAULT_IFLAGS, }, @@ -199,7 +199,7 @@ make_io_test!( non_ascii: false, ibs: 521, xfer_stats: None, - count: Some(CountType::Bytes(32*1024)), + count: Some(CountType::Bytes(32 * 1024)), cflags: icf!(), iflags: DEFAULT_IFLAGS, }, @@ -217,7 +217,8 @@ make_io_test!( "random-73k-test-lazy-fullblock", Input { src: LazyReader { - src: File::open("./test-resources/random-5828891cb1230748e146f34223bbd3b5.test").unwrap() + src: File::open("./test-resources/random-5828891cb1230748e146f34223bbd3b5.test") + .unwrap() }, non_ascii: false, ibs: 521, @@ -254,53 +255,48 @@ make_io_test!( // Test internal buffer size fn #[test] -fn bsize_test_primes() -{ - let (n,m) = (7901, 7919); +fn bsize_test_primes() { + let (n, m) = (7901, 7919); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); - assert_eq!(res, n*m); + assert_eq!(res, n * m); } #[test] -fn bsize_test_rel_prime_obs_greater() -{ - let (n,m) = (7*5119, 13*5119); +fn bsize_test_rel_prime_obs_greater() { + let (n, m) = (7 * 5119, 13 * 5119); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); - assert_eq!(res, 7*13*5119); + assert_eq!(res, 7 * 13 * 5119); } #[test] -fn bsize_test_rel_prime_ibs_greater() -{ - let (n,m) = (13*5119, 7*5119); +fn bsize_test_rel_prime_ibs_greater() { + let (n, m) = (13 * 5119, 7 * 5119); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); - assert_eq!(res, 7*13*5119); + assert_eq!(res, 7 * 13 * 5119); } #[test] -fn bsize_test_3fac_rel_prime() -{ - let (n,m) = (11*13*5119, 7*11*5119); +fn bsize_test_3fac_rel_prime() { + let (n, m) = (11 * 13 * 5119, 7 * 11 * 5119); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); - assert_eq!(res, 7*11*13*5119); + assert_eq!(res, 7 * 11 * 13 * 5119); } #[test] -fn bsize_test_ibs_greater() -{ - let (n,m) = (512*1024, 256*1024); +fn bsize_test_ibs_greater() { + let (n, m) = (512 * 1024, 256 * 1024); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); @@ -309,9 +305,8 @@ fn bsize_test_ibs_greater() } #[test] -fn bsize_test_obs_greater() -{ - let (n,m) = (256*1024, 512*1024); +fn bsize_test_obs_greater() { + let (n, m) = (256 * 1024, 512 * 1024); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); @@ -320,9 +315,8 @@ fn bsize_test_obs_greater() } #[test] -fn bsize_test_bs_eq() -{ - let (n,m) = (1024, 1024); +fn bsize_test_bs_eq() { + let (n, m) = (1024, 1024); let res = calc_bsize(n, m); assert!(res % n == 0); assert!(res % m == 0); diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index f134886b2..15bb8d481 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -8,8 +8,7 @@ pub type Matches = clap::ArgMatches<'static>; /// Parser Errors describe errors with parser input #[derive(Debug, PartialEq)] -pub enum ParseError -{ +pub enum ParseError { MultipleFmtTable, MultipleUCaseLCase, MultipleBlockUnblock, @@ -24,59 +23,52 @@ pub enum ParseError Unimplemented(String), } -impl std::fmt::Display for ParseError -{ +impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self - { - Self::MultipleFmtTable => - { - write!(f, "Only one of conv=ascii conv=ebcdic or conv=ibm may be specified") - }, - Self::MultipleUCaseLCase => - { + match self { + Self::MultipleFmtTable => { + write!( + f, + "Only one of conv=ascii conv=ebcdic or conv=ibm may be specified" + ) + } + Self::MultipleUCaseLCase => { write!(f, "Only one of conv=lcase or conv=ucase may be specified") - }, - Self::MultipleBlockUnblock => - { + } + Self::MultipleBlockUnblock => { write!(f, "Only one of conv=block or conv=unblock may be specified") - }, - Self::MultipleExclNoCreat => - { + } + Self::MultipleExclNoCreat => { write!(f, "Only one ov conv=excl or conv=nocreat may be specified") - }, - Self::FlagNoMatch(arg) => - { + } + Self::FlagNoMatch(arg) => { write!(f, "Unrecognized iflag=FLAG or oflag=FLAG -> {}", arg) - }, - Self::ConvFlagNoMatch(arg) => - { + } + Self::ConvFlagNoMatch(arg) => { write!(f, "Unrecognized conv=CONV -> {}", arg) - }, - Self::NoMatchingMultiplier(arg) => - { + } + Self::NoMatchingMultiplier(arg) => { write!(f, "Unrecognized byte multiplier -> {}", arg) - }, - Self::ByteStringContainsNoValue(arg) => - { + } + Self::ByteStringContainsNoValue(arg) => { write!(f, "Unrecognized byte value -> {}", arg) - }, - Self::MultiplierStringWouldOverflow(arg) => - { - write!(f, "Multiplier string would overflow on current system -> {}", arg) - }, - Self::BlockUnblockWithoutCBS => - { + } + Self::MultiplierStringWouldOverflow(arg) => { + write!( + f, + "Multiplier string would overflow on current system -> {}", + arg + ) + } + Self::BlockUnblockWithoutCBS => { write!(f, "conv=block or conv=unblock specified without cbs=N") - }, - Self::StatusLevelNotRecognized(arg) => - { + } + Self::StatusLevelNotRecognized(arg) => { write!(f, "status=LEVEL not recognized -> {}", arg) - }, - Self::Unimplemented(arg) => - { + } + Self::Unimplemented(arg) => { write!(f, "feature not implemented on this system -> {}", arg) - }, + } } } } @@ -86,8 +78,7 @@ impl Error for ParseError {} /// Some flags specified as part of a conv=CONV[,CONV]... block /// relate to the input file, others to the output file. #[derive(Debug, PartialEq)] -enum ConvFlag -{ +enum ConvFlag { // Input FmtAtoE, FmtEtoA, @@ -108,56 +99,35 @@ enum ConvFlag FSync, } -impl std::str::FromStr for ConvFlag -{ +impl std::str::FromStr for ConvFlag { type Err = ParseError; - fn from_str(s: &str) -> Result - { - match s - { + fn from_str(s: &str) -> Result { + match s { // Input - "ascii" => - Ok(Self::FmtEtoA), - "ebcdic" => - Ok(Self::FmtAtoE), - "ibm" => - Ok(Self::FmtAtoI), - "lcase" => - Ok(Self::LCase), - "ucase" => - Ok(Self::UCase), - "block" => - Ok(Self::Block), - "unblock" => - Ok(Self::Unblock), - "swab" => - Ok(Self::Swab), - "sync" => - Ok(Self::Sync), - "noerror" => - Ok(Self::NoError), + "ascii" => Ok(Self::FmtEtoA), + "ebcdic" => Ok(Self::FmtAtoE), + "ibm" => Ok(Self::FmtAtoI), + "lcase" => Ok(Self::LCase), + "ucase" => Ok(Self::UCase), + "block" => Ok(Self::Block), + "unblock" => Ok(Self::Unblock), + "swab" => Ok(Self::Swab), + "sync" => Ok(Self::Sync), + "noerror" => Ok(Self::NoError), // Output - "sparse" => - Ok(Self::Sparse), - "excl" => - Ok(Self::Excl), - "nocreat" => - Ok(Self::NoCreat), - "notrunc" => - Ok(Self::NoTrunc), - "fdatasync" => - Ok(Self::FDataSync), - "fsync" => - Ok(Self::FSync), - _ => - Err(ParseError::ConvFlagNoMatch(String::from(s))) - } + "sparse" => Ok(Self::Sparse), + "excl" => Ok(Self::Excl), + "nocreat" => Ok(Self::NoCreat), + "notrunc" => Ok(Self::NoTrunc), + "fdatasync" => Ok(Self::FDataSync), + "fsync" => Ok(Self::FSync), + _ => Err(ParseError::ConvFlagNoMatch(String::from(s))), + } } } -enum Flag -{ +enum Flag { // Input only FullBlock, CountBytes, @@ -181,353 +151,271 @@ enum Flag SeekBytes, } -impl std::str::FromStr for Flag -{ +impl std::str::FromStr for Flag { type Err = ParseError; - fn from_str(s: &str) -> Result - { - match s - { + fn from_str(s: &str) -> Result { + match s { // Input only - "fullblock" => - Ok(Self::FullBlock), - "count_bytes" => - Ok(Self::CountBytes), - "skip_bytes" => - Ok(Self::SkipBytes), + "fullblock" => Ok(Self::FullBlock), + "count_bytes" => Ok(Self::CountBytes), + "skip_bytes" => Ok(Self::SkipBytes), // Either "cio" => - // Ok(Self::Cio), - Err(ParseError::Unimplemented(s.to_string())), + // Ok(Self::Cio), + { + Err(ParseError::Unimplemented(s.to_string())) + } "direct" => - // Ok(Self::Direct), - if cfg!(unix) - { + // Ok(Self::Direct), + { + if cfg!(unix) { Ok(Self::Direct) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "directory" => - // Ok(Self::Directory), - if cfg!(unix) - { + // Ok(Self::Directory), + { + if cfg!(unix) { Ok(Self::Directory) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "dsync" => - // Ok(Self::Dsync), - if cfg!(unix) - { + // Ok(Self::Dsync), + { + if cfg!(unix) { Ok(Self::Dsync) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "sync" => - // Ok(Self::Sync), - if cfg!(unix) - { + // Ok(Self::Sync), + { + if cfg!(unix) { Ok(Self::Sync) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "nocache" => - // Ok(Self::NoCache), - Err(ParseError::Unimplemented(s.to_string())), + // Ok(Self::NoCache), + { + Err(ParseError::Unimplemented(s.to_string())) + } "nonblock" => - // Ok(Self::NonBlock), - if cfg!(unix) - { + // Ok(Self::NonBlock), + { + if cfg!(unix) { Ok(Self::NonBlock) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "noatime" => - // Ok(Self::NoATime), - if cfg!(unix) - { + // Ok(Self::NoATime), + { + if cfg!(unix) { Ok(Self::NoATime) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "noctty" => - // Ok(Self::NoCtty), - if cfg!(unix) - { + // Ok(Self::NoCtty), + { + if cfg!(unix) { Ok(Self::NoCtty) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "nofollow" => - // Ok(Self::NoFollow), - if cfg!(unix) - { + // Ok(Self::NoFollow), + { + if cfg!(unix) { Ok(Self::NoFollow) - } - else - { + } else { Err(ParseError::Unimplemented(s.to_string())) - }, + } + } "nolinks" => - // Ok(Self::NoLinks), - Err(ParseError::Unimplemented(s.to_string())), + // Ok(Self::NoLinks), + { + Err(ParseError::Unimplemented(s.to_string())) + } "binary" => - // Ok(Self::Binary), - Err(ParseError::Unimplemented(s.to_string())), + // Ok(Self::Binary), + { + Err(ParseError::Unimplemented(s.to_string())) + } "text" => - // Ok(Self::Text), - Err(ParseError::Unimplemented(s.to_string())), + // Ok(Self::Text), + { + Err(ParseError::Unimplemented(s.to_string())) + } // Output only - "append" => - Ok(Self::Append), - "seek_bytes" => - Ok(Self::SeekBytes), - _ => - Err(ParseError::FlagNoMatch(String::from(s))), + "append" => Ok(Self::Append), + "seek_bytes" => Ok(Self::SeekBytes), + _ => Err(ParseError::FlagNoMatch(String::from(s))), } } } -impl std::str::FromStr for StatusLevel -{ +impl std::str::FromStr for StatusLevel { type Err = ParseError; - fn from_str(s: &str) -> Result - { - match s - { - "none" => - Ok(StatusLevel::None), - "noxfer" => - Ok(StatusLevel::Noxfer), - "progress" => - Ok(StatusLevel::Progress), - _ => - Err(ParseError::StatusLevelNotRecognized(s.to_string())), + fn from_str(s: &str) -> Result { + match s { + "none" => Ok(StatusLevel::None), + "noxfer" => Ok(StatusLevel::Noxfer), + "progress" => Ok(StatusLevel::Progress), + _ => Err(ParseError::StatusLevelNotRecognized(s.to_string())), } } } -fn parse_multiplier<'a>(s: &'a str) -> Result -{ - match s - { - "c" => - Ok(1), - "w" => - Ok(2), - "b" => - Ok(512), - "kB" => - Ok(1000), - "K" | "KiB" => - Ok(1024), - "MB" => - Ok(1000*1000), - "M" | "MiB" => - Ok(1024*1024), - "GB" => - Ok(1000*1000*1000), - "G" | "GiB" => - Ok(1024*1024*1024), - "TB" => - Ok(1000*1000*1000*1000), - "T" | "TiB" => - Ok(1024*1024*1024*1024), - "PB" => - Ok(1000*1000*1000*1000*1000), - "P" | "PiB" => - Ok(1024*1024*1024*1024*1024), - "EB" => - Ok(1000*1000*1000*1000*1000*1000), - "E" | "EiB" => - Ok(1024*1024*1024*1024*1024*1024), -// The following would overflow on my x64 system -// "ZB" => -// Ok(1000*1000*1000*1000*1000*1000*1000), -// "Z" | "ZiB" => -// Ok(1024*1024*1024*1024*1024*1024*1024), -// "YB" => -// Ok(1000*1000*1000*1000*1000*1000*1000*1000), -// "Y" | "YiB" => -// Ok(1024*1024*1024*1024*1024*1024*1024*1024), - _ => - Err(ParseError::NoMatchingMultiplier(s.to_string())), +fn parse_multiplier<'a>(s: &'a str) -> Result { + match s { + "c" => Ok(1), + "w" => Ok(2), + "b" => Ok(512), + "kB" => Ok(1000), + "K" | "KiB" => Ok(1024), + "MB" => Ok(1000 * 1000), + "M" | "MiB" => Ok(1024 * 1024), + "GB" => Ok(1000 * 1000 * 1000), + "G" | "GiB" => Ok(1024 * 1024 * 1024), + "TB" => Ok(1000 * 1000 * 1000 * 1000), + "T" | "TiB" => Ok(1024 * 1024 * 1024 * 1024), + "PB" => Ok(1000 * 1000 * 1000 * 1000 * 1000), + "P" | "PiB" => Ok(1024 * 1024 * 1024 * 1024 * 1024), + "EB" => Ok(1000 * 1000 * 1000 * 1000 * 1000 * 1000), + "E" | "EiB" => Ok(1024 * 1024 * 1024 * 1024 * 1024 * 1024), + // The following would overflow on my x64 system + // "ZB" => + // Ok(1000*1000*1000*1000*1000*1000*1000), + // "Z" | "ZiB" => + // Ok(1024*1024*1024*1024*1024*1024*1024), + // "YB" => + // Ok(1000*1000*1000*1000*1000*1000*1000*1000), + // "Y" | "YiB" => + // Ok(1024*1024*1024*1024*1024*1024*1024*1024), + _ => Err(ParseError::NoMatchingMultiplier(s.to_string())), } } -fn parse_bytes_only(s: &str) -> Result -{ - match s.parse() - { - Ok(bytes) => - Ok(bytes), - Err(_) => - Err(ParseError::ByteStringContainsNoValue(s.to_string())), +fn parse_bytes_only(s: &str) -> Result { + match s.parse() { + Ok(bytes) => Ok(bytes), + Err(_) => Err(ParseError::ByteStringContainsNoValue(s.to_string())), } } -fn parse_bytes_with_opt_multiplier(s: &str) -> Result -{ - match s.find(char::is_alphabetic) - { - Some(idx) => - { +fn parse_bytes_with_opt_multiplier(s: &str) -> Result { + match s.find(char::is_alphabetic) { + Some(idx) => { let base = parse_bytes_only(&s[..idx])?; let mult = parse_multiplier(&s[idx..])?; - if let Some(bytes) = base.checked_mul(mult) - { + if let Some(bytes) = base.checked_mul(mult) { Ok(bytes) - } - else - { + } else { Err(ParseError::MultiplierStringWouldOverflow(s.to_string())) } } - _ => - parse_bytes_only(&s), + _ => parse_bytes_only(&s), } } -pub fn parse_ibs(matches: &Matches) -> Result -{ - if let Some(mixed_str) = matches.value_of("bs") - { +pub fn parse_ibs(matches: &Matches) -> Result { + if let Some(mixed_str) = matches.value_of("bs") { parse_bytes_with_opt_multiplier(mixed_str) - } - else if let Some(mixed_str) = matches.value_of("ibs") - { + } else if let Some(mixed_str) = matches.value_of("ibs") { parse_bytes_with_opt_multiplier(mixed_str) - } - else - { + } else { Ok(512) } } -fn parse_cbs(matches: &Matches) -> Result, ParseError> -{ - if let Some(s) = matches.value_of("cbs") - { +fn parse_cbs(matches: &Matches) -> Result, ParseError> { + if let Some(s) = matches.value_of("cbs") { let bytes = parse_bytes_with_opt_multiplier(s)?; Ok(Some(bytes)) - } - else - { + } else { Ok(None) } } -pub fn parse_status_level(matches: &Matches) -> Result, ParseError> -{ - match matches.value_of("status") - { - Some(s) => - { +pub fn parse_status_level(matches: &Matches) -> Result, ParseError> { + match matches.value_of("status") { + Some(s) => { let st = s.parse()?; Ok(Some(st)) - }, - None => - Ok(None), + } + None => Ok(None), } } -pub fn parse_obs(matches: &Matches) -> Result -{ - if let Some(mixed_str) = matches.value_of("bs") - { +pub fn parse_obs(matches: &Matches) -> Result { + if let Some(mixed_str) = matches.value_of("bs") { parse_bytes_with_opt_multiplier(mixed_str) - } - else if let Some(mixed_str) = matches.value_of("obs") - { + } else if let Some(mixed_str) = matches.value_of("obs") { parse_bytes_with_opt_multiplier(mixed_str) - } - else - { + } else { Ok(512) } } -fn parse_ctable(fmt: Option, case: Option) -> Option<&'static ConversionTable> -{ - fn parse_conv_and_case_table(fmt: &ConvFlag, case: &ConvFlag) -> Option<&'static ConversionTable> - { - match (fmt, case) - { - (ConvFlag::FmtAtoE, ConvFlag::UCase) => - Some(&ASCII_TO_EBCDIC_LCASE_TO_UCASE), - (ConvFlag::FmtAtoE, ConvFlag::LCase) => - Some(&ASCII_TO_EBCDIC_UCASE_TO_LCASE), - (ConvFlag::FmtEtoA, ConvFlag::UCase) => - Some(&EBCDIC_TO_ASCII_LCASE_TO_UCASE), - (ConvFlag::FmtEtoA, ConvFlag::LCase) => - Some(&EBCDIC_TO_ASCII_UCASE_TO_LCASE), - (ConvFlag::FmtAtoI, ConvFlag::UCase) => - Some(&ASCII_TO_IBM_UCASE_TO_LCASE), - (ConvFlag::FmtAtoI, ConvFlag::LCase) => - Some(&ASCII_TO_IBM_LCASE_TO_UCASE), - (_, _) => - None, +fn parse_ctable(fmt: Option, case: Option) -> Option<&'static ConversionTable> { + fn parse_conv_and_case_table( + fmt: &ConvFlag, + case: &ConvFlag, + ) -> Option<&'static ConversionTable> { + match (fmt, case) { + (ConvFlag::FmtAtoE, ConvFlag::UCase) => Some(&ASCII_TO_EBCDIC_LCASE_TO_UCASE), + (ConvFlag::FmtAtoE, ConvFlag::LCase) => Some(&ASCII_TO_EBCDIC_UCASE_TO_LCASE), + (ConvFlag::FmtEtoA, ConvFlag::UCase) => Some(&EBCDIC_TO_ASCII_LCASE_TO_UCASE), + (ConvFlag::FmtEtoA, ConvFlag::LCase) => Some(&EBCDIC_TO_ASCII_UCASE_TO_LCASE), + (ConvFlag::FmtAtoI, ConvFlag::UCase) => Some(&ASCII_TO_IBM_UCASE_TO_LCASE), + (ConvFlag::FmtAtoI, ConvFlag::LCase) => Some(&ASCII_TO_IBM_LCASE_TO_UCASE), + (_, _) => None, } } - fn parse_conv_table_only(fmt: &ConvFlag) -> Option<&'static ConversionTable> - { - match fmt - { - ConvFlag::FmtAtoE => - Some(&ASCII_TO_EBCDIC), - ConvFlag::FmtEtoA => - Some(&EBCDIC_TO_ASCII), - ConvFlag::FmtAtoI => - Some(&ASCII_TO_IBM), - _ => - None, + fn parse_conv_table_only(fmt: &ConvFlag) -> Option<&'static ConversionTable> { + match fmt { + ConvFlag::FmtAtoE => Some(&ASCII_TO_EBCDIC), + ConvFlag::FmtEtoA => Some(&EBCDIC_TO_ASCII), + ConvFlag::FmtAtoI => Some(&ASCII_TO_IBM), + _ => None, } } // ------------------------------------------------------------------------ - match (fmt, case) - { + match (fmt, case) { // Both [ascii | ebcdic | ibm] and [lcase | ucase] specified - (Some(fmt), Some(case)) => - parse_conv_and_case_table(&fmt, &case), + (Some(fmt), Some(case)) => parse_conv_and_case_table(&fmt, &case), // Only [ascii | ebcdic | ibm] specified - (Some(fmt), None) => - parse_conv_table_only(&fmt), + (Some(fmt), None) => parse_conv_table_only(&fmt), // Only [lcase | ucase] specified - (None, Some(ConvFlag::UCase)) => - Some(&ASCII_LCASE_TO_UCASE), - (None, Some(ConvFlag::LCase)) => - Some(&ASCII_UCASE_TO_LCASE), + (None, Some(ConvFlag::UCase)) => Some(&ASCII_LCASE_TO_UCASE), + (None, Some(ConvFlag::LCase)) => Some(&ASCII_UCASE_TO_LCASE), // ST else... - (_, _) => - None, - } + (_, _) => None, + } } -fn parse_flag_list>(tag: &str, matches: &Matches) -> Result, ParseError> -{ +fn parse_flag_list>( + tag: &str, + matches: &Matches, +) -> Result, ParseError> { let mut flags = Vec::new(); - if let Some(comma_str) = matches.value_of(tag) - { - for s in comma_str.split(",") - { + if let Some(comma_str) = matches.value_of(tag) { + for s in comma_str.split(",") { let flag = s.parse()?; flags.push(flag); } @@ -538,8 +426,7 @@ fn parse_flag_list>(tag: &str, matches: & /// Parse Conversion Options (Input Variety) /// Construct and validate a IConvFlags -pub fn parse_conv_flag_input(matches: &Matches) -> Result -{ +pub fn parse_conv_flag_input(matches: &Matches) -> Result { let flags = parse_flag_list("conv", matches)?; let cbs = parse_cbs(matches)?; @@ -551,96 +438,66 @@ pub fn parse_conv_flag_input(matches: &Matches) -> Result - if let Some(_) = fmt - { + for flag in flags { + match flag { + ConvFlag::FmtEtoA => { + if let Some(_) = fmt { return Err(ParseError::MultipleFmtTable); - } - else - { + } else { fmt = Some(flag); - }, - ConvFlag::FmtAtoE => - if let Some(_) = fmt - { + } + } + ConvFlag::FmtAtoE => { + if let Some(_) = fmt { return Err(ParseError::MultipleFmtTable); - } - else - { + } else { fmt = Some(flag); - }, - ConvFlag::FmtAtoI => - if let Some(_) = fmt - { + } + } + ConvFlag::FmtAtoI => { + if let Some(_) = fmt { return Err(ParseError::MultipleFmtTable); - } - else - { + } else { fmt = Some(flag); - }, - ConvFlag::UCase => - if let Some(_) = case - { + } + } + ConvFlag::UCase => { + if let Some(_) = case { return Err(ParseError::MultipleUCaseLCase); - } - else - { + } else { case = Some(flag) - }, - ConvFlag::LCase => - if let Some(_) = case - { + } + } + ConvFlag::LCase => { + if let Some(_) = case { return Err(ParseError::MultipleUCaseLCase); - } - else - { + } else { case = Some(flag) - }, - ConvFlag::Block => - match (cbs, unblock) - { - (Some(cbs), None) => - block = Some(cbs), - (None, _) => - return Err(ParseError::BlockUnblockWithoutCBS), - (_, Some(_)) => - return Err(ParseError::MultipleBlockUnblock), - }, - ConvFlag::Unblock => - match (cbs, block) - { - (Some(cbs), None) => - unblock = Some(cbs), - (None, _) => - return Err(ParseError::BlockUnblockWithoutCBS), - (_, Some(_)) => - return Err(ParseError::MultipleBlockUnblock), - }, - ConvFlag::Swab => - swab = true, - ConvFlag::Sync => - sync = true, - ConvFlag::NoError => - noerror = true, - _ => {}, + } + } + ConvFlag::Block => match (cbs, unblock) { + (Some(cbs), None) => block = Some(cbs), + (None, _) => return Err(ParseError::BlockUnblockWithoutCBS), + (_, Some(_)) => return Err(ParseError::MultipleBlockUnblock), + }, + ConvFlag::Unblock => match (cbs, block) { + (Some(cbs), None) => unblock = Some(cbs), + (None, _) => return Err(ParseError::BlockUnblockWithoutCBS), + (_, Some(_)) => return Err(ParseError::MultipleBlockUnblock), + }, + ConvFlag::Swab => swab = true, + ConvFlag::Sync => sync = true, + ConvFlag::NoError => noerror = true, + _ => {} } } let ctable = parse_ctable(fmt, case); - let sync = if sync && (block.is_some() || unblock.is_some()) - { + let sync = if sync && (block.is_some() || unblock.is_some()) { Some(' ' as u8) - } - else if sync - { + } else if sync { Some(0u8) - } - else - { + } else { None }; @@ -656,8 +513,7 @@ pub fn parse_conv_flag_input(matches: &Matches) -> Result Result -{ +pub fn parse_conv_flag_output(matches: &Matches) -> Result { let flags = parse_flag_list("conv", matches)?; let mut sparse = false; @@ -667,38 +523,28 @@ pub fn parse_conv_flag_output(matches: &Matches) -> Result - sparse = true, - ConvFlag::Excl => - if !nocreat - { + for flag in flags { + match flag { + ConvFlag::Sparse => sparse = true, + ConvFlag::Excl => { + if !nocreat { excl = true; - } - else - { + } else { return Err(ParseError::MultipleExclNoCreat); - }, - ConvFlag::NoCreat => - if !excl - { + } + } + ConvFlag::NoCreat => { + if !excl { nocreat = true; - } - else - { + } else { return Err(ParseError::MultipleExclNoCreat); - }, - ConvFlag::NoTrunc => - notrunc = true, - ConvFlag::FDataSync => - fdatasync = true, - ConvFlag::FSync => - fsync = true, - _ => {}, - } + } + } + ConvFlag::NoTrunc => notrunc = true, + ConvFlag::FDataSync => fdatasync = true, + ConvFlag::FSync => fsync = true, + _ => {} + } } Ok(OConvFlags { @@ -712,8 +558,7 @@ pub fn parse_conv_flag_output(matches: &Matches) -> Result Result -{ +pub fn parse_iflags(matches: &Matches) -> Result { let mut cio = false; let mut direct = false; let mut directory = false; @@ -733,47 +578,29 @@ pub fn parse_iflags(matches: &Matches) -> Result let flags = parse_flag_list("iflag", matches)?; - for flag in flags - { - match flag - { - Flag::Cio => - cio = true, - Flag::Direct => - direct = true, - Flag::Directory => - directory = true, - Flag::Dsync => - dsync = true, - Flag::Sync => - sync = true, - Flag::NoCache => - nocache = true, - Flag::NonBlock => - nonblock = true, - Flag::NoATime => - noatime = true, - Flag::NoCtty => - noctty = true, - Flag::NoFollow => - nofollow = true, - Flag::NoLinks => - nolinks = true, - Flag::Binary => - binary = true, - Flag::Text => - text = true, - Flag::FullBlock => - fullblock = true, - Flag::CountBytes => - count_bytes = true, - Flag::SkipBytes => - skip_bytes = true, - _ => {}, + for flag in flags { + match flag { + Flag::Cio => cio = true, + Flag::Direct => direct = true, + Flag::Directory => directory = true, + Flag::Dsync => dsync = true, + Flag::Sync => sync = true, + Flag::NoCache => nocache = true, + Flag::NonBlock => nonblock = true, + Flag::NoATime => noatime = true, + Flag::NoCtty => noctty = true, + Flag::NoFollow => nofollow = true, + Flag::NoLinks => nolinks = true, + Flag::Binary => binary = true, + Flag::Text => text = true, + Flag::FullBlock => fullblock = true, + Flag::CountBytes => count_bytes = true, + Flag::SkipBytes => skip_bytes = true, + _ => {} } } - Ok(IFlags{ + Ok(IFlags { cio, direct, directory, @@ -794,8 +621,7 @@ pub fn parse_iflags(matches: &Matches) -> Result } /// Parse OFlags struct from CL-input -pub fn parse_oflags(matches: &Matches) -> Result -{ +pub fn parse_oflags(matches: &Matches) -> Result { let mut append = false; let mut cio = false; let mut direct = false; @@ -814,41 +640,24 @@ pub fn parse_oflags(matches: &Matches) -> Result let flags = parse_flag_list("oflag", matches)?; - for flag in flags - { - match flag - { - Flag::Append => - append = true, - Flag::Cio => - cio = true, - Flag::Direct => - direct = true, - Flag::Directory => - directory = true, - Flag::Dsync => - dsync = true, - Flag::Sync => - sync = true, - Flag::NoCache => - nocache = true, - Flag::NonBlock => - nonblock = true, - Flag::NoATime => - noatime = true, - Flag::NoCtty => - noctty = true, - Flag::NoFollow => - nofollow = true, - Flag::NoLinks => - nolinks = true, - Flag::Binary => - binary = true, - Flag::Text => - text = true, - Flag::SeekBytes => - seek_bytes = true, - _ => {}, + for flag in flags { + match flag { + Flag::Append => append = true, + Flag::Cio => cio = true, + Flag::Direct => direct = true, + Flag::Directory => directory = true, + Flag::Dsync => dsync = true, + Flag::Sync => sync = true, + Flag::NoCache => nocache = true, + Flag::NonBlock => nonblock = true, + Flag::NoATime => noatime = true, + Flag::NoCtty => noctty = true, + Flag::NoFollow => nofollow = true, + Flag::NoLinks => nolinks = true, + Flag::Binary => binary = true, + Flag::Text => text = true, + Flag::SeekBytes => seek_bytes = true, + _ => {} } } @@ -872,79 +681,62 @@ pub fn parse_oflags(matches: &Matches) -> Result } /// Parse the amount of the input file to skip. -pub fn parse_skip_amt(ibs: &usize, iflags: &IFlags, matches: &Matches) -> Result, ParseError> -{ - if let Some(amt) = matches.value_of("skip") - { - if iflags.skip_bytes - { +pub fn parse_skip_amt( + ibs: &usize, + iflags: &IFlags, + matches: &Matches, +) -> Result, ParseError> { + if let Some(amt) = matches.value_of("skip") { + if iflags.skip_bytes { let n = parse_bytes_with_opt_multiplier(amt)?; Ok(Some(n)) - } - else - { + } else { let n = parse_bytes_with_opt_multiplier(amt)?; - Ok(Some(ibs*n)) + Ok(Some(ibs * n)) } - } - else - { + } else { Ok(None) } } /// Parse the amount of the output file to seek. -pub fn parse_seek_amt(obs: &usize, oflags: &OFlags, matches: &Matches) -> Result, ParseError> -{ - if let Some(amt) = matches.value_of("seek") - { - if oflags.seek_bytes - { +pub fn parse_seek_amt( + obs: &usize, + oflags: &OFlags, + matches: &Matches, +) -> Result, ParseError> { + if let Some(amt) = matches.value_of("seek") { + if oflags.seek_bytes { let n = parse_bytes_with_opt_multiplier(amt)?; Ok(Some(n)) - } - else - { + } else { let n = parse_bytes_with_opt_multiplier(amt)?; - Ok(Some(obs*n)) + Ok(Some(obs * n)) } - } - else - { + } else { Ok(None) } } /// Parse the value of count=N and the type of N implied by iflags -pub fn parse_count(iflags: &IFlags, matches: &Matches) -> Result, ParseError> -{ - if let Some(amt) = matches.value_of("count") - { +pub fn parse_count(iflags: &IFlags, matches: &Matches) -> Result, ParseError> { + if let Some(amt) = matches.value_of("count") { let n = parse_bytes_with_opt_multiplier(amt)?; - if iflags.count_bytes - { + if iflags.count_bytes { Ok(Some(CountType::Bytes(n))) - } - else - { + } else { Ok(Some(CountType::Reads(n))) } - } - else - { + } else { Ok(None) } } /// Parse whether the args indicate the input is not ascii -pub fn parse_input_non_ascii(matches: &Matches) -> Result -{ - if let Some(conv_opts) = matches.value_of("conv") - { +pub fn parse_input_non_ascii(matches: &Matches) -> Result { + if let Some(conv_opts) = matches.value_of("conv") { Ok(conv_opts.contains("ascii")) - } - else - { + } else { Ok(false) } } diff --git a/src/uu/dd/src/parseargs/unit_tests.rs b/src/uu/dd/src/parseargs/unit_tests.rs index 05d9176d0..2c8954cec 100644 --- a/src/uu/dd/src/parseargs/unit_tests.rs +++ b/src/uu/dd/src/parseargs/unit_tests.rs @@ -1,19 +1,23 @@ use super::*; -use crate::{ - build_dd_app, - StatusLevel, -}; +use crate::{build_dd_app, StatusLevel}; #[cfg(not(unix))] #[test] -fn unimplemented_flags_should_error_non_unix() -{ +fn unimplemented_flags_should_error_non_unix() { let mut unfailed = Vec::new(); // The following flags are only implemented in unix - for flag in vec!["direct", "directory", "dsync", "sync", "nonblock", "noatime", "noctty", "nofollow"] - { + for flag in vec![ + "direct", + "directory", + "dsync", + "sync", + "nonblock", + "noatime", + "noctty", + "nofollow", + ] { let args = vec![ String::from("dd"), format!("--iflag={}", flag), @@ -21,36 +25,30 @@ fn unimplemented_flags_should_error_non_unix() ]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); - match parse_iflags(&matches) - { - Ok(_) => - unfailed.push(format!("iflag={}", flag)), - Err(_) => - {/* expected behaviour :-) */}, + match parse_iflags(&matches) { + Ok(_) => unfailed.push(format!("iflag={}", flag)), + Err(_) => { /* expected behaviour :-) */ } } - match parse_oflags(&matches) - { - Ok(_) => - unfailed.push(format!("oflag={}", flag)), - Err(_) => - {/* expected behaviour :-) */}, + match parse_oflags(&matches) { + Ok(_) => unfailed.push(format!("oflag={}", flag)), + Err(_) => { /* expected behaviour :-) */ } } } - if !unfailed.is_empty() - { - panic!("The following flags did not panic as expected: {:?}", unfailed); + if !unfailed.is_empty() { + panic!( + "The following flags did not panic as expected: {:?}", + unfailed + ); } } #[test] -fn unimplemented_flags_should_error() -{ +fn unimplemented_flags_should_error() { let mut unfailed = Vec::new(); // The following flags are not implemented - for flag in vec!["cio", "nocache", "nolinks", "text", "binary"] - { + for flag in vec!["cio", "nocache", "nolinks", "text", "binary"] { let args = vec![ String::from("dd"), format!("--iflag={}", flag), @@ -58,31 +56,26 @@ fn unimplemented_flags_should_error() ]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); - match parse_iflags(&matches) - { - Ok(_) => - unfailed.push(format!("iflag={}", flag)), - Err(_) => - {/* expected behaviour :-) */}, + match parse_iflags(&matches) { + Ok(_) => unfailed.push(format!("iflag={}", flag)), + Err(_) => { /* expected behaviour :-) */ } } - match parse_oflags(&matches) - { - Ok(_) => - unfailed.push(format!("oflag={}", flag)), - Err(_) => - {/* expected behaviour :-) */}, + match parse_oflags(&matches) { + Ok(_) => unfailed.push(format!("oflag={}", flag)), + Err(_) => { /* expected behaviour :-) */ } } } - if !unfailed.is_empty() - { - panic!("The following flags did not panic as expected: {:?}", unfailed); + if !unfailed.is_empty() { + panic!( + "The following flags did not panic as expected: {:?}", + unfailed + ); } } #[test] -fn test_status_level_absent() -{ +fn test_status_level_absent() { let args = vec![ String::from("dd"), String::from("--if=foo.file"), @@ -96,8 +89,7 @@ fn test_status_level_absent() } #[test] -fn test_status_level_none() -{ +fn test_status_level_none() { let args = vec![ String::from("dd"), String::from("--status=none"), @@ -112,8 +104,7 @@ fn test_status_level_none() } #[test] -fn test_status_level_progress() -{ +fn test_status_level_progress() { let args = vec![ String::from("dd"), String::from("--if=foo.file"), @@ -128,8 +119,7 @@ fn test_status_level_progress() } #[test] -fn test_status_level_noxfer() -{ +fn test_status_level_noxfer() { let args = vec![ String::from("dd"), String::from("--if=foo.file"), @@ -147,12 +137,8 @@ fn test_status_level_noxfer() #[test] #[should_panic] -fn icf_ctable_error() -{ - let args = vec![ - String::from("dd"), - String::from("--conv=ascii,ebcdic,ibm"), - ]; +fn icf_ctable_error() { + let args = vec![String::from("dd"), String::from("--conv=ascii,ebcdic,ibm")]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); @@ -161,12 +147,8 @@ fn icf_ctable_error() #[test] #[should_panic] -fn icf_case_error() -{ - let args = vec![ - String::from("dd"), - String::from("--conv=ucase,lcase"), - ]; +fn icf_case_error() { + let args = vec![String::from("dd"), String::from("--conv=ucase,lcase")]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); @@ -175,12 +157,8 @@ fn icf_case_error() #[test] #[should_panic] -fn icf_block_error() -{ - let args = vec![ - String::from("dd"), - String::from("--conv=block,unblock"), - ]; +fn icf_block_error() { + let args = vec![String::from("dd"), String::from("--conv=block,unblock")]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); @@ -189,12 +167,8 @@ fn icf_block_error() #[test] #[should_panic] -fn icf_creat_error() -{ - let args = vec![ - String::from("dd"), - String::from("--conv=excl,nocreat"), - ]; +fn icf_creat_error() { + let args = vec![String::from("dd"), String::from("--conv=excl,nocreat")]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); @@ -202,35 +176,23 @@ fn icf_creat_error() } #[test] -fn parse_icf_token_ibm() -{ - let exp = vec![ - ConvFlag::FmtAtoI, - ]; +fn parse_icf_token_ibm() { + let exp = vec![ConvFlag::FmtAtoI]; - let args = vec![ - String::from("dd"), - String::from("--conv=ibm"), - ]; + let args = vec![String::from("dd"), String::from("--conv=ibm")]; let matches = build_dd_app!().get_matches_from_safe(args).unwrap(); let act = parse_flag_list::("conv", &matches).unwrap(); assert_eq!(exp.len(), act.len()); - for cf in &exp - { + for cf in &exp { assert!(exp.contains(&cf)); } } #[test] -fn parse_icf_tokens_elu() -{ - let exp = vec![ - ConvFlag::FmtEtoA, - ConvFlag::LCase, - ConvFlag::Unblock, - ]; +fn parse_icf_tokens_elu() { + let exp = vec![ConvFlag::FmtEtoA, ConvFlag::LCase, ConvFlag::Unblock]; let args = vec![ String::from("dd"), @@ -240,15 +202,13 @@ fn parse_icf_tokens_elu() let act = parse_flag_list::("conv", &matches).unwrap(); assert_eq!(exp.len(), act.len()); - for cf in &exp - { + for cf in &exp { assert!(exp.contains(&cf)); } } #[test] -fn parse_icf_tokens_remaining() -{ +fn parse_icf_tokens_remaining() { let exp = vec![ ConvFlag::FmtAtoE, ConvFlag::UCase, @@ -274,8 +234,7 @@ fn parse_icf_tokens_remaining() let act = parse_flag_list::("conv", &matches).unwrap(); assert_eq!(exp.len(), act.len()); - for cf in &exp - { + for cf in &exp { assert!(exp.contains(&cf)); } } @@ -294,130 +253,53 @@ macro_rules! test_byte_parser ( } ); -test_byte_parser!( - test_bytes_n, - "765", - 765 -); -test_byte_parser!( - test_bytes_c, - "13c", - 13 -); +test_byte_parser!(test_bytes_n, "765", 765); +test_byte_parser!(test_bytes_c, "13c", 13); -test_byte_parser!( - test_bytes_w, - "1w", - 2 -); +test_byte_parser!(test_bytes_w, "1w", 2); -test_byte_parser!( - test_bytes_b, - "1b", - 512 -); +test_byte_parser!(test_bytes_b, "1b", 512); -test_byte_parser!( - test_bytes_k, - "1kB", - 1000 -); -test_byte_parser!( - test_bytes_K, - "1K", - 1024 -); -test_byte_parser!( - test_bytes_Ki, - "1KiB", - 1024 -); +test_byte_parser!(test_bytes_k, "1kB", 1000); +test_byte_parser!(test_bytes_K, "1K", 1024); +test_byte_parser!(test_bytes_Ki, "1KiB", 1024); -test_byte_parser!( - test_bytes_MB, - "2MB", - 2*1000*1000 -); -test_byte_parser!( - test_bytes_M, - "2M", - 2*1024*1024 -); -test_byte_parser!( - test_bytes_Mi, - "2MiB", - 2*1024*1024 -); +test_byte_parser!(test_bytes_MB, "2MB", 2 * 1000 * 1000); +test_byte_parser!(test_bytes_M, "2M", 2 * 1024 * 1024); +test_byte_parser!(test_bytes_Mi, "2MiB", 2 * 1024 * 1024); -test_byte_parser!( - test_bytes_GB, - "3GB", - 3*1000*1000*1000 -); -test_byte_parser!( - test_bytes_G, - "3G", - 3*1024*1024*1024 -); -test_byte_parser!( - test_bytes_Gi, - "3GiB", - 3*1024*1024*1024 -); +test_byte_parser!(test_bytes_GB, "3GB", 3 * 1000 * 1000 * 1000); +test_byte_parser!(test_bytes_G, "3G", 3 * 1024 * 1024 * 1024); +test_byte_parser!(test_bytes_Gi, "3GiB", 3 * 1024 * 1024 * 1024); -test_byte_parser!( - test_bytes_TB, - "4TB", - 4*1000*1000*1000*1000 -); -test_byte_parser!( - test_bytes_T, - "4T", - 4*1024*1024*1024*1024 -); -test_byte_parser!( - test_bytes_Ti, - "4TiB", - 4*1024*1024*1024*1024 -); +test_byte_parser!(test_bytes_TB, "4TB", 4 * 1000 * 1000 * 1000 * 1000); +test_byte_parser!(test_bytes_T, "4T", 4 * 1024 * 1024 * 1024 * 1024); +test_byte_parser!(test_bytes_Ti, "4TiB", 4 * 1024 * 1024 * 1024 * 1024); -test_byte_parser!( - test_bytes_PB, - "5PB", - 5*1000*1000*1000*1000*1000 -); -test_byte_parser!( - test_bytes_P, - "5P", - 5*1024*1024*1024*1024*1024 -); -test_byte_parser!( - test_bytes_Pi, - "5PiB", - 5*1024*1024*1024*1024*1024 -); +test_byte_parser!(test_bytes_PB, "5PB", 5 * 1000 * 1000 * 1000 * 1000 * 1000); +test_byte_parser!(test_bytes_P, "5P", 5 * 1024 * 1024 * 1024 * 1024 * 1024); +test_byte_parser!(test_bytes_Pi, "5PiB", 5 * 1024 * 1024 * 1024 * 1024 * 1024); test_byte_parser!( test_bytes_EB, "6EB", - 6*1000*1000*1000*1000*1000*1000 + 6 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 ); test_byte_parser!( test_bytes_E, "6E", - 6*1024*1024*1024*1024*1024*1024 + 6 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 ); test_byte_parser!( test_bytes_Ei, "6EiB", - 6*1024*1024*1024*1024*1024*1024 + 6 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 ); #[test] #[should_panic] #[allow(non_snake_case)] -fn test_KB_multiplier_error() -{ +fn test_KB_multiplier_error() { // KB is not valid (kB, K, and KiB are) let bs_str = "2000KB"; @@ -426,8 +308,7 @@ fn test_KB_multiplier_error() #[test] #[should_panic] -fn test_overflow_panic() -{ +fn test_overflow_panic() { let bs_str = format!("{}KiB", usize::MAX); parse_bytes_with_opt_multiplier(&bs_str).unwrap(); @@ -435,8 +316,7 @@ fn test_overflow_panic() #[test] #[should_panic] -fn test_neg_panic() -{ +fn test_neg_panic() { let bs_str = format!("{}KiB", -1); parse_bytes_with_opt_multiplier(&bs_str).unwrap();