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

psx_settings/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Shared, allocator-free game preferences.
3//!
4//! The record holds settings that recur across PSoXide games, seven
5//! game-owned flag bits and [`GAME_BYTES_LEN`] game-owned bytes. Games remain
6//! free to keep larger simulation or renderer-specific data in their own saves.
7//! The byte format is explicit and checksummed so a newer executable can reject
8//! a torn or incompatible card write and fall back to its shipped defaults.
9
10#![no_std]
11#![warn(missing_docs)]
12
13use psx_display::{Brightness, ScreenOffset};
14use psx_pad::ActionMap;
15
16/// On-card record magic.
17pub const MAGIC: [u8; 4] = *b"PSST";
18/// Current record format version.
19///
20/// Version 1 held a 0..=100 brightness percentage that no game used. Version 2
21/// replaced it with the [`Brightness`] step (the save byte of
22/// [`Brightness::to_byte`]) and added the [`ScreenOffset`] bytes after the
23/// checksum. Version 3 adds [`GAME_BYTES_LEN`] game-owned bytes after the
24/// screen offset and brings those two offset bytes under the checksum.
25/// [`Profile::decode`] reads versions 1 and 2 and gives every field they lack
26/// its default (the picture options for version 1, zeroed game bytes for both);
27/// [`Profile::encode`] writes version 3.
28///
29/// An executable built before version 3 refuses a version 3 record with
30/// [`CodecError::UnsupportedVersion`] and falls back to its shipped defaults,
31/// exactly as it does for a torn record. A record carries no way for older code
32/// to skip a layout it does not know, so there is no partial load: keep a game
33/// and its save on the same SDK, or accept a settings reset on rollback.
34pub const VERSION: u8 = 3;
35/// The oldest record version [`Profile::decode`] reads.
36const OLDEST_VERSION: u8 = 1;
37/// Header bytes before action bindings and scores, in a version 1 record.
38const HEADER_LEN_V1: usize = 16;
39/// Header bytes before action bindings and scores, in a version 2 record:
40/// the version 1 header plus the screen X and Y bytes.
41const HEADER_LEN_V2: usize = 18;
42/// Number of game-defined bytes in a [`Profile`] (version 3 onward).
43///
44/// Eight bytes keep every record far inside [`MAX_RECORD_LEN`] (the largest
45/// shipping shape, 9 actions and no scores, grows from 54 to 62 bytes) and a
46/// settings file is one 8 KiB memory-card block whatever its length, so the
47/// card footprint does not change.
48pub const GAME_BYTES_LEN: usize = 8;
49/// Header bytes before action bindings and scores, in a version 3 record:
50/// the version 2 header plus [`GAME_BYTES_LEN`] game bytes.
51const HEADER_LEN: usize = HEADER_LEN_V2 + GAME_BYTES_LEN;
52/// Offset of the checksum byte in every version.
53const CHECKSUM_AT: usize = 15;
54/// Bytes occupied by one action binding.
55const BINDING_LEN: usize = 4;
56/// Bytes occupied by one high score.
57const SCORE_LEN: usize = 4;
58/// Largest settings record accepted by the card helpers.
59pub const MAX_RECORD_LEN: usize = 128;
60
61/// Settings flag: invert vertical look.
62pub const FLAG_INVERT_Y: u8 = 1 << 0;
63/// Bits in the existing settings flag byte owned by each game. Bit 0 stays
64/// reserved for [`FLAG_INVERT_Y`], and no future shared setting may use these
65/// seven bits. Unknown game bits survive loading, sanitizing and saving with
66/// this SDK. Older executables masked these bits on load and may erase them on
67/// a later save, so rolling back a game build cannot preserve their meaning.
68pub const GAME_FLAGS_MASK: u8 = !FLAG_INVERT_Y;
69
70/// A game profile shared by menus, input and memory-card persistence.
71///
72/// `ACTIONS` is the number of game-defined logical actions. `SCORES` is the
73/// number of high-score slots (usually one per difficulty).
74#[derive(Copy, Clone, Debug, PartialEq, Eq)]
75pub struct Profile<const ACTIONS: usize, const SCORES: usize> {
76    /// Picture brightness: `DEFAULT`, `DARKER 1..=5` or `BRIGHTER 1..=5`.
77    pub brightness: Brightness,
78    /// Picture position on the television, within 16 pixels each way.
79    pub screen_offset: ScreenOffset,
80    /// Sound-effect volume, 0..=100.
81    pub sfx_volume: u8,
82    /// Music volume, 0..=100.
83    pub music_volume: u8,
84    /// Left-stick deadzone in raw stick counts.
85    pub move_deadzone: u8,
86    /// Right-stick deadzone in raw stick counts.
87    pub look_deadzone: u8,
88    /// Look-speed percentage.
89    pub look_speed_percent: u8,
90    /// Game-selected difficulty index.
91    pub difficulty: u8,
92    /// Bit flags: bit 0 is [`FLAG_INVERT_Y`], bits 1 through 7 belong to the
93    /// game. Prefer [`Self::set_game_flag`] so unrelated bits survive edits.
94    pub flags: u8,
95    /// Bytes reserved for the game's own settings, zero by default and stored
96    /// verbatim (version 3 onward). The SDK never reads, clamps or interprets
97    /// them, so a game must range-check what it loads from its own slots.
98    /// Name each slot with a `const` index in the game, for example
99    /// `const FOV_BYTE: usize = 0;`. A slot a game has not written reads as 0,
100    /// including from a version 1 or 2 record, so make 0 mean "default".
101    pub game_bytes: [u8; GAME_BYTES_LEN],
102    /// Logical action bindings.
103    pub actions: ActionMap<ACTIONS>,
104    /// Persistent high-score slots.
105    pub high_scores: [u32; SCORES],
106}
107
108impl<const ACTIONS: usize, const SCORES: usize> Profile<ACTIONS, SCORES> {
109    /// Construct a profile with common presentation/input defaults and the
110    /// caller's game-specific action map.
111    pub const fn new(actions: ActionMap<ACTIONS>) -> Self {
112        Self {
113            brightness: Brightness::DEFAULT,
114            screen_offset: ScreenOffset::CENTRE,
115            sfx_volume: 100,
116            music_volume: 100,
117            move_deadzone: 18,
118            look_deadzone: 12,
119            look_speed_percent: 100,
120            difficulty: 1,
121            flags: 0,
122            game_bytes: [0; GAME_BYTES_LEN],
123            actions,
124            high_scores: [0; SCORES],
125        }
126    }
127
128    /// Exact encoded byte length for this profile shape (the current version).
129    pub const fn encoded_len() -> usize {
130        HEADER_LEN + ACTIONS * BINDING_LEN + SCORES * SCORE_LEN
131    }
132
133    /// Clamp user-controlled values to safe shared ranges. Flag bits are
134    /// preserved because the game owns bits 1 through 7.
135    pub fn sanitize(&mut self) {
136        // `Brightness` and `ScreenOffset` clamp in their constructors, so any
137        // value a profile holds is already inside -5..=5 and -16..=16.
138        self.sfx_volume = self.sfx_volume.min(100);
139        self.music_volume = self.music_volume.min(100);
140        self.move_deadzone = self.move_deadzone.clamp(0, 64);
141        self.look_deadzone = self.look_deadzone.clamp(0, 64);
142        self.look_speed_percent = self.look_speed_percent.clamp(25, 200);
143    }
144
145    /// Whether vertical look is inverted.
146    pub const fn invert_y(&self) -> bool {
147        self.flags & FLAG_INVERT_Y != 0
148    }
149
150    /// Enable or disable inverted vertical look.
151    pub fn set_invert_y(&mut self, enabled: bool) {
152        if enabled {
153            self.flags |= FLAG_INVERT_Y;
154        } else {
155            self.flags &= !FLAG_INVERT_Y;
156        }
157    }
158
159    /// Return the raw game-owned bits in the settings flag byte.
160    pub const fn game_flags(&self) -> u8 {
161        self.flags & GAME_FLAGS_MASK
162    }
163
164    /// Set or clear the selected game-owned bits without changing any other
165    /// bits. Bit 0 is ignored even if it appears in `mask`.
166    pub fn set_game_flag(&mut self, mask: u8, enabled: bool) {
167        let mask = mask & GAME_FLAGS_MASK;
168        if enabled {
169            self.flags |= mask;
170        } else {
171            self.flags &= !mask;
172        }
173    }
174
175    /// Raise one high-score slot when `score` beats it. Returns `true` if the
176    /// profile changed and should be persisted.
177    pub fn submit_score(&mut self, slot: usize, score: u32) -> bool {
178        let Some(best) = self.high_scores.get_mut(slot) else {
179            return false;
180        };
181        if score <= *best {
182            return false;
183        }
184        *best = score;
185        true
186    }
187
188    /// Encode into `out` as a version 3 record, returning the bytes used.
189    pub fn encode(&self, out: &mut [u8]) -> Result<usize, CodecError> {
190        let len = Self::encoded_len();
191        if len > MAX_RECORD_LEN || out.len() < len {
192            return Err(CodecError::BufferTooSmall);
193        }
194        out[..len].fill(0);
195        out[..4].copy_from_slice(&MAGIC);
196        out[4] = VERSION;
197        out[5] = ACTIONS as u8;
198        out[6] = SCORES as u8;
199        out[7] = self.flags;
200        out[8] = self.brightness.to_byte();
201        out[9] = self.sfx_volume;
202        out[10] = self.music_volume;
203        out[11] = self.move_deadzone;
204        out[12] = self.look_deadzone;
205        out[13] = self.look_speed_percent;
206        out[14] = self.difficulty;
207        let [screen_x, screen_y] = self.screen_offset.to_bytes();
208        out[16] = screen_x;
209        out[17] = screen_y;
210        out[HEADER_LEN_V2..HEADER_LEN].copy_from_slice(&self.game_bytes);
211        let mut cursor = HEADER_LEN;
212        for binding in self.actions.bindings() {
213            put_u16(out, cursor, binding.primary);
214            put_u16(out, cursor + 2, binding.secondary);
215            cursor += BINDING_LEN;
216        }
217        for score in self.high_scores {
218            put_u32(out, cursor, score);
219            cursor += SCORE_LEN;
220        }
221        // Version 3 seals every byte but the checksum itself.
222        out[CHECKSUM_AT] = checksum(&out[..CHECKSUM_AT], &out[CHECKSUM_AT + 1..len]);
223        Ok(len)
224    }
225
226    /// Decode a profile of this exact action/score shape, from a record of
227    /// the current version or of version 1 or 2. A version 1 record carries no
228    /// picture options, so those read as their defaults; a record older than
229    /// version 3 carries no game bytes, so those read as zero. Every other
230    /// field is preserved.
231    pub fn decode(bytes: &[u8]) -> Result<Self, CodecError> {
232        if bytes.len() < HEADER_LEN_V1 {
233            return Err(CodecError::BufferTooSmall);
234        }
235        if bytes[..4] != MAGIC {
236            return Err(CodecError::BadMagic);
237        }
238        let version = bytes[4];
239        if !(OLDEST_VERSION..=VERSION).contains(&version) {
240            return Err(CodecError::UnsupportedVersion);
241        }
242        let header_len = match version {
243            1 => HEADER_LEN_V1,
244            2 => HEADER_LEN_V2,
245            _ => HEADER_LEN,
246        };
247        let len = header_len + ACTIONS * BINDING_LEN + SCORES * SCORE_LEN;
248        if len > MAX_RECORD_LEN || bytes.len() < len {
249            return Err(CodecError::BufferTooSmall);
250        }
251        if bytes[5] as usize != ACTIONS || bytes[6] as usize != SCORES {
252            return Err(CodecError::WrongShape);
253        }
254        // Versions 1 and 2 sealed the first 15 bytes and the payload after
255        // the header, leaving the version 2 screen offset bytes unprotected;
256        // version 3 seals everything but the checksum.
257        let sealed = if version >= 3 {
258            checksum(&bytes[..CHECKSUM_AT], &bytes[CHECKSUM_AT + 1..len])
259        } else {
260            checksum(&bytes[..CHECKSUM_AT], &bytes[header_len..len])
261        };
262        if bytes[CHECKSUM_AT] != sealed {
263            return Err(CodecError::BadChecksum);
264        }
265        let (brightness, screen_offset) = if version == 1 {
266            (Brightness::DEFAULT, ScreenOffset::CENTRE)
267        } else {
268            (
269                Brightness::from_byte(bytes[8]),
270                ScreenOffset::from_bytes([bytes[16], bytes[17]]),
271            )
272        };
273        let mut game_bytes = [0; GAME_BYTES_LEN];
274        if version >= 3 {
275            game_bytes.copy_from_slice(&bytes[HEADER_LEN_V2..HEADER_LEN]);
276        }
277        let mut cursor = header_len;
278        let mut bindings = [psx_pad::ActionBinding::UNBOUND; ACTIONS];
279        for binding in &mut bindings {
280            binding.primary = get_u16(bytes, cursor);
281            binding.secondary = get_u16(bytes, cursor + 2);
282            cursor += BINDING_LEN;
283        }
284        let mut high_scores = [0; SCORES];
285        for score in &mut high_scores {
286            *score = get_u32(bytes, cursor);
287            cursor += SCORE_LEN;
288        }
289        let mut profile = Self {
290            brightness,
291            screen_offset,
292            sfx_volume: bytes[9],
293            music_volume: bytes[10],
294            move_deadzone: bytes[11],
295            look_deadzone: bytes[12],
296            look_speed_percent: bytes[13],
297            difficulty: bytes[14],
298            flags: bytes[7],
299            game_bytes,
300            actions: ActionMap::new(bindings),
301            high_scores,
302        };
303        profile.sanitize();
304        Ok(profile)
305    }
306}
307
308/// Settings codec failure.
309#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310pub enum CodecError {
311    /// The supplied byte slice cannot contain this profile shape.
312    BufferTooSmall,
313    /// The record is not a PSoXide settings record.
314    BadMagic,
315    /// The record belongs to an unsupported format version.
316    UnsupportedVersion,
317    /// The record carries different action or score counts.
318    WrongShape,
319    /// The record was damaged or only partly written.
320    BadChecksum,
321}
322
323/// Persistence failure from the settings layer.
324#[cfg(feature = "card")]
325#[derive(Copy, Clone, Debug, PartialEq, Eq)]
326pub enum CardError {
327    /// Memory-card filesystem or transport failure.
328    Card(psx_mc::Error),
329    /// Settings codec failure.
330    Codec(CodecError),
331}
332
333/// Save one profile into a standard PS1 memory-card file.
334///
335/// A card without the `MC` header is not written to: this returns
336/// `CardError::Card(psx_mc::Error::NotFormatted)` and leaves the card as it
337/// was, so the game can ask the player before calling
338/// [`format_and_save`]. Formatting drops every save on the card from its
339/// directory.
340#[cfg(feature = "card")]
341pub fn save<B: psx_mc::Block, const ACTIONS: usize, const SCORES: usize>(
342    card: &mut psx_mc::Card<B>,
343    name: &str,
344    title: &str,
345    profile: &Profile<ACTIONS, SCORES>,
346) -> Result<(), CardError> {
347    if !card.is_formatted().map_err(CardError::Card)? {
348        return Err(CardError::Card(psx_mc::Error::NotFormatted));
349    }
350    let mut bytes = [0u8; MAX_RECORD_LEN];
351    let len = profile.encode(&mut bytes).map_err(CardError::Codec)?;
352    card.write(name, title, &bytes[..len])
353        .map_err(CardError::Card)
354}
355
356/// Format the card if it has no `MC` header, then save the profile. Call
357/// this only after the player agreed to format: it replaces the directory of
358/// an unformatted card, and every save the card held stops being listed. A
359/// formatted card is left alone and the profile is saved onto it.
360#[cfg(feature = "card")]
361pub fn format_and_save<B: psx_mc::Block, const ACTIONS: usize, const SCORES: usize>(
362    card: &mut psx_mc::Card<B>,
363    name: &str,
364    title: &str,
365    profile: &Profile<ACTIONS, SCORES>,
366) -> Result<(), CardError> {
367    if !card.is_formatted().map_err(CardError::Card)? {
368        card.format().map_err(CardError::Card)?;
369    }
370    save(card, name, title, profile)
371}
372
373/// Load one exact profile shape from a standard PS1 memory-card file.
374#[cfg(feature = "card")]
375pub fn load<B: psx_mc::Block, const ACTIONS: usize, const SCORES: usize>(
376    card: &mut psx_mc::Card<B>,
377    name: &str,
378) -> Result<Profile<ACTIONS, SCORES>, CardError> {
379    let mut bytes = [0u8; MAX_RECORD_LEN];
380    let len = card.read(name, &mut bytes).map_err(CardError::Card)?;
381    Profile::decode(&bytes[..len]).map_err(CardError::Codec)
382}
383
384/// Save a profile to the controller-1 memory-card slot, driving the port
385/// through `port`. Existing files with the same name are replaced. A card that
386/// is not formatted is refused with `CardError::Card(psx_mc::Error::NotFormatted)`
387/// and not touched; use [`format_and_save_to_slot_one`] once the player has
388/// agreed to format.
389#[cfg(feature = "card")]
390pub fn save_to_slot_one<const ACTIONS: usize, const SCORES: usize>(
391    port: &mut psx_mc::ControllerPort,
392    name: &str,
393    title: &str,
394    profile: &Profile<ACTIONS, SCORES>,
395) -> Result<(), CardError> {
396    let mut card = psx_mc::Card::new(psx_mc::HardwareCard::on_port(port, psx_mc::Slot::One));
397    save(&mut card, name, title, profile)
398}
399
400/// [`save_to_slot_one`] on a token the caller does not hold.
401#[cfg(feature = "card")]
402#[deprecated(note = "use `save_to_slot_one` with the `ControllerPort` token")]
403pub fn save_slot_one<const ACTIONS: usize, const SCORES: usize>(
404    name: &str,
405    title: &str,
406    profile: &Profile<ACTIONS, SCORES>,
407) -> Result<(), CardError> {
408    save_to_slot_one(&mut steal_port(), name, title, profile)
409}
410
411/// [`format_and_save`] on the controller-1 memory-card slot. This is the
412/// call that can erase a card's directory; reach it only from an explicit
413/// "format this card?" answer.
414#[cfg(feature = "card")]
415pub fn format_and_save_to_slot_one<const ACTIONS: usize, const SCORES: usize>(
416    port: &mut psx_mc::ControllerPort,
417    name: &str,
418    title: &str,
419    profile: &Profile<ACTIONS, SCORES>,
420) -> Result<(), CardError> {
421    let mut card = psx_mc::Card::new(psx_mc::HardwareCard::on_port(port, psx_mc::Slot::One));
422    format_and_save(&mut card, name, title, profile)
423}
424
425/// Load a profile from the controller-1 memory-card slot, driving the port
426/// through `port`.
427#[cfg(feature = "card")]
428pub fn load_from_slot_one<const ACTIONS: usize, const SCORES: usize>(
429    port: &mut psx_mc::ControllerPort,
430    name: &str,
431) -> Result<Profile<ACTIONS, SCORES>, CardError> {
432    let mut card = psx_mc::Card::new(psx_mc::HardwareCard::on_port(port, psx_mc::Slot::One));
433    load(&mut card, name)
434}
435
436/// [`load_from_slot_one`] on a token the caller does not hold.
437#[cfg(feature = "card")]
438#[deprecated(note = "use `load_from_slot_one` with the `ControllerPort` token")]
439pub fn load_slot_one<const ACTIONS: usize, const SCORES: usize>(
440    name: &str,
441) -> Result<Profile<ACTIONS, SCORES>, CardError> {
442    load_from_slot_one(&mut steal_port(), name)
443}
444
445/// The token for a deprecated forwarder that never took one.
446#[cfg(feature = "card")]
447fn steal_port() -> psx_mc::ControllerPort {
448    // SAFETY: a token is a logic guard, not a memory-safety one (see
449    // `psx_io::periph`), and the old functions never took one.
450    unsafe { psx_mc::ControllerPort::steal() }
451}
452
453#[inline]
454fn put_u16(out: &mut [u8], offset: usize, value: u16) {
455    out[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
456}
457
458#[inline]
459fn put_u32(out: &mut [u8], offset: usize, value: u32) {
460    out[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
461}
462
463#[inline]
464fn get_u16(bytes: &[u8], offset: usize) -> u16 {
465    u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
466}
467
468#[inline]
469fn get_u32(bytes: &[u8], offset: usize) -> u32 {
470    u32::from_le_bytes([
471        bytes[offset],
472        bytes[offset + 1],
473        bytes[offset + 2],
474        bytes[offset + 3],
475    ])
476}
477
478fn checksum(header: &[u8], payload: &[u8]) -> u8 {
479    let mut value = 0xa7u8;
480    for byte in header.iter().chain(payload) {
481        value = value.rotate_left(1) ^ *byte;
482    }
483    value
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use psx_pad::{button, ActionBinding};
490
491    const ACTIONS: ActionMap<2> = ActionMap::new([
492        ActionBinding::new(button::CROSS, button::CIRCLE),
493        ActionBinding::new(button::START, 0),
494    ]);
495
496    /// A version 1 record exactly as the first release wrote it: a 16 byte
497    /// header whose byte 8 is a 0..=100 brightness percentage.
498    fn version_one_record(percent: u8) -> ([u8; MAX_RECORD_LEN], usize) {
499        let mut out = [0u8; MAX_RECORD_LEN];
500        let len = HEADER_LEN_V1 + 2 * BINDING_LEN + 3 * SCORE_LEN;
501        out[..4].copy_from_slice(&MAGIC);
502        out[4] = 1;
503        out[5] = 2;
504        out[6] = 3;
505        out[7] = FLAG_INVERT_Y;
506        out[8] = percent;
507        out[9] = 80;
508        out[10] = 60;
509        out[11] = 20;
510        out[12] = 14;
511        out[13] = 120;
512        out[14] = 2;
513        put_u16(&mut out, 16, button::CROSS);
514        put_u16(&mut out, 18, button::CIRCLE);
515        put_u16(&mut out, 20, button::START);
516        put_u16(&mut out, 22, 0);
517        put_u32(&mut out, 24, 7);
518        put_u32(&mut out, 28, 42);
519        put_u32(&mut out, 32, 9);
520        out[15] = checksum(&out[..15], &out[HEADER_LEN_V1..len]);
521        (out, len)
522    }
523
524    /// A version 2 record exactly as the previous release wrote it: an 18
525    /// byte header, no game bytes, and a checksum that leaves the two screen
526    /// offset bytes unsealed.
527    fn version_two_record(flags: u8) -> ([u8; MAX_RECORD_LEN], usize) {
528        let mut out = [0u8; MAX_RECORD_LEN];
529        let len = HEADER_LEN_V2 + 2 * BINDING_LEN + 3 * SCORE_LEN;
530        out[..4].copy_from_slice(&MAGIC);
531        out[4] = 2;
532        out[5] = 2;
533        out[6] = 3;
534        out[7] = flags;
535        out[8] = Brightness::new(-3).to_byte();
536        out[9] = 80;
537        out[10] = 60;
538        out[11] = 20;
539        out[12] = 14;
540        out[13] = 120;
541        // Version 2 shipped games stored their own value here.
542        out[14] = 3;
543        let [x, y] = ScreenOffset::<16>::new(5, -7).to_bytes();
544        out[16] = x;
545        out[17] = y;
546        put_u16(&mut out, 18, button::CROSS);
547        put_u16(&mut out, 20, button::CIRCLE);
548        put_u16(&mut out, 22, button::START);
549        put_u16(&mut out, 24, 0);
550        put_u32(&mut out, 26, 7);
551        put_u32(&mut out, 30, 42);
552        put_u32(&mut out, 34, 9);
553        out[15] = checksum(&out[..15], &out[HEADER_LEN_V2..len]);
554        (out, len)
555    }
556
557    #[test]
558    fn profile_round_trips_and_sanitizes() {
559        let mut original = Profile::<2, 3>::new(ACTIONS);
560        original.look_speed_percent = 220;
561        original.set_invert_y(true);
562        original.high_scores = [7, 42, 9];
563        let mut bytes = [0u8; MAX_RECORD_LEN];
564        let len = original.encode(&mut bytes).unwrap();
565        assert_eq!(len, Profile::<2, 3>::encoded_len());
566        assert_eq!(bytes[4], VERSION);
567        let decoded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
568        assert_eq!(decoded.look_speed_percent, 200);
569        assert!(decoded.invert_y());
570        assert_eq!(decoded.actions, ACTIONS);
571        assert_eq!(decoded.high_scores, [7, 42, 9]);
572        assert_eq!(decoded.brightness, Brightness::DEFAULT);
573        assert_eq!(decoded.screen_offset, ScreenOffset::CENTRE);
574    }
575
576    #[test]
577    fn every_brightness_step_and_screen_offset_round_trips() {
578        for level in -5..=5i8 {
579            let mut original = Profile::<2, 1>::new(ACTIONS);
580            original.brightness = Brightness::new(level);
581            original.screen_offset = ScreenOffset::new(level * 3, -level * 3);
582            let mut bytes = [0u8; MAX_RECORD_LEN];
583            let len = original.encode(&mut bytes).unwrap();
584            let decoded = Profile::<2, 1>::decode(&bytes[..len]).unwrap();
585            assert_eq!(decoded.brightness.level(), level);
586            assert_eq!(
587                decoded.screen_offset.pixels(),
588                ((level * 3) as i16, (-level * 3) as i16)
589            );
590            assert_eq!(decoded, original);
591        }
592    }
593
594    #[test]
595    fn the_brightness_byte_is_the_display_crates_save_byte() {
596        let mut profile = Profile::<2, 1>::new(ACTIONS);
597        profile.brightness = Brightness::new(-3);
598        let mut bytes = [0u8; MAX_RECORD_LEN];
599        profile.encode(&mut bytes).unwrap();
600        assert_eq!(bytes[8], Brightness::new(-3).to_byte());
601        assert_eq!(bytes[8], 0xfd);
602    }
603
604    #[test]
605    fn an_out_of_range_brightness_or_offset_byte_is_clamped_on_load() {
606        let mut profile = Profile::<2, 1>::new(ACTIONS);
607        let mut bytes = [0u8; MAX_RECORD_LEN];
608        let len = profile.encode(&mut bytes).unwrap();
609        // 0x7F is +127 and 0x80 is -128 in two's complement; 0x64 stands for
610        // the old percentage scale. Re-seal the checksum after each edit.
611        for (byte, level) in [(0x7f, 5), (0x80, -5), (0x64, 5), (0xfb, -5), (0x05, 5)] {
612            bytes[8] = byte;
613            bytes[16] = 0x7f;
614            bytes[17] = 0x80;
615            bytes[15] = checksum(&bytes[..15], &bytes[16..len]);
616            profile = Profile::<2, 1>::decode(&bytes[..len]).unwrap();
617            assert_eq!(profile.brightness.level(), level);
618            assert_eq!(profile.screen_offset.pixels(), (16, -16));
619        }
620    }
621
622    #[test]
623    fn a_version_one_record_loads_with_the_picture_defaults() {
624        // 75 was the shipped percentage; 100 is its ceiling; 0 its floor.
625        for percent in [75, 100, 0] {
626            let (bytes, len) = version_one_record(percent);
627            let loaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
628            assert_eq!(loaded.brightness, Brightness::DEFAULT);
629            assert_eq!(loaded.screen_offset, ScreenOffset::CENTRE);
630            // Everything else the old record held survives.
631            assert_eq!(loaded.sfx_volume, 80);
632            assert_eq!(loaded.music_volume, 60);
633            assert_eq!(loaded.move_deadzone, 20);
634            assert_eq!(loaded.look_deadzone, 14);
635            assert_eq!(loaded.look_speed_percent, 120);
636            assert_eq!(loaded.difficulty, 2);
637            assert!(loaded.invert_y());
638            assert_eq!(loaded.actions, ACTIONS);
639            assert_eq!(loaded.high_scores, [7, 42, 9]);
640        }
641    }
642
643    #[test]
644    fn a_version_one_record_is_rewritten_as_the_current_version() {
645        let (old, old_len) = version_one_record(75);
646        let mut loaded = Profile::<2, 3>::decode(&old[..old_len]).unwrap();
647        loaded.brightness = loaded.brightness.stepped(2);
648        let mut bytes = [0u8; MAX_RECORD_LEN];
649        let len = loaded.encode(&mut bytes).unwrap();
650        assert_eq!(len, old_len + 2 + GAME_BYTES_LEN);
651        assert_eq!(bytes[4], VERSION);
652        let reloaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
653        assert_eq!(reloaded, loaded);
654        assert_eq!(reloaded.brightness.level(), 2);
655        assert_eq!(reloaded.high_scores, [7, 42, 9]);
656    }
657
658    #[test]
659    fn game_bits_survive_every_record_version_and_sanitize() {
660        let (mut old, old_len) = version_one_record(75);
661        old[7] = 0xa7;
662        old[15] = checksum(&old[..15], &old[HEADER_LEN_V1..old_len]);
663        let mut profile = Profile::<2, 3>::decode(&old[..old_len]).unwrap();
664        assert_eq!(profile.flags, 0xa7);
665        assert_eq!(profile.game_flags(), 0xa6);
666        assert!(profile.invert_y());
667        profile.sanitize();
668        assert_eq!(profile.flags, 0xa7);
669
670        let mut bytes = [0u8; MAX_RECORD_LEN];
671        let len = profile.encode(&mut bytes).unwrap();
672        assert_eq!(VERSION, 3);
673        assert_eq!(len, old_len + 2 + GAME_BYTES_LEN);
674        assert_eq!(bytes[7], 0xa7);
675        assert_eq!(Profile::<2, 3>::decode(&bytes[..len]).unwrap(), profile);
676
677        let (mut v2, v2_len) = version_two_record(0xa7);
678        let loaded = Profile::<2, 3>::decode(&v2[..v2_len]).unwrap();
679        assert_eq!(loaded.game_flags(), 0xa6);
680        v2[7] ^= 0x40;
681        assert_eq!(
682            Profile::<2, 3>::decode(&v2[..v2_len]),
683            Err(CodecError::BadChecksum)
684        );
685    }
686
687    #[test]
688    fn game_flag_edits_preserve_other_bits_and_cannot_change_invert_y() {
689        let mut profile = Profile::<2, 1>::new(ACTIONS);
690        profile.flags = 0xa7;
691        profile.set_game_flag(0x02, false);
692        assert_eq!(profile.flags, 0xa5);
693        profile.set_game_flag(0x03, true);
694        assert_eq!(profile.flags, 0xa7);
695        profile.set_game_flag(FLAG_INVERT_Y, false);
696        assert_eq!(profile.flags, 0xa7);
697        profile.set_invert_y(false);
698        assert_eq!(profile.flags, 0xa6);
699        profile.set_game_flag(0x02, false);
700        assert_eq!(profile.flags, 0xa4);
701        profile.set_invert_y(true);
702        assert_eq!(profile.flags, 0xa5);
703    }
704
705    #[test]
706    fn game_bits_keep_the_current_length_and_checksum() {
707        let mut profile = Profile::<5, 0>::new(ActionMap::new([ActionBinding::UNBOUND; 5]));
708        profile.set_game_flag(0x80, true);
709        let mut bytes = [0u8; MAX_RECORD_LEN];
710        let len = profile.encode(&mut bytes).unwrap();
711        assert_eq!(len, 18 + GAME_BYTES_LEN + 5 * BINDING_LEN);
712        assert_eq!(len, 46);
713        assert_eq!(bytes[4], 3);
714        assert_eq!(bytes[7], 0x80);
715        bytes[7] ^= 0x40;
716        assert_eq!(
717            Profile::<5, 0>::decode(&bytes[..len]),
718            Err(CodecError::BadChecksum)
719        );
720    }
721
722    #[test]
723    fn a_torn_version_one_record_and_an_unknown_version_are_rejected() {
724        let (mut bytes, len) = version_one_record(75);
725        bytes[len - 1] ^= 0x01;
726        assert_eq!(
727            Profile::<2, 3>::decode(&bytes[..len]),
728            Err(CodecError::BadChecksum)
729        );
730        let (mut bytes, len) = version_one_record(75);
731        bytes[4] = 0;
732        assert_eq!(
733            Profile::<2, 3>::decode(&bytes[..len]),
734            Err(CodecError::UnsupportedVersion)
735        );
736        bytes[4] = VERSION + 1;
737        assert_eq!(
738            Profile::<2, 3>::decode(&bytes[..len]),
739            Err(CodecError::UnsupportedVersion)
740        );
741        // A version 1 record cut short of its payload is too small, not a
742        // version 2 reading of the next bytes.
743        let (bytes, len) = version_one_record(75);
744        assert_eq!(
745            Profile::<2, 3>::decode(&bytes[..len - 1]),
746            Err(CodecError::BufferTooSmall)
747        );
748        // Another shape is refused for both versions.
749        let (bytes, len) = version_one_record(75);
750        assert_eq!(
751            Profile::<2, 2>::decode(&bytes[..len]),
752            Err(CodecError::WrongShape)
753        );
754    }
755
756    #[cfg(feature = "card")]
757    #[test]
758    fn a_version_one_card_file_loads_and_is_replaced_by_the_current_version() {
759        let (old, old_len) = version_one_record(75);
760        let mut card = psx_mc::Card::new(psx_mc::RamCard::new());
761        card.format().unwrap();
762        card.write("BESLES-00000SETTEST1", "SETTINGS TEST", &old[..old_len])
763            .unwrap();
764        let mut profile = load::<_, 2, 3>(&mut card, "BESLES-00000SETTEST1").unwrap();
765        assert_eq!(profile.brightness, Brightness::DEFAULT);
766        profile.brightness = Brightness::new(-4);
767        save(&mut card, "BESLES-00000SETTEST1", "SETTINGS TEST", &profile).unwrap();
768        let reloaded = load::<_, 2, 3>(&mut card, "BESLES-00000SETTEST1").unwrap();
769        assert_eq!(reloaded, profile);
770    }
771
772    #[test]
773    fn game_bytes_default_to_zero_and_round_trip_verbatim() {
774        let mut profile = Profile::<2, 3>::new(ACTIONS);
775        assert_eq!(profile.game_bytes, [0; GAME_BYTES_LEN]);
776        profile.game_bytes = [0, 255, 1, 128, 7, 0, 9, 200];
777        profile.difficulty = 2;
778        profile.high_scores = [7, 42, 9];
779        let mut bytes = [0u8; MAX_RECORD_LEN];
780        let len = profile.encode(&mut bytes).unwrap();
781        assert_eq!(&bytes[18..26], &[0, 255, 1, 128, 7, 0, 9, 200]);
782        let loaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
783        // sanitize() must not touch them, and nothing else moves.
784        assert_eq!(loaded, profile);
785        assert_eq!(loaded.difficulty, 2);
786    }
787
788    #[test]
789    fn a_version_two_record_loads_with_zero_game_bytes_and_every_field_kept() {
790        let (bytes, len) = version_two_record(FLAG_INVERT_Y | 0x40);
791        let loaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
792        assert_eq!(loaded.game_bytes, [0; GAME_BYTES_LEN]);
793        assert_eq!(loaded.brightness.level(), -3);
794        assert_eq!(loaded.screen_offset.pixels(), (5, -7));
795        assert_eq!(loaded.sfx_volume, 80);
796        assert_eq!(loaded.music_volume, 60);
797        assert_eq!(loaded.move_deadzone, 20);
798        assert_eq!(loaded.look_deadzone, 14);
799        assert_eq!(loaded.look_speed_percent, 120);
800        assert_eq!(loaded.difficulty, 3);
801        assert_eq!(loaded.flags, FLAG_INVERT_Y | 0x40);
802        assert_eq!(loaded.actions, ACTIONS);
803        assert_eq!(loaded.high_scores, [7, 42, 9]);
804    }
805
806    #[test]
807    fn a_version_one_record_also_loads_with_zero_game_bytes() {
808        let (bytes, len) = version_one_record(75);
809        let loaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
810        assert_eq!(loaded.game_bytes, [0; GAME_BYTES_LEN]);
811    }
812
813    #[test]
814    fn a_version_two_record_is_rewritten_as_version_three_keeping_its_fields() {
815        let (old, old_len) = version_two_record(FLAG_INVERT_Y);
816        let mut loaded = Profile::<2, 3>::decode(&old[..old_len]).unwrap();
817        loaded.game_bytes[3] = 41;
818        let mut bytes = [0u8; MAX_RECORD_LEN];
819        let len = loaded.encode(&mut bytes).unwrap();
820        assert_eq!(len, old_len + GAME_BYTES_LEN);
821        assert_eq!(bytes[4], 3);
822        let reloaded = Profile::<2, 3>::decode(&bytes[..len]).unwrap();
823        assert_eq!(reloaded, loaded);
824        assert_eq!(reloaded.game_bytes[3], 41);
825        assert_eq!(reloaded.screen_offset.pixels(), (5, -7));
826        assert_eq!(reloaded.difficulty, 3);
827        assert_eq!(reloaded.high_scores, [7, 42, 9]);
828    }
829
830    #[test]
831    fn the_version_three_checksum_seals_the_game_bytes_and_screen_offset() {
832        let mut profile = Profile::<2, 3>::new(ACTIONS);
833        profile.game_bytes[0] = 5;
834        let mut bytes = [0u8; MAX_RECORD_LEN];
835        let len = profile.encode(&mut bytes).unwrap();
836        // Every byte but the checksum itself is covered: flipping any one
837        // is caught.
838        for at in (0..len).filter(|at| *at != 15 && *at != 4) {
839            let mut torn = bytes;
840            torn[at] ^= 0x01;
841            let result = Profile::<2, 3>::decode(&torn[..len]);
842            let expected = match at {
843                0..=3 => Err(CodecError::BadMagic),
844                5 | 6 => Err(CodecError::WrongShape),
845                _ => Err(CodecError::BadChecksum),
846            };
847            assert_eq!(result, expected, "byte {at}");
848        }
849    }
850
851    #[test]
852    fn a_version_four_record_and_a_cut_short_version_three_record_are_rejected() {
853        let profile = Profile::<2, 3>::new(ACTIONS);
854        let mut bytes = [0u8; MAX_RECORD_LEN];
855        let len = profile.encode(&mut bytes).unwrap();
856        // A reader never guesses the layout of a version it does not know.
857        let mut future = bytes;
858        future[4] = VERSION + 1;
859        assert_eq!(
860            Profile::<2, 3>::decode(&future[..len]),
861            Err(CodecError::UnsupportedVersion)
862        );
863        assert_eq!(
864            Profile::<2, 3>::decode(&bytes[..len - 1]),
865            Err(CodecError::BufferTooSmall)
866        );
867        // Another shape is refused.
868        assert_eq!(
869            Profile::<2, 2>::decode(&bytes[..len]),
870            Err(CodecError::WrongShape)
871        );
872    }
873
874    #[test]
875    fn the_record_size_limit_is_checked_for_the_version_three_header() {
876        // 18 + 8 + 4 * (actions + scores) must stay within MAX_RECORD_LEN.
877        let fits = Profile::<20, 5>::new(ActionMap::new([ActionBinding::UNBOUND; 20]));
878        assert_eq!(Profile::<20, 5>::encoded_len(), 126);
879        let mut bytes = [0u8; MAX_RECORD_LEN];
880        let len = fits.encode(&mut bytes).unwrap();
881        assert_eq!(Profile::<20, 5>::decode(&bytes[..len]).unwrap(), fits);
882
883        let too_big = Profile::<20, 6>::new(ActionMap::new([ActionBinding::UNBOUND; 20]));
884        assert_eq!(Profile::<20, 6>::encoded_len(), 130);
885        assert_eq!(too_big.encode(&mut bytes), Err(CodecError::BufferTooSmall));
886        // A caller buffer shorter than the record is refused too.
887        let small = Profile::<2, 1>::new(ACTIONS);
888        let mut short = [0u8; 20];
889        assert_eq!(small.encode(&mut short), Err(CodecError::BufferTooSmall));
890    }
891
892    #[test]
893    fn every_shipping_shape_still_fits_in_one_card_block() {
894        // NitroXide 9/0, VoXide 5/0 and the arcade microgames 0/3.
895        assert_eq!(Profile::<9, 0>::encoded_len(), 62);
896        assert_eq!(Profile::<5, 0>::encoded_len(), 46);
897        assert_eq!(Profile::<0, 3>::encoded_len(), 38);
898        assert!(Profile::<9, 0>::encoded_len() <= MAX_RECORD_LEN);
899    }
900
901    #[cfg(feature = "card")]
902    #[test]
903    fn a_version_two_card_file_loads_and_is_replaced_by_version_three() {
904        let (old, old_len) = version_two_record(0);
905        let mut card = psx_mc::Card::new(psx_mc::RamCard::new());
906        card.format().unwrap();
907        card.write("BESLES-00000SETTEST1", "SETTINGS TEST", &old[..old_len])
908            .unwrap();
909        let mut profile = load::<_, 2, 3>(&mut card, "BESLES-00000SETTEST1").unwrap();
910        assert_eq!(profile.game_bytes, [0; GAME_BYTES_LEN]);
911        profile.game_bytes[1] = 9;
912        save(&mut card, "BESLES-00000SETTEST1", "SETTINGS TEST", &profile).unwrap();
913        let reloaded = load::<_, 2, 3>(&mut card, "BESLES-00000SETTEST1").unwrap();
914        assert_eq!(reloaded, profile);
915        assert_eq!(reloaded.game_bytes[1], 9);
916    }
917
918    #[test]
919    fn checksum_rejects_a_torn_record() {
920        let profile = Profile::<2, 1>::new(ACTIONS);
921        let mut bytes = [0u8; MAX_RECORD_LEN];
922        let len = profile.encode(&mut bytes).unwrap();
923        bytes[len - 1] ^= 0x80;
924        assert_eq!(
925            Profile::<2, 1>::decode(&bytes[..len]),
926            Err(CodecError::BadChecksum)
927        );
928    }
929
930    #[cfg(feature = "card")]
931    #[test]
932    fn memory_card_round_trip_uses_normal_filesystem() {
933        let mut card = psx_mc::Card::new(psx_mc::RamCard::new());
934        card.format().unwrap();
935        let mut profile = Profile::<2, 2>::new(ACTIONS);
936        profile.high_scores = [1234, 5678];
937        save(&mut card, "BESLES-00000SETTEST1", "SETTINGS TEST", &profile).unwrap();
938        let loaded = load::<_, 2, 2>(&mut card, "BESLES-00000SETTEST1").unwrap();
939        assert_eq!(loaded, profile);
940    }
941
942    /// A card holding another game's save whose `MC` header frame was lost.
943    #[cfg(feature = "card")]
944    fn card_without_header() -> psx_mc::Card<psx_mc::RamCard> {
945        let mut card = psx_mc::Card::new(psx_mc::RamCard::new());
946        card.format().unwrap();
947        card.write("BESLES-00000OTHER001", "OTHER", b"another save")
948            .unwrap();
949        let mut image = *card.into_inner().image();
950        image[..psx_mc::FRAME_SIZE].fill(0);
951        psx_mc::Card::new(psx_mc::RamCard::from_image(&image).unwrap())
952    }
953
954    #[cfg(feature = "card")]
955    #[test]
956    fn saving_to_an_unformatted_card_is_refused_and_touches_nothing() {
957        let profile = Profile::<2, 1>::new(ACTIONS);
958        let mut card = card_without_header();
959        let before = *card.device().image();
960        assert_eq!(
961            save(&mut card, "BESLES-00000SETTEST1", "SETTINGS TEST", &profile),
962            Err(CardError::Card(psx_mc::Error::NotFormatted))
963        );
964        assert_eq!(card.device().image(), &before);
965    }
966
967    #[cfg(feature = "card")]
968    #[test]
969    fn formatting_is_a_separate_explicit_call() {
970        let profile = Profile::<2, 1>::new(ACTIONS);
971        // A blank card is formatted and written.
972        let mut blank = psx_mc::Card::new(psx_mc::RamCard::new());
973        format_and_save(
974            &mut blank,
975            "BESLES-00000SETTEST1",
976            "SETTINGS TEST",
977            &profile,
978        )
979        .unwrap();
980        assert_eq!(
981            load::<_, 2, 1>(&mut blank, "BESLES-00000SETTEST1").unwrap(),
982            profile
983        );
984        // A formatted card keeps its other saves.
985        let mut card = psx_mc::Card::new(psx_mc::RamCard::new());
986        card.format().unwrap();
987        card.write("BESLES-00000OTHER001", "OTHER", b"another save")
988            .unwrap();
989        format_and_save(&mut card, "BESLES-00000SETTEST1", "SETTINGS TEST", &profile).unwrap();
990        let mut buf = [0u8; 32];
991        let n = card.read("BESLES-00000OTHER001", &mut buf).unwrap();
992        assert_eq!(&buf[..n], b"another save");
993    }
994}