refactor(tvix/eval): extract float formatting into a helper

This keeps the actual TotalDisplay implementation readable, as this
float formatting code suddenly made up the majority of its implementation.

Change-Id: I2c0d00e4a691e0b8ffbc72680f680e16feef4bee
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7925
Reviewed-by: flokli <flokli@flokli.de>
Autosubmit: tazjin <tazjin@tvl.su>
Tested-by: BuildkiteCI
This commit is contained in:
Vincent Ambo 2023-01-25 11:05:43 +03:00 committed by clbot
parent d05c380504
commit 164005656d

View file

@ -514,24 +514,9 @@ impl Display for Value {
}
}
impl TotalDisplay for Value {
fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
match self {
Value::Null => f.write_str("null"),
Value::Bool(true) => f.write_str("true"),
Value::Bool(false) => f.write_str("false"),
Value::Integer(num) => write!(f, "{}", num),
Value::String(s) => s.fmt(f),
Value::Path(p) => p.display().fmt(f),
Value::Attrs(attrs) => attrs.total_fmt(f, set),
Value::List(list) => list.total_fmt(f, set),
Value::Closure(_) => f.write_str("lambda"), // TODO: print position
Value::Builtin(builtin) => builtin.fmt(f),
// Nix prints floats with a maximum precision of 5 digits
// only. Except when it decides to use scientific notation
// (with a + after the `e`, and zero-padded to 0 digits)
Value::Float(num) => {
/// Emulates the C++-Nix style formatting of floats, which diverges
/// significantly from Rust's native float formatting.
fn total_fmt_float<F: std::fmt::Write>(num: f64, mut f: F) -> std::fmt::Result {
let mut buf = [b'0'; lexical_core::BUFFER_SIZE];
let mut s = lexical_core::write_with_options::<f64, { CXX_LITERAL }>(
num.clone(),
@ -601,7 +586,26 @@ impl TotalDisplay for Value {
}
write!(f, "{}", format!("{}", String::from_utf8_lossy(&s)))
}
}
impl TotalDisplay for Value {
fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
match self {
Value::Null => f.write_str("null"),
Value::Bool(true) => f.write_str("true"),
Value::Bool(false) => f.write_str("false"),
Value::Integer(num) => write!(f, "{}", num),
Value::String(s) => s.fmt(f),
Value::Path(p) => p.display().fmt(f),
Value::Attrs(attrs) => attrs.total_fmt(f, set),
Value::List(list) => list.total_fmt(f, set),
Value::Closure(_) => f.write_str("lambda"), // TODO: print position
Value::Builtin(builtin) => builtin.fmt(f),
// Nix prints floats with a maximum precision of 5 digits
// only. Except when it decides to use scientific notation
// (with a + after the `e`, and zero-padded to 0 digits)
Value::Float(num) => total_fmt_float(*num, f),
// internal types
Value::AttrNotFound => f.write_str("internal[not found]"),