Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_segments/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Bounded segment selection and independent launch requests.
3//!
4//! Games render the selection with their existing debug menu, own the load and
5//! spawn types, and apply their complete save state. Diagnostic reset launches
6//! remain a separate operation and never count as progression-backed coverage.
7//! This crate neither polls controllers nor owns a renderer or a mailbox.
8#![no_std]
9
10use core::ops::Range;
11
12/// Current control request version, separate from a game's observed gate state.
13pub const REQUEST_VERSION: u32 = 1;
14/// Launch from a real captured playthrough state.
15pub const MODE_PLAYTHROUGH: u32 = 1;
16/// Launch with the game's existing diagnostic reset behavior.
17pub const MODE_DIAGNOSTIC: u32 = 2;
18
19/// Immutable evidence for a game's complete captured state.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub struct Provenance<'a> {
22    /// Game save format version used to decode the capture.
23    pub save_version: u32,
24    /// Actual retained capture path or immutable repository reference.
25    pub capture: &'a str,
26    /// SHA-256 of the captured bytes, in lowercase hexadecimal.
27    pub capture_sha256: &'a str,
28    /// Retained normal-play journey or recording receipt.
29    pub playthrough: &'a str,
30}
31
32impl Provenance<'_> {
33    fn is_valid(&self) -> bool {
34        self.save_version != 0
35            && !self.capture.is_empty()
36            && !self.playthrough.is_empty()
37            && self.capture_sha256.len() == 64
38            && self
39                .capture_sha256
40                .bytes()
41                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
42    }
43}
44
45/// Availability of earned progression at this segment.
46#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub enum Progression<'a, State> {
48    /// No complete captured state exists; explain the missing evidence.
49    Unverified(&'a str),
50    /// Complete game-owned state decoded from a normal playthrough capture.
51    Verified {
52        /// State including every progression field needed for independent play.
53        state: State,
54        /// Evidence that produced this state.
55        provenance: &'a Provenance<'a>,
56    },
57}
58
59/// A row shared by the debug page, coverage export and journey launch lookup.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct Segment<'a, Load, Spawn, State> {
62    /// Stable game-assigned identifier; distinct from the display row index.
63    pub id: u32,
64    /// Player-facing segment name.
65    pub name: &'a str,
66    /// Game-owned load target.
67    pub load: Load,
68    /// Game-owned spawn description.
69    pub spawn: Spawn,
70    /// Full earned state, or the reason independent progression is unavailable.
71    pub progression: Progression<'a, State>,
72    /// Whether the game supports an explicit diagnostic reset for this row.
73    pub diagnostic: bool,
74}
75
76/// Fixed-width control request. Zero is an idle mailbox, never a launch.
77#[repr(C)]
78#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
79pub struct LaunchRequest {
80    /// Must equal [`REQUEST_VERSION`].
81    pub version: u32,
82    /// Stable [`Segment::id`] to launch.
83    pub segment_id: u32,
84    /// [`MODE_PLAYTHROUGH`] or [`MODE_DIAGNOSTIC`].
85    pub mode: u32,
86}
87
88impl LaunchRequest {
89    /// Idle request for initialization and clearing a consumed mailbox.
90    pub const IDLE: Self = Self {
91        version: 0,
92        segment_id: 0,
93        mode: 0,
94    };
95}
96
97/// Validated launch, borrowing the table without copying a save payload.
98#[derive(Debug, Eq, PartialEq)]
99pub enum Launch<'table, 'data, Load, Spawn, State> {
100    /// Complete captured state, available only with valid evidence metadata.
101    Playthrough {
102        /// Matching table row.
103        segment: &'table Segment<'data, Load, Spawn, State>,
104        /// Exact captured state borrowed from that row.
105        state: &'table State,
106        /// Capture provenance borrowed from that row.
107        provenance: &'table Provenance<'data>,
108    },
109    /// Explicit diagnostic reset, with no earned state supplied.
110    Diagnostic(&'table Segment<'data, Load, Spawn, State>),
111}
112
113/// Request or table rejection, before any game callback runs.
114#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub enum LaunchError {
116    /// Unsupported control protocol version.
117    Version,
118    /// Unknown launch mode.
119    Mode,
120    /// Table has ambiguous identifiers.
121    DuplicateId,
122    /// Stable identifier is absent from the table.
123    UnknownId,
124    /// No full playthrough state has been captured.
125    Unverified,
126    /// Capture metadata is absent or malformed.
127    Provenance,
128    /// Row does not permit diagnostic reset.
129    DiagnosticUnavailable,
130}
131
132/// Validate the whole identifier table and resolve a request before side effects.
133pub fn validate<'table, 'data, Load, Spawn, State>(
134    request: LaunchRequest,
135    table: &'table [Segment<'data, Load, Spawn, State>],
136) -> Result<Launch<'table, 'data, Load, Spawn, State>, LaunchError> {
137    if request.version != REQUEST_VERSION {
138        return Err(LaunchError::Version);
139    }
140    if request.mode != MODE_PLAYTHROUGH && request.mode != MODE_DIAGNOSTIC {
141        return Err(LaunchError::Mode);
142    }
143    for (index, segment) in table.iter().enumerate() {
144        if table[..index]
145            .iter()
146            .any(|previous| previous.id == segment.id)
147        {
148            return Err(LaunchError::DuplicateId);
149        }
150    }
151    let segment = table
152        .iter()
153        .find(|segment| segment.id == request.segment_id)
154        .ok_or(LaunchError::UnknownId)?;
155    if request.mode == MODE_DIAGNOSTIC {
156        return if segment.diagnostic {
157            Ok(Launch::Diagnostic(segment))
158        } else {
159            Err(LaunchError::DiagnosticUnavailable)
160        };
161    }
162    match &segment.progression {
163        Progression::Unverified(_) => Err(LaunchError::Unverified),
164        Progression::Verified { state, provenance } if provenance.is_valid() => {
165            Ok(Launch::Playthrough {
166                segment,
167                state,
168                provenance,
169            })
170        }
171        Progression::Verified { .. } => Err(LaunchError::Provenance),
172    }
173}
174
175/// An explicit result for a once-consumed control request.
176#[derive(Clone, Copy, Debug, Eq, PartialEq)]
177pub enum ConsumeResult<T, E> {
178    /// Mailbox was zero; neither callback ran.
179    Idle,
180    /// Validation failed; neither callback ran.
181    Rejected(LaunchError),
182    /// The selected game callback ran exactly once and returned this result.
183    Applied(Result<T, E>),
184}
185
186/// Consume a locally owned request before validation or callbacks.
187///
188/// Games that expose a volatile mailbox must first read and clear it through
189/// their own synchronized control channel, then pass that local request here.
190/// Never share this ordinary reference directly with an asynchronous writer.
191/// Callback failure still consumes the request; retries require a new request.
192pub fn consume<Load, Spawn, State, T, E>(
193    request: &mut LaunchRequest,
194    table: &[Segment<'_, Load, Spawn, State>],
195    playthrough: impl FnOnce(&Load, &Spawn, &State, &Provenance<'_>) -> Result<T, E>,
196    diagnostic: impl FnOnce(&Load, &Spawn) -> Result<T, E>,
197) -> ConsumeResult<T, E> {
198    let pending = core::mem::replace(request, LaunchRequest::IDLE);
199    if pending == LaunchRequest::IDLE {
200        return ConsumeResult::Idle;
201    }
202    match validate(pending, table) {
203        Err(error) => ConsumeResult::Rejected(error),
204        Ok(Launch::Playthrough {
205            segment,
206            state,
207            provenance,
208        }) => ConsumeResult::Applied(playthrough(
209            &segment.load,
210            &segment.spawn,
211            state,
212            provenance,
213        )),
214        Ok(Launch::Diagnostic(segment)) => {
215            ConsumeResult::Applied(diagnostic(&segment.load, &segment.spawn))
216        }
217    }
218}
219
220/// Allocator-free selection whose bounds are fixed at construction.
221#[derive(Clone, Copy, Debug, Eq, PartialEq)]
222pub struct Selection {
223    selected: usize,
224    count: usize,
225}
226
227impl Selection {
228    /// Select the first row of a table with `count` rows.
229    pub const fn new(count: usize) -> Self {
230        Self { selected: 0, count }
231    }
232    /// Current row, or no row for an empty table.
233    pub const fn selected(&self) -> Option<usize> {
234        if self.count == 0 {
235            None
236        } else {
237            Some(self.selected)
238        }
239    }
240    /// Move up one row, wrapping at the first row.
241    pub fn previous(&mut self) {
242        if self.count != 0 {
243            self.selected = if self.selected == 0 {
244                self.count - 1
245            } else {
246                self.selected - 1
247            };
248        }
249    }
250    /// Move down one row, wrapping at the last row.
251    pub fn next(&mut self) {
252        if self.count != 0 {
253            self.selected = if self.selected == self.count - 1 {
254                0
255            } else {
256                self.selected + 1
257            };
258        }
259    }
260    /// Visible rows, centered on selection where the table bounds permit.
261    /// A zero row capacity always returns an empty range.
262    pub fn visible_range(&self, row_count: usize) -> Range<usize> {
263        let visible = row_count.min(self.count);
264        let start = self
265            .selected
266            .saturating_sub(visible / 2)
267            .min(self.count - visible);
268        start..start + visible
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use core::cell::Cell;
276
277    // Synthetic unit fixture only; this is not a captured game state.
278    fn row() -> Segment<'static, u16, [i32; 3], u32> {
279        Segment {
280            id: 7,
281            name: "unit fixture",
282            load: 96,
283            spawn: [1, 2, 3],
284            progression: Progression::Verified {
285                state: 42,
286                provenance: &Provenance {
287                    save_version: 4,
288                    capture: "unit fixture bytes",
289                    capture_sha256:
290                        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
291                    playthrough: "unit fixture receipt",
292                },
293            },
294            diagnostic: true,
295        }
296    }
297    fn request(mode: u32) -> LaunchRequest {
298        LaunchRequest {
299            version: REQUEST_VERSION,
300            segment_id: 7,
301            mode,
302        }
303    }
304
305    #[test]
306    fn selection_stays_bounded_and_wraps() {
307        let mut empty = Selection::new(0);
308        empty.previous();
309        empty.next();
310        assert_eq!(empty.selected(), None);
311        assert_eq!(empty.visible_range(5), 0..0);
312        let mut selection = Selection::new(10);
313        selection.previous();
314        assert_eq!(selection.selected(), Some(9));
315        assert_eq!(selection.visible_range(4), 6..10);
316        selection.next();
317        assert_eq!(selection.selected(), Some(0));
318        assert_eq!(selection.visible_range(4), 0..4);
319        assert_eq!(selection.visible_range(0), 0..0);
320        assert_eq!(selection.visible_range(usize::MAX), 0..10);
321        let mut single = Selection::new(1);
322        single.next();
323        single.previous();
324        assert_eq!(single.selected(), Some(0));
325    }
326
327    #[test]
328    fn malformed_requests_and_tables_fail_closed() {
329        let table = [row()];
330        assert_eq!(
331            validate(LaunchRequest::IDLE, &table),
332            Err(LaunchError::Version)
333        );
334        assert_eq!(validate(request(0), &table), Err(LaunchError::Mode));
335        assert_eq!(
336            validate(
337                request(MODE_PLAYTHROUGH),
338                &[] as &[Segment<'_, u16, [i32; 3], u32>]
339            ),
340            Err(LaunchError::UnknownId)
341        );
342        let mut unknown = request(MODE_PLAYTHROUGH);
343        unknown.segment_id = u32::MAX;
344        assert_eq!(validate(unknown, &table), Err(LaunchError::UnknownId));
345        assert_eq!(
346            validate(request(MODE_PLAYTHROUGH), &[row(), row()]),
347            Err(LaunchError::DuplicateId)
348        );
349    }
350
351    #[test]
352    fn rejection_consumes_request_without_callbacks() {
353        let mut unverified = row();
354        unverified.progression = Progression::Unverified("capture missing");
355        let calls = Cell::new(0);
356        let mut pending = request(MODE_PLAYTHROUGH);
357        let result: ConsumeResult<(), ()> = consume(
358            &mut pending,
359            &[unverified],
360            |_, _, _, _| {
361                calls.set(calls.get() + 1);
362                Ok(())
363            },
364            |_, _| {
365                calls.set(calls.get() + 1);
366                Ok(())
367            },
368        );
369        assert_eq!(result, ConsumeResult::Rejected(LaunchError::Unverified));
370        assert_eq!(pending, LaunchRequest::IDLE);
371        assert_eq!(calls.get(), 0);
372    }
373
374    #[test]
375    fn callback_failure_still_consumes_exactly_once() {
376        let calls = Cell::new(0);
377        let table = [row()];
378        let mut pending = request(MODE_PLAYTHROUGH);
379        let result = consume(
380            &mut pending,
381            &table,
382            |load, spawn, state, provenance| {
383                calls.set(calls.get() + 1);
384                assert_eq!((*load, *spawn, *state), (96, [1, 2, 3], 42));
385                assert_eq!(
386                    *provenance,
387                    match table[0].progression {
388                        Progression::Verified { provenance, .. } => *provenance,
389                        _ => unreachable!(),
390                    }
391                );
392                Err::<(), _>("game refused")
393            },
394            |_, _| panic!("unexpected diagnostic launch"),
395        );
396        assert_eq!(result, ConsumeResult::Applied(Err("game refused")));
397        let again: ConsumeResult<(), ()> = consume(
398            &mut pending,
399            &table,
400            |_, _, _, _| panic!("request replayed"),
401            |_, _| panic!("request replayed"),
402        );
403        assert_eq!(again, ConsumeResult::Idle);
404        assert_eq!(calls.get(), 1);
405    }
406
407    #[test]
408    fn diagnostics_do_not_need_or_supply_earned_state() {
409        let mut segment = row();
410        segment.progression = Progression::Unverified("capture missing");
411        let mut pending = request(MODE_DIAGNOSTIC);
412        let result: ConsumeResult<u16, ()> = consume(
413            &mut pending,
414            &[segment],
415            |_, _, _, _| panic!("unverified state used"),
416            |load, _| Ok(*load),
417        );
418        assert_eq!(result, ConsumeResult::Applied(Ok(96)));
419        segment.diagnostic = false;
420        assert_eq!(
421            validate(request(MODE_DIAGNOSTIC), &[segment]),
422            Err(LaunchError::DiagnosticUnavailable)
423        );
424    }
425
426    #[test]
427    fn invalid_provenance_never_becomes_playthrough_launch() {
428        let mut segment = row();
429        let mut invalid = match segment.progression {
430            Progression::Verified { provenance, .. } => *provenance,
431            _ => unreachable!(),
432        };
433        invalid.capture_sha256 = "missing";
434        segment.progression = Progression::Verified {
435            state: 42,
436            provenance: &invalid,
437        };
438        assert_eq!(
439            validate(request(MODE_PLAYTHROUGH), &[segment]),
440            Err(LaunchError::Provenance)
441        );
442    }
443}