From 71c23f089533635c92e8fa06658e322f26798aba Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Mar 2026 06:26:44 +0000 Subject: [PATCH] [refactor](trx-frontend-http): pre-allocate spectrum encoding output Replace format! with pre-allocated String::with_capacity for spectrum frame encoding, reducing allocation overhead in the hot SSE path. https://claude.ai/code/session_01XzurkeuUmamBuhQwxVy7T4 Signed-off-by: Claude --- .../trx-frontend/trx-frontend-http/src/api.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/trx-client/trx-frontend/trx-frontend-http/src/api.rs b/src/trx-client/trx-frontend/trx-frontend-http/src/api.rs index 75933df..4eed79c 100644 --- a/src/trx-client/trx-frontend/trx-frontend-http/src/api.rs +++ b/src/trx-client/trx-frontend/trx-frontend-http/src/api.rs @@ -71,13 +71,22 @@ fn base64_encode(data: &[u8]) -> String { /// RDS is intentionally excluded — it changes rarely and is sent via the /// `/events` state stream instead. fn encode_spectrum_frame(frame: &trx_core::rig::state::SpectrumData) -> String { - let bytes: Vec = frame + // Encode directly from the iterator to avoid an intermediate Vec. + let clamped: Vec = frame .bins .iter() .map(|&v| v.round().clamp(-128.0, 127.0) as i8 as u8) .collect(); - let b64 = base64_encode(&bytes); - format!("{},{},{b64}", frame.center_hz, frame.sample_rate) + let b64 = base64_encode(&clamped); + + // Pre-allocate: header digits + 2 commas + base64 body. + let mut out = String::with_capacity(40 + b64.len()); + out.push_str(&frame.center_hz.to_string()); + out.push(','); + out.push_str(&frame.sample_rate.to_string()); + out.push(','); + out.push_str(&b64); + out } #[derive(serde::Serialize)]