From 15317b11456b99d3bcd616e914353e39e478d697 Mon Sep 17 00:00:00 2001 From: juntaochi <53086415+juntaochi@users.noreply.github.com> Date: Tue, 26 May 2026 15:57:14 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Bolt:=20Optimize=20string=20formatt?= =?UTF-8?q?ing=20in=20App::update?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inlined integer calculations and formatting logic into single `format!` macros to eliminate nested, intermediate heap allocations during high-frequency TUI updates. Also removed unused helper functions. --- src/ui/mod.rs | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 6bbba9d..5ecc206 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -9,7 +9,6 @@ use ratatui::{ }; use std::borrow::Cow; use std::sync::Arc; -use std::time::Duration; use tokio::task::JoinHandle; use crate::artwork::converter::ArtworkConverter; @@ -444,22 +443,24 @@ impl App { cache.artist = track.artist.to_uppercase(); cache.album = track.album.to_uppercase(); } - let progress_percent = if track.duration.as_secs() > 0 { + let pos_secs = track.position.as_secs(); + let dur_secs = track.duration.as_secs(); + + let progress_percent = if dur_secs > 0 { ((track.position.as_secs_f64() / track.duration.as_secs_f64()) * 100.0) as u16 } else { 0 }; + + // Optimized formatting to eliminate nested heap allocations cache.duration_str = format!( - "{} / {}", - format_duration(track.position), - format_duration(track.duration) - ); - cache.gauge_label = format!( - " {}/{} | {:02}% ", - format_duration_seconds(track.position), - format_duration_seconds(track.duration), - progress_percent + "{:02}:{:02} / {:02}:{:02}", + pos_secs / 60, + pos_secs % 60, + dur_secs / 60, + dur_secs % 60 ); + cache.gauge_label = format!(" {}s/{}s | {:02}% ", pos_secs, dur_secs, progress_percent); cache.progress_percent = progress_percent; self.metadata_cache = Some(cache); } else { @@ -1029,18 +1030,6 @@ pub fn draw(f: &mut Frame, app: &mut App) { } } -fn format_duration_seconds(duration: Duration) -> String { - let total_seconds = duration.as_secs(); - format!("{}s", total_seconds) -} - -fn format_duration(duration: Duration) -> String { - let total_seconds = duration.as_secs(); - let minutes = total_seconds / 60; - let seconds = total_seconds % 60; - format!("{:02}:{:02}", minutes, seconds) -} - // Optimized: Uses iterator chaining/cycling to avoid intermediate Vec and format! allocations. // Benchmark: ~32% speedup (329ms vs 484ms for 100k iters). fn scroll_text<'a>(text: &'a str, width: usize, frame: u32) -> Cow<'a, str> { @@ -1070,6 +1059,7 @@ mod tests { use async_trait::async_trait; use ratatui::backend::TestBackend; use ratatui::Terminal; + use std::time::Duration; struct MockPlayer { volume: u8,