Skip to main content

cli/
perf.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Developer-facing performance profiling helpers.
3//!
4//! The profile surface is intentionally env-gated so the public CLI
5//! stays focused. `HEDDLE_PROFILE=1` writes human-readable timings to
6//! stderr; stdout remains reserved for normal text/JSON command output.
7
8use std::time::Duration;
9
10#[derive(Clone, Copy, Debug)]
11pub struct ProfileField {
12    pub name: &'static str,
13    pub value: u128,
14}
15
16impl ProfileField {
17    pub fn millis(name: &'static str, value_ms: u128) -> Self {
18        Self {
19            name,
20            value: value_ms,
21        }
22    }
23
24    pub fn duration(name: &'static str, value: Duration) -> Self {
25        Self {
26            name,
27            value: value.as_millis(),
28        }
29    }
30
31    pub fn count(name: &'static str, value: impl Into<u128>) -> Self {
32        Self {
33            name,
34            value: value.into(),
35        }
36    }
37}
38
39pub fn profile_enabled() -> bool {
40    std::env::var("HEDDLE_PROFILE")
41        .map(|value| {
42            let normalized = value.trim().to_ascii_lowercase();
43            !matches!(normalized.as_str(), "" | "0" | "false" | "no" | "off")
44        })
45        .unwrap_or(false)
46}
47
48pub fn emit_profile(command: &str, fields: &[ProfileField]) {
49    if !profile_enabled() {
50        return;
51    }
52
53    eprintln!("heddle profile:");
54    eprintln!("  command: {command}");
55    for field in fields {
56        eprintln!("  {}: {}", field.name, field.value);
57    }
58}