From 0034e99fe88f861a995f5cc80bc7759c2e779799 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:31:15 -0700 Subject: [PATCH] link: time out requests by upstream's RTT rule; tools share formatters --- crates/rns-runtime/src/link_client.rs | 41 ++-- crates/rns-tools/src/commands/rnpath.rs | 120 +++--------- crates/rns-tools/src/commands/rnprobe.rs | 34 +--- crates/rns-tools/src/commands/rnstatus.rs | 218 +--------------------- crates/rns-tools/src/format.rs | 205 ++++++++++++++++++++ 5 files changed, 264 insertions(+), 354 deletions(-) diff --git a/crates/rns-runtime/src/link_client.rs b/crates/rns-runtime/src/link_client.rs index 76be2fd..aea5941 100644 --- a/crates/rns-runtime/src/link_client.rs +++ b/crates/rns-runtime/src/link_client.rs @@ -34,6 +34,8 @@ pub enum LinkClientError { TransportUnavailable, #[error("timed out waiting for {0}")] Timeout(&'static str), + #[error("request sent but failed: {0}")] + RequestFailed(RequestFailure), #[error("could not discover remote identity public key for destination")] PubkeyNotDiscovered, #[error("link proof validation failed: {0}")] @@ -50,6 +52,15 @@ pub enum LinkClientError { StampFailure(#[from] rns_link::stamp::LinkStampError), } +/// Why a sent request ended without a response (`RequestReceipt.FAILED`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum RequestFailure { + #[error("no response within the request timeout")] + TimedOut, + #[error("link closed while the request was pending")] + LinkClosed, +} + #[derive(Clone)] pub struct LinkClient { transport_tx: mpsc::Sender, @@ -77,7 +88,10 @@ impl LinkClient { /// `payload` is one encoded MessagePack value, or empty to send nil. /// /// `overall_timeout` supplies remaining budgets for discovery, Link proof and - /// response waits. Registration, endpoint binding, sends and teardown can + /// response waits. The response wait is also bounded by the request timeout + /// `Link.request` derives from the measured RTT; when that expires, or the + /// link closes with the request pending, the result is + /// [`LinkClientError::RequestFailed`]. Registration, endpoint binding, sends and teardown can /// await transport admission/replies outside that budget. Wrap the call in /// an outer timeout when the entire operation needs a deadline. pub async fn query( @@ -203,7 +217,7 @@ impl LinkClient { ); self.send_link_packet(link_id, identify_pkt).await?; - let req_timeout = Duration::from_secs(5); + let req_timeout = link.default_request_timeout(); // An empty payload sends nil, as Link.request(path) does. let packed_data = (!payload.is_empty()).then_some(payload.as_slice()); let (encrypted_req, request_id) = link @@ -311,10 +325,12 @@ async fn wait_for_response( deadline: Duration, req_timeout: Duration, ) -> Result, LinkClientError> { - // The request deadline applies until a response Resource is accepted; + // The request timeout, capped by the overall deadline, applies until a + // response Resource is accepted; // after that the Resource watchdog ends a stalled transfer (Link.py:1475-1522). // Between segments no watchdog runs, so the request timeout bounds each gap. - let deadline_at = Instant::now() + deadline; + let request_bound = deadline >= req_timeout; + let deadline_at = Instant::now() + deadline.min(req_timeout); let mut segment_gap_since: Option = None; let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new(); // Split response: segment payloads in order, file metadata flag of segment 1. @@ -327,7 +343,11 @@ async fn wait_for_response( let wait = if !receiving { let remaining = deadline_at.saturating_duration_since(Instant::now()); if remaining.is_zero() { - return Err(LinkClientError::Timeout("response")); + return Err(if request_bound { + LinkClientError::RequestFailed(RequestFailure::TimedOut) + } else { + LinkClientError::Timeout("response") + }); } remaining.min(WATCHDOG_TICK) } else if let Some(since) = segment_gap_since { @@ -344,9 +364,8 @@ async fn wait_for_response( "destination channel closed".into(), ))?, terminal = endpoint.lifecycle_rx.recv() => { - return Err(LinkClientError::HandshakeFailed(format!( - "link endpoint terminated: {terminal:?}" - ))); + tracing::debug!("link endpoint terminated: {terminal:?}"); + return Err(LinkClientError::RequestFailed(RequestFailure::LinkClosed)); } _ = tokio::time::sleep(wait) => { poll_response_resources(transport_tx, link, link_id, &mut inbound_resources) @@ -356,7 +375,7 @@ async fn wait_for_response( }; match ev { DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => { - return Err(LinkClientError::HandshakeFailed("link closed".into())); + return Err(LinkClientError::RequestFailed(RequestFailure::LinkClosed)); } DestinationEvent::InboundPacket { raw, @@ -643,9 +662,7 @@ async fn wait_for_response( rns_wire::context::PacketContext::LinkClose if link.receive_teardown(body) => { - return Err(LinkClientError::HandshakeFailed( - "link closed by remote".into(), - )); + return Err(LinkClientError::RequestFailed(RequestFailure::LinkClosed)); } _ => {} } diff --git a/crates/rns-tools/src/commands/rnpath.rs b/crates/rns-tools/src/commands/rnpath.rs index 21ad576..ebe7201 100644 --- a/crates/rns-tools/src/commands/rnpath.rs +++ b/crates/rns-tools/src/commands/rnpath.rs @@ -18,7 +18,7 @@ use rns_identity::destination::Destination; use rns_identity::identity::Identity; use rns_runtime::config::Config; use rns_runtime::lifecycle::ShutdownSignal; -use rns_runtime::link_client::{LinkClient, LinkClientError}; +use rns_runtime::link_client::{LinkClient, LinkClientError, RequestFailure}; use rns_runtime::platform::resolve_config_dir; use rns_runtime::reticulum::{ InitOptions, InstanceMode, ReticulumConfig, ReticulumHandle, SharedInstanceRpcEndpoint, init, @@ -26,7 +26,7 @@ use rns_runtime::reticulum::{ }; use rns_runtime::rpc::{self, RpcRequest, RpcResponse}; use rns_tools::RS_RETICULUM_VERSION; -use rns_tools::format::pretty_hex_rep; +use rns_tools::format::{PyNum, pretty_cost, pretty_hex_rep, prettytime, py_float_repr, py_round}; use rns_transport::constants::PATH_REQUEST_TIMEOUT; use rns_transport::messages::PathRequestOptions; @@ -486,7 +486,10 @@ fn blackhole_lines( let identity = pretty_hex_rep(&entry.identity); let until = match entry.until { Some(until) if until != 0.0 => { - format!("for {}", py_prettytime((until - now).max(0.0), false)) + format!( + "for {}", + prettytime(PyNum::Float((until - now).max(0.0)), false) + ) } _ => "indefinitely".to_string(), }; @@ -670,7 +673,7 @@ fn path_table_line(entry: &rpc::PathTableEntry, now: f64) -> String { entry.hops, pretty_hex_rep(entry.via.as_deref().unwrap_or_default()), entry.interface, - py_prettytime(entry.expires - now, true), + prettytime(PyNum::Float(entry.expires - now), true), cost_suffix(entry.value, entry.lr_cost) ) } @@ -685,14 +688,6 @@ fn cost_suffix(value: Option, lr_cost: Option) -> String { format!("(dv:{}/lc:{})", pretty_cost(value), pretty_cost(lr_cost)) } -/// `RNS.prettycost`: the quantized cost to three decimals, `n` when absent. -fn pretty_cost(value: Option) -> String { - match value.map(rns_identity::stamps::quantize_cost) { - Some(Ok(cost)) => format!("{cost:.3}"), - _ => "n".to_string(), - } -} - /// `json.dumps` of the path table rows with bytes as hex (rnpath.py:276-282). /// Upstream sends `value` and `used` as int 0 when unset, and floats otherwise. fn path_table_json(entries: &[rpc::PathTableEntry]) -> String { @@ -1165,7 +1160,7 @@ async fn remote_query( print!("{OUTPUT_RST}Sending request... "); flush(); let client = LinkClient::new(handle.transport_tx.clone(), identity); - client + match client .query( transport_hash, app, @@ -1175,14 +1170,18 @@ async fn remote_query( REMOTE_LINK_TIMEOUT, ) .await - .map_err(|e| { + { + // A timed-out receipt has no response; callers report it as a failed request. + Err(LinkClientError::RequestFailed(RequestFailure::TimedOut)) => Ok(Vec::new()), + result => result.map_err(|e| { print!("{OUTPUT_RST}"); match e { LinkClientError::Timeout(_) => println!("The link timed out, exiting now"), _ => println!("Link closed unexpectedly, exiting now"), } ExitCode::from(10) - }) + }), + } } /// rnpath.py:146-206: `-p` fetches `/list` from the transport whose identity @@ -1366,53 +1365,6 @@ fn remote_request_failed() -> ExitCode { ExitCode::from(10) } -/// `RNS.prettytime` (RNS/__init__.py:239-290), not verbose. -fn py_prettytime(time: f64, compact: bool) -> String { - let neg = time < 0.0; - let mut time = time.abs(); - let days = (time / 86400.0).floor(); - time %= 86400.0; - let hours = (time / 3600.0).floor(); - time %= 3600.0; - let minutes = (time / 60.0).floor(); - time %= 60.0; - let seconds = if compact { - time.trunc() - } else { - py_round(time, 2) - }; - - let mut components = Vec::new(); - for (value, unit) in [(days, "d"), (hours, "h"), (minutes, "m")] { - if value > 0.0 && (!compact || components.len() < 2) { - components.push(format!("{}{unit}", value as i64)); - } - } - if seconds > 0.0 && (!compact || components.len() < 2) { - let seconds = if compact { - format!("{}", seconds as i64) - } else { - py_float_repr(seconds) - }; - components.push(format!("{seconds}s")); - } - let mut out = String::new(); - let count = components.len(); - for (i, c) in components.iter().enumerate() { - if i > 0 { - out.push_str(if i + 1 < count { ", " } else { " and " }); - } - out.push_str(c); - } - if out.is_empty() { - "0s".to_string() - } else if neg { - format!("-{out}") - } else { - out - } -} - /// rnpath.py:542-561 for an integer timestamp, from `datetime` differences. fn pretty_date(time: f64, now: f64) -> String { let diff = now - time; @@ -1448,38 +1400,6 @@ fn pretty_date(time: f64, now: f64) -> String { format!("{} years", day_diff / 365) } -/// Python `round(x, n)` for a float. -fn py_round(value: f64, digits: usize) -> f64 { - format!("{value:.digits$}").parse().unwrap_or(value) -} - -/// Python `repr(float)`: shortest round-trip digits, scientific notation -/// outside `1e-4 <= |x| < 1e16`. -fn py_float_repr(value: f64) -> String { - if value.is_nan() { - return "nan".to_string(); - } - if value.is_infinite() { - return if value > 0.0 { "inf" } else { "-inf" }.to_string(); - } - let sci = format!("{value:e}"); - let (mantissa, exponent) = sci - .split_once('e') - .expect("scientific format has an exponent"); - let exponent: i32 = exponent.parse().expect("integer exponent"); - if value == 0.0 || (-4..16).contains(&exponent) { - let fixed = format!("{value}"); - if fixed.contains('.') { - fixed - } else { - format!("{fixed}.0") - } - } else { - let sign = if exponent < 0 { '-' } else { '+' }; - format!("{mantissa}e{sign}{:02}", exponent.abs()) - } -} - /// A `json.dumps` string with the default `ensure_ascii`. fn py_json_str(s: &str) -> String { let mut out = String::from("\""); @@ -1524,11 +1444,19 @@ mod tests { fn formatting_matches_upstream_helpers() { for case in cases("prettytime_compact") { let t = case[0].as_f64().unwrap(); - assert_eq!(py_prettytime(t, true), case[1].as_str().unwrap(), "{t}"); + assert_eq!( + prettytime(PyNum::Float(t), true), + case[1].as_str().unwrap(), + "{t}" + ); } for case in cases("prettytime") { let t = case[0].as_f64().unwrap(); - assert_eq!(py_prettytime(t, false), case[1].as_str().unwrap(), "{t}"); + assert_eq!( + prettytime(PyNum::Float(t), false), + case[1].as_str().unwrap(), + "{t}" + ); } let now = fixture()["pretty_date_now"].as_f64().unwrap(); for case in cases("pretty_date") { diff --git a/crates/rns-tools/src/commands/rnprobe.rs b/crates/rns-tools/src/commands/rnprobe.rs index 0676f34..41a5999 100644 --- a/crates/rns-tools/src/commands/rnprobe.rs +++ b/crates/rns-tools/src/commands/rnprobe.rs @@ -16,7 +16,7 @@ use rns_identity::destination::{ }; use rns_runtime::reticulum::{InstanceMode, ReticulumHandle}; use rns_tools::RS_RETICULUM_VERSION; -use rns_tools::format::pretty_hex_rep; +use rns_tools::format::{pretty_hex_rep, py_float_repr, py_round}; use rns_transport::link_messages::{DestinationEvent, PacketMetrics}; use rns_transport::messages::{ OutboundRequest, PathRequestOptions, TransportMessage, TransportQuery, TransportQueryResponse, @@ -652,38 +652,6 @@ fn flush() { let _ = std::io::stdout().flush(); } -/// Python `round(x, n)` for a float. -fn py_round(value: f64, digits: usize) -> f64 { - format!("{value:.digits$}").parse().unwrap_or(value) -} - -/// Python `repr(float)`: shortest round-trip digits, scientific notation -/// outside `1e-4 <= |x| < 1e16`. -fn py_float_repr(value: f64) -> String { - if value.is_nan() { - return "nan".to_string(); - } - if value.is_infinite() { - return if value > 0.0 { "inf" } else { "-inf" }.to_string(); - } - let sci = format!("{value:e}"); - let (mantissa, exponent) = sci - .split_once('e') - .expect("scientific format has an exponent"); - let exponent: i32 = exponent.parse().expect("integer exponent"); - if value == 0.0 || (-4..16).contains(&exponent) { - let fixed = format!("{value}"); - if fixed.contains('.') { - fixed - } else { - format!("{fixed}.0") - } - } else { - let sign = if exponent < 0 { '-' } else { '+' }; - format!("{mantissa}e{sign}{:02}", exponent.abs()) - } -} - struct JsonOk<'a> { rtt: Duration, hops: u8, diff --git a/crates/rns-tools/src/commands/rnstatus.rs b/crates/rns-tools/src/commands/rnstatus.rs index 5a37d22..9e5fd8b 100644 --- a/crates/rns-tools/src/commands/rnstatus.rs +++ b/crates/rns-tools/src/commands/rnstatus.rs @@ -28,6 +28,10 @@ use rns_runtime::reticulum::{ }; use rns_runtime::rpc::{self, ManageOperation, RpcRequest}; use rns_tools::RS_RETICULUM_VERSION; +use rns_tools::format::{ + PyNum as Num, pretty_cost, prettyfrequency, prettyshorttime, prettysize, prettyspeed, + prettytime, py_float_repr, py_round, +}; use rns_transport::constants::PATH_REQUEST_TIMEOUT; use rns_transport::discovery::{DiscoveredInterface, DiscoveryStatus, DiscoveryStore}; use rns_transport::messages::PathRequestOptions; @@ -734,16 +738,8 @@ impl Session { } } -/// LinkClient reports these only once the request has been sent -/// (link_client.rs `wait_for_response`). fn request_went_unanswered(error: &LinkClientError) -> bool { - match error { - LinkClientError::Timeout(stage) => *stage == "response", - LinkClientError::HandshakeFailed(reason) => { - reason == "link closed by remote" || reason.starts_with("link endpoint terminated") - } - _ => false, - } + matches!(error, LinkClientError::RequestFailed(_)) } /// The stored info dictionary as `list_discovered_interfaces` returns it: @@ -1677,35 +1673,6 @@ fn py_eq_bool(value: &Value, b: bool) -> bool { } } -#[derive(Debug, Clone, Copy)] -enum Num { - Int(i64), - Float(f64), -} - -impl Num { - fn f(self) -> f64 { - match self { - Num::Int(i) => i as f64, - Num::Float(f) => f, - } - } - - fn i(self) -> i64 { - match self { - Num::Int(i) => i, - Num::Float(f) => f as i64, - } - } - - fn py_str(self) -> String { - match self { - Num::Int(i) => i.to_string(), - Num::Float(f) => py_float_repr(f), - } - } -} - fn num(value: Option<&Value>) -> Num { match value { Some(Value::Integer(i)) => i @@ -1854,59 +1821,6 @@ fn py_json_str(s: &str) -> String { out } -// --------------------------------------------------------------------------- -// Upstream's formatting helpers (RNS/__init__.py, rnstatus.py:971-984). - -/// Python `round(x, n)` for a float. -fn py_round(value: f64, digits: usize) -> f64 { - format!("{value:.digits$}").parse().unwrap_or(value) -} - -/// Python `repr(float)`. -fn py_float_repr(value: f64) -> String { - if value.is_nan() { - return "nan".to_string(); - } - if value.is_infinite() { - return if value > 0.0 { "inf" } else { "-inf" }.to_string(); - } - let sci = format!("{value:e}"); - let (mantissa, exponent) = sci.split_once('e').unwrap_or((&sci, "0")); - let exponent: i32 = exponent.parse().unwrap_or(0); - if value == 0.0 || (-4..16).contains(&exponent) { - let fixed = format!("{value}"); - if fixed.contains('.') { - fixed - } else { - format!("{fixed}.0") - } - } else { - let sign = if exponent < 0 { '-' } else { '+' }; - format!("{mantissa}e{sign}{:02}", exponent.abs()) - } -} - -/// `RNS.prettysize`. -fn prettysize(num: f64, suffix: &str) -> String { - let mut num = num; - for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] { - if num.abs() < 1000.0 { - return if unit.is_empty() { - format!("{num:.0} {unit}{suffix}") - } else { - format!("{num:.2} {unit}{suffix}") - }; - } - num /= 1000.0; - } - format!("{num:.2}Y{suffix}") -} - -/// `RNS.prettyspeed`: `prettysize(num/8, suffix="b")+"ps"`. -fn prettyspeed(num: f64) -> String { - format!("{}ps", prettysize(num, "b")) -} - /// rnstatus.py `speed_str`. fn speed_str(num: f64) -> String { let mut num = num; @@ -1919,128 +1833,6 @@ fn speed_str(num: f64) -> String { format!("{num:.2} Ybps") } -/// `RNS.prettyfrequency`. -fn prettyfrequency(hz: Num, suffix: &str, d: usize, lpf: bool) -> String { - if hz.f() == 0.0 { - return "0 Hz".to_string(); - } - let mut num = if lpf { hz } else { Num::Float(hz.f() * 1e6) }; - let units: &[&str] = if lpf { - &["", "K", "M", "G", "T", "P", "E", "Z"] - } else { - &["µ", "m", "", "K", "M", "G", "T", "P", "E", "Z"] - }; - for unit in units { - if num.f().abs() < 1000.0 { - return if d == 2 { - format!("{:.2} {unit}{suffix}", num.f()) - } else { - let rounded = match num { - Num::Int(i) => Num::Int(i), - Num::Float(f) => Num::Float(py_round(f, d)), - }; - format!("{} {unit}{suffix}", rounded.py_str()) - }; - } - num = Num::Float(num.f() / 1000.0); - } - format!("{:.2}Y{suffix}", num.f()) -} - -/// `RNS.prettytime(t, compact=...)`, not verbose. -fn prettytime(time: Num, compact: bool) -> String { - let neg = time.f() < 0.0; - let (days, hours, minutes, seconds) = match time { - Num::Int(t) => { - let t = t.abs(); - let rest = t % 86400; - ( - t / 86400, - rest / 3600, - (rest % 3600) / 60, - Num::Int(rest % 3600 % 60), - ) - } - Num::Float(t) => { - let t = t.abs(); - let days = (t / 86400.0).floor(); - let mut rest = t % 86400.0; - let hours = (rest / 3600.0).floor(); - rest %= 3600.0; - let minutes = (rest / 60.0).floor(); - rest %= 60.0; - let seconds = if compact { - Num::Int(rest as i64) - } else { - Num::Float(py_round(rest, 2)) - }; - (days as i64, hours as i64, minutes as i64, seconds) - } - }; - let mut components = Vec::new(); - for (value, unit) in [(days, "d"), (hours, "h"), (minutes, "m")] { - if value > 0 && (!compact || components.len() < 2) { - components.push(format!("{value}{unit}")); - } - } - if seconds.f() > 0.0 && (!compact || components.len() < 2) { - components.push(format!("{}s", seconds.py_str())); - } - let count = components.len(); - let mut out = String::new(); - for (i, c) in components.iter().enumerate() { - if i > 0 { - out.push_str(if i + 1 < count { ", " } else { " and " }); - } - out.push_str(c); - } - if out.is_empty() { - "0s".to_string() - } else if neg { - format!("-{out}") - } else { - out - } -} - -/// `RNS.prettyshorttime(t, tight=True)`. -fn prettyshorttime(time: f64) -> String { - let neg = time < 0.0; - let mut time = (time * 1e6).abs(); - let seconds = (time / 1e6).floor() as i64; - time %= 1e6; - let millis = (time / 1e3).floor() as i64; - time %= 1e3; - let micros = py_round(time, 2); - let mut components = Vec::new(); - if seconds > 0 { - components.push(format!("{seconds}s")); - } - if millis > 0 { - components.push(format!("{millis}ms")); - } - if micros > 0.0 { - components.push(format!("{}µs", py_float_repr(micros))); - } - let out = components.join(" "); - if out.is_empty() { - "0us".to_string() - } else if neg { - format!("-{out}") - } else { - out - } -} - -/// `RNS.prettycost`: the quantized cost to three decimals, `n` for -/// anything but a number. -fn pretty_cost(cost: Option) -> String { - match cost.map(rns_identity::stamps::quantize_cost) { - Some(Ok(cost)) => format!("{cost:.3}"), - _ => "n".to_string(), - } -} - fn unix_now() -> f64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/crates/rns-tools/src/format.rs b/crates/rns-tools/src/format.rs index addb34c..11b2df8 100644 --- a/crates/rns-tools/src/format.rs +++ b/crates/rns-tools/src/format.rs @@ -78,6 +78,211 @@ pub fn pretty_hex_rep(data: &[u8]) -> String { format!("<{}>", hex::encode(data)) } +// Python-format helpers: byte-identical to the RNS/__init__.py functions each one names. + +/// A MessagePack number as Python holds it: `int` and `float` print differently. +#[derive(Debug, Clone, Copy)] +pub enum PyNum { + Int(i64), + Float(f64), +} + +impl PyNum { + pub fn f(self) -> f64 { + match self { + PyNum::Int(i) => i as f64, + PyNum::Float(f) => f, + } + } + + pub fn i(self) -> i64 { + match self { + PyNum::Int(i) => i, + PyNum::Float(f) => f as i64, + } + } + + pub fn py_str(self) -> String { + match self { + PyNum::Int(i) => i.to_string(), + PyNum::Float(f) => py_float_repr(f), + } + } +} + +/// Python `round(x, n)` for a float. +pub fn py_round(value: f64, digits: usize) -> f64 { + format!("{value:.digits$}").parse().unwrap_or(value) +} + +/// Python `repr(float)`: shortest round-trip digits, scientific notation +/// outside `1e-4 <= |x| < 1e16`. +pub fn py_float_repr(value: f64) -> String { + if value.is_nan() { + return "nan".to_string(); + } + if value.is_infinite() { + return if value > 0.0 { "inf" } else { "-inf" }.to_string(); + } + let sci = format!("{value:e}"); + let (mantissa, exponent) = sci.split_once('e').unwrap_or((&sci, "0")); + let exponent: i32 = exponent.parse().unwrap_or(0); + if value == 0.0 || (-4..16).contains(&exponent) { + let fixed = format!("{value}"); + if fixed.contains('.') { + fixed + } else { + format!("{fixed}.0") + } + } else { + let sign = if exponent < 0 { '-' } else { '+' }; + format!("{mantissa}e{sign}{:02}", exponent.abs()) + } +} + +/// `RNS.prettysize`. +pub fn prettysize(num: f64, suffix: &str) -> String { + let mut num = num; + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] { + if num.abs() < 1000.0 { + return if unit.is_empty() { + format!("{num:.0} {unit}{suffix}") + } else { + format!("{num:.2} {unit}{suffix}") + }; + } + num /= 1000.0; + } + format!("{num:.2}Y{suffix}") +} + +/// `RNS.prettyspeed`: `prettysize(num/8, suffix="b")+"ps"`. +pub fn prettyspeed(num: f64) -> String { + format!("{}ps", prettysize(num, "b")) +} + +/// `RNS.prettyfrequency`. +pub fn prettyfrequency(hz: PyNum, suffix: &str, d: usize, lpf: bool) -> String { + if hz.f() == 0.0 { + return "0 Hz".to_string(); + } + let mut num = if lpf { hz } else { PyNum::Float(hz.f() * 1e6) }; + let units: &[&str] = if lpf { + &["", "K", "M", "G", "T", "P", "E", "Z"] + } else { + &["µ", "m", "", "K", "M", "G", "T", "P", "E", "Z"] + }; + for unit in units { + if num.f().abs() < 1000.0 { + return if d == 2 { + format!("{:.2} {unit}{suffix}", num.f()) + } else { + let rounded = match num { + PyNum::Int(i) => PyNum::Int(i), + PyNum::Float(f) => PyNum::Float(py_round(f, d)), + }; + format!("{} {unit}{suffix}", rounded.py_str()) + }; + } + num = PyNum::Float(num.f() / 1000.0); + } + format!("{:.2}Y{suffix}", num.f()) +} + +/// `RNS.prettytime(t, compact=...)`, not verbose. +pub fn prettytime(time: PyNum, compact: bool) -> String { + let neg = time.f() < 0.0; + let (days, hours, minutes, seconds) = match time { + PyNum::Int(t) => { + let t = t.abs(); + let rest = t % 86400; + ( + t / 86400, + rest / 3600, + (rest % 3600) / 60, + PyNum::Int(rest % 3600 % 60), + ) + } + PyNum::Float(t) => { + let t = t.abs(); + let days = (t / 86400.0).floor(); + let mut rest = t % 86400.0; + let hours = (rest / 3600.0).floor(); + rest %= 3600.0; + let minutes = (rest / 60.0).floor(); + rest %= 60.0; + let seconds = if compact { + PyNum::Int(rest as i64) + } else { + PyNum::Float(py_round(rest, 2)) + }; + (days as i64, hours as i64, minutes as i64, seconds) + } + }; + let mut components = Vec::new(); + for (value, unit) in [(days, "d"), (hours, "h"), (minutes, "m")] { + if value > 0 && (!compact || components.len() < 2) { + components.push(format!("{value}{unit}")); + } + } + if seconds.f() > 0.0 && (!compact || components.len() < 2) { + components.push(format!("{}s", seconds.py_str())); + } + let count = components.len(); + let mut out = String::new(); + for (i, c) in components.iter().enumerate() { + if i > 0 { + out.push_str(if i + 1 < count { ", " } else { " and " }); + } + out.push_str(c); + } + if out.is_empty() { + "0s".to_string() + } else if neg { + format!("-{out}") + } else { + out + } +} + +/// `RNS.prettyshorttime(t, tight=True)`. +pub fn prettyshorttime(time: f64) -> String { + let neg = time < 0.0; + let mut time = (time * 1e6).abs(); + let seconds = (time / 1e6).floor() as i64; + time %= 1e6; + let millis = (time / 1e3).floor() as i64; + time %= 1e3; + let micros = py_round(time, 2); + let mut components = Vec::new(); + if seconds > 0 { + components.push(format!("{seconds}s")); + } + if millis > 0 { + components.push(format!("{millis}ms")); + } + if micros > 0.0 { + components.push(format!("{}µs", py_float_repr(micros))); + } + let out = components.join(" "); + if out.is_empty() { + "0us".to_string() + } else if neg { + format!("-{out}") + } else { + out + } +} + +/// `RNS.prettycost`: the quantized cost to three decimals, `n` for +/// anything but a number. +pub fn pretty_cost(cost: Option) -> String { + match cost.map(rns_identity::stamps::quantize_cost) { + Some(Ok(cost)) => format!("{cost:.3}"), + _ => "n".to_string(), + } +} + #[cfg(test)] mod tests { use super::*;