1#![no_std]
11#![warn(missing_docs)]
12
13use psx_display::{Brightness, ScreenOffset};
14use psx_pad::ActionMap;
15
16pub const MAGIC: [u8; 4] = *b"PSST";
18pub const VERSION: u8 = 3;
35const OLDEST_VERSION: u8 = 1;
37const HEADER_LEN_V1: usize = 16;
39const HEADER_LEN_V2: usize = 18;
42pub const GAME_BYTES_LEN: usize = 8;
49const HEADER_LEN: usize = HEADER_LEN_V2 + GAME_BYTES_LEN;
52const CHECKSUM_AT: usize = 15;
54const BINDING_LEN: usize = 4;
56const SCORE_LEN: usize = 4;
58pub const MAX_RECORD_LEN: usize = 128;
60
61pub const FLAG_INVERT_Y: u8 = 1 << 0;
63pub const GAME_FLAGS_MASK: u8 = !FLAG_INVERT_Y;
69
70#[derive(Copy, Clone, Debug, PartialEq, Eq)]
75pub struct Profile<const ACTIONS: usize, const SCORES: usize> {
76 pub brightness: Brightness,
78 pub screen_offset: ScreenOffset,
80 pub sfx_volume: u8,
82 pub music_volume: u8,
84 pub move_deadzone: u8,
86 pub look_deadzone: u8,
88 pub look_speed_percent: u8,
90 pub difficulty: u8,
92 pub flags: u8,
95 pub game_bytes: [u8; GAME_BYTES_LEN],
102 pub actions: ActionMap<ACTIONS>,
104 pub high_scores: [u32; SCORES],
106}
107
108impl<const ACTIONS: usize, const SCORES: usize> Profile<ACTIONS, SCORES> {
109 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 pub const fn encoded_len() -> usize {
130 HEADER_LEN + ACTIONS * BINDING_LEN + SCORES * SCORE_LEN
131 }
132
133 pub fn sanitize(&mut self) {
136 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 pub const fn invert_y(&self) -> bool {
147 self.flags & FLAG_INVERT_Y != 0
148 }
149
150 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 pub const fn game_flags(&self) -> u8 {
161 self.flags & GAME_FLAGS_MASK
162 }
163
164 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 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 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 out[CHECKSUM_AT] = checksum(&out[..CHECKSUM_AT], &out[CHECKSUM_AT + 1..len]);
223 Ok(len)
224 }
225
226 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 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#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310pub enum CodecError {
311 BufferTooSmall,
313 BadMagic,
315 UnsupportedVersion,
317 WrongShape,
319 BadChecksum,
321}
322
323#[cfg(feature = "card")]
325#[derive(Copy, Clone, Debug, PartialEq, Eq)]
326pub enum CardError {
327 Card(psx_mc::Error),
329 Codec(CodecError),
331}
332
333#[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#[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#[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#[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#[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#[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#[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#[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#[cfg(feature = "card")]
447fn steal_port() -> psx_mc::ControllerPort {
448 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 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 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 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 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 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 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 let (bytes, len) = version_one_record(75);
744 assert_eq!(
745 Profile::<2, 3>::decode(&bytes[..len - 1]),
746 Err(CodecError::BufferTooSmall)
747 );
748 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 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 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 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 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 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 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 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 #[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 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 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}