Skip to main content

aft_base/
list_envelope.rs

1use serde::{Deserialize, Serialize};
2
3/// Maximum total count before render-time display clamping (R23).
4pub const R23_MAX_DISPLAY_TOTAL: usize = 999_999_999;
5/// Threshold at or above which total count is clamped to `≥999999999` (R23).
6pub const R23_CLAMP_THRESHOLD: usize = 1_000_000_000;
7
8/// Reason why a list-shaped surface was cut short.
9/// Precedence ordering: TimeLimit > Walk > Depth > Budget > Cap > Kind.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum Reason {
13    /// Entries were counted instead of listed because of what kind of file
14    /// holds them (grep counts lockfile and log lines, for example).
15    Kind,
16    Cap,
17    Budget,
18    Depth,
19    Walk,
20    TimeLimit,
21}
22
23impl Reason {
24    /// Numerical precedence rank: higher value means higher precedence.
25    pub const fn precedence(self) -> u8 {
26        match self {
27            Self::TimeLimit => 5,
28            Self::Walk => 4,
29            Self::Depth => 3,
30            Self::Budget => 2,
31            Self::Cap => 1,
32            Self::Kind => 0,
33        }
34    }
35
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::TimeLimit => "time limit",
39            Self::Walk => "walk",
40            Self::Depth => "depth",
41            Self::Budget => "budget",
42            Self::Cap => "cap",
43            Self::Kind => "kind",
44        }
45    }
46}
47
48/// Permitted unit word for a list-shaped surface.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum Unit {
52    Sites,
53    Paths,
54    Files,
55    Results,
56    Rows,
57    Lines,
58    Items,
59    Directories,
60    Hops,
61}
62
63impl Unit {
64    pub const fn as_str(self) -> &'static str {
65        match self {
66            Self::Sites => "sites",
67            Self::Paths => "paths",
68            Self::Files => "files",
69            Self::Results => "results",
70            Self::Rows => "rows",
71            Self::Lines => "lines",
72            Self::Items => "items",
73            Self::Directories => "directories",
74            Self::Hops => "hops",
75        }
76    }
77}
78
79impl std::fmt::Display for Unit {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{}", self.as_str())
82    }
83}
84
85/// Total count of items, either exact or a proved lower bound.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
88pub enum Total {
89    Exact(usize),
90    AtLeast(usize),
91}
92
93impl Total {
94    pub fn value(&self) -> usize {
95        match *self {
96            Total::Exact(v) | Total::AtLeast(v) => v,
97        }
98    }
99
100    pub fn is_exact(&self) -> bool {
101        matches!(self, Total::Exact(_))
102    }
103
104    pub fn is_at_least(&self) -> bool {
105        matches!(self, Total::AtLeast(_))
106    }
107}
108
109/// Common truncation envelope returned beside list-shaped replies.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct ListEnvelope {
112    pub shown: usize,
113    pub total: Total,
114    pub unit: Unit,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub reason: Option<Reason>,
117    pub causes: Vec<Reason>,
118    pub narrow: Vec<String>,
119}
120
121impl ListEnvelope {
122    pub fn new(
123        shown: usize,
124        total: Total,
125        unit: Unit,
126        mut causes: Vec<Reason>,
127        narrow: &[&str],
128    ) -> Self {
129        causes.sort_by(|a, b| b.precedence().cmp(&a.precedence()));
130        causes.dedup();
131        let reason = causes.first().copied();
132        Self {
133            shown,
134            total,
135            unit,
136            reason,
137            causes,
138            narrow: narrow.iter().map(|s| s.to_string()).collect(),
139        }
140    }
141}
142
143/// Format a total count in the envelope's form: bare integer for Exact,
144/// prefixed with `≥` for AtLeast, and clamped to `≥999999999` if >= 1e9 (R23).
145pub fn render_total(total: &Total) -> String {
146    if total.value() >= R23_CLAMP_THRESHOLD {
147        format!("≥{R23_MAX_DISPLAY_TOTAL}")
148    } else {
149        match *total {
150            Total::Exact(v) => format!("{v}"),
151            Total::AtLeast(v) => format!("≥{v}"),
152        }
153    }
154}
155
156/// Render the trailer text for a list envelope.
157///
158/// Trailer grammar (pinned):
159/// `shown <n> of <total> <unit> (<reason>) · narrow: <a>, <b>`
160/// - Decimal integers, no separators
161/// - `Exact` bare, `AtLeast` prefixed `≥`
162/// - No trailing punctuation
163/// - Narrow clause omitted only for surfaces with `narrow: []`
164/// - Emitted iff `reason.is_some()`
165/// - Clamped to `≥999999999` at render time if `total.value >= 1e9`
166pub fn render_trailer(envelope: &ListEnvelope) -> Option<String> {
167    let reason = envelope.reason?;
168    let shown = envelope.shown;
169
170    let total_str = render_total(&envelope.total);
171
172    let unit_str = envelope.unit.as_str();
173    let reason_str = reason.as_str();
174
175    let base = format!("shown {shown} of {total_str} {unit_str} ({reason_str})");
176    if envelope.narrow.is_empty() {
177        Some(base)
178    } else {
179        Some(format!("{base} · narrow: {}", envelope.narrow.join(", ")))
180    }
181}
182
183/// Measure the rendered trailer byte length without exposing trailer text to producers (R13).
184pub fn measure_trailer_len(envelope: &ListEnvelope) -> usize {
185    render_trailer(envelope).map(|s| s.len()).unwrap_or(0)
186}
187
188/// Derive the wire key for serializing a list envelope per R14/R21.
189/// - For array lists: `<last-id-segment>_list_envelope` beside the array in its owning object.
190/// - For text surfaces: `<full-id-with-_-replacing-.>_list_envelope` at the reply root.
191pub fn derive_wire_key(list_id: &str, is_text_surface: bool) -> String {
192    if is_text_surface {
193        format!("{}_list_envelope", list_id.replace('.', "_"))
194    } else {
195        let last_segment = list_id.rsplit('.').next().unwrap_or(list_id);
196        format!("{last_segment}_list_envelope")
197    }
198}