Skip to content

Commit

Permalink
Merge pull request #5128 from tertsdiepraam/printf-rewrite
Browse files Browse the repository at this point in the history
`printf` rewrite (with a lot of `seq` changes)
  • Loading branch information
sylvestre authored Nov 28, 2023
2 parents 0e8197e + 8eb66ab commit 14a8e8a
Show file tree
Hide file tree
Showing 37 changed files with 1,812 additions and 3,336 deletions.
2 changes: 1 addition & 1 deletion src/uu/dd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ path = "src/dd.rs"
clap = { workspace = true }
gcd = { workspace = true }
libc = { workspace = true }
uucore = { workspace = true, features = ["memo", "quoting-style"] }
uucore = { workspace = true, features = ["format", "quoting-style"] }

[target.'cfg(any(target_os = "linux"))'.dependencies]
nix = { workspace = true, features = ["fs"] }
Expand Down
15 changes: 12 additions & 3 deletions src/uu/dd/src/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ use std::io::Write;
use std::sync::mpsc;
use std::time::Duration;

use uucore::error::UResult;
use uucore::memo::sprintf;
use uucore::{
error::UResult,
format::num_format::{FloatVariant, Formatter},
};

use crate::numbers::{to_magnitude_and_suffix, SuffixType};

Expand Down Expand Up @@ -152,7 +154,14 @@ impl ProgUpdate {
let (carriage_return, newline) = if rewrite { ("\r", "") } else { ("", "\n") };

// The duration should be formatted as in `printf %g`.
let duration_str = sprintf("%g", &[duration.to_string()])?;
let mut duration_str = Vec::new();
uucore::format::num_format::Float {
variant: FloatVariant::Shortest,
..Default::default()
}
.fmt(&mut duration_str, duration)?;
// We assume that printf will output valid UTF-8
let duration_str = std::str::from_utf8(&duration_str).unwrap();

// If the number of bytes written is sufficiently large, then
// print a more concise representation of the number, like
Expand Down
2 changes: 1 addition & 1 deletion src/uu/printf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ path = "src/printf.rs"

[dependencies]
clap = { workspace = true }
uucore = { workspace = true, features = ["memo", "quoting-style"] }
uucore = { workspace = true, features = ["format", "quoting-style"] }

[[bin]]
name = "printf"
Expand Down
27 changes: 23 additions & 4 deletions src/uu/printf/src/printf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
// spell-checker:ignore (change!) each's
// spell-checker:ignore (ToDO) LONGHELP FORMATSTRING templating parameterizing formatstr

use std::io::stdout;
use std::ops::ControlFlow;

use clap::{crate_version, Arg, ArgAction, Command};
use uucore::error::{UResult, UUsageError};
use uucore::memo::printf;
use uucore::format::{parse_spec_and_escape, FormatArgument};
use uucore::{format_usage, help_about, help_section, help_usage};

const VERSION: &str = "version";
Expand All @@ -30,12 +33,28 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let format_string = matches
.get_one::<String>(options::FORMATSTRING)
.ok_or_else(|| UUsageError::new(1, "missing operand"))?;
let values: Vec<String> = match matches.get_many::<String>(options::ARGUMENT) {
Some(s) => s.map(|s| s.to_string()).collect(),

let values: Vec<_> = match matches.get_many::<String>(options::ARGUMENT) {
Some(s) => s.map(|s| FormatArgument::Unparsed(s.to_string())).collect(),
None => vec![],
};

printf(format_string, &values[..])?;
let mut args = values.iter().peekable();
for item in parse_spec_and_escape(format_string.as_ref()) {
match item?.write(stdout(), &mut args)? {
ControlFlow::Continue(()) => {}
ControlFlow::Break(()) => return Ok(()),
};
}

while args.peek().is_some() {
for item in parse_spec_and_escape(format_string.as_ref()) {
match item?.write(stdout(), &mut args)? {
ControlFlow::Continue(()) => {}
ControlFlow::Break(()) => return Ok(()),
};
}
}
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion src/uu/seq/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ bigdecimal = { workspace = true }
clap = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
uucore = { workspace = true, features = ["memo", "quoting-style"] }
uucore = { workspace = true, features = ["format", "quoting-style"] }

[[bin]]
name = "seq"
Expand Down
54 changes: 5 additions & 49 deletions src/uu/seq/src/extendedbigdecimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,8 @@ use std::fmt::Display;
use std::ops::Add;

use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_bigint::ToBigInt;
use num_traits::One;
use num_traits::Zero;

use crate::extendedbigint::ExtendedBigInt;

#[derive(Debug, Clone)]
pub enum ExtendedBigDecimal {
/// Arbitrary precision floating point number.
Expand Down Expand Up @@ -72,53 +67,14 @@ pub enum ExtendedBigDecimal {
Nan,
}

/// The smallest integer greater than or equal to this number.
fn ceil(x: BigDecimal) -> BigInt {
if x.is_integer() {
// Unwrapping the Option because it always returns Some
x.to_bigint().unwrap()
} else {
(x + BigDecimal::one().half()).round(0).to_bigint().unwrap()
}
}

/// The largest integer less than or equal to this number.
fn floor(x: BigDecimal) -> BigInt {
if x.is_integer() {
// Unwrapping the Option because it always returns Some
x.to_bigint().unwrap()
} else {
(x - BigDecimal::one().half()).round(0).to_bigint().unwrap()
}
}

impl ExtendedBigDecimal {
/// The smallest integer greater than or equal to this number.
pub fn ceil(self) -> ExtendedBigInt {
match self {
Self::BigDecimal(x) => ExtendedBigInt::BigInt(ceil(x)),
other => From::from(other),
}
#[cfg(test)]
pub fn zero() -> Self {
Self::BigDecimal(0.into())
}

/// The largest integer less than or equal to this number.
pub fn floor(self) -> ExtendedBigInt {
match self {
Self::BigDecimal(x) => ExtendedBigInt::BigInt(floor(x)),
other => From::from(other),
}
}
}

impl From<ExtendedBigInt> for ExtendedBigDecimal {
fn from(big_int: ExtendedBigInt) -> Self {
match big_int {
ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)),
ExtendedBigInt::Infinity => Self::Infinity,
ExtendedBigInt::MinusInfinity => Self::MinusInfinity,
ExtendedBigInt::MinusZero => Self::MinusZero,
ExtendedBigInt::Nan => Self::Nan,
}
pub fn one() -> Self {
Self::BigDecimal(1.into())
}
}

Expand Down
214 changes: 0 additions & 214 deletions src/uu/seq/src/extendedbigint.rs

This file was deleted.

Loading

0 comments on commit 14a8e8a

Please sign in to comment.