1use alloc::vec::Vec;
57
58use crate::input_device::InputDevice;
59use crate::nes::Nes;
60use crate::save_state::{BinReader, BinWriter};
61use rustynes_mappers::Barcode;
62
63#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
73#[non_exhaustive]
74pub enum DeviceInput {
75 #[default]
78 None,
79 Zapper {
82 x: u16,
84 y: u16,
86 trigger: bool,
88 },
89 Vaus {
91 position: u8,
93 fire: bool,
95 },
96 PowerPad(u16),
98 FamilyTrainer(u16),
101 SnesMouse {
103 dx: i16,
105 dy: i16,
107 left: bool,
109 right: bool,
111 sensitivity: u8,
113 },
114 FamilyKeyboard([u8; 9]),
117 SuborKeyboard([u8; 9]),
119 KonamiHyperShot(u8),
121 BandaiHyperShot(u8),
123}
124
125const DEVICE_PAYLOAD_MAX: usize = 9;
127
128impl DeviceInput {
129 #[must_use]
131 pub const fn capture(device: &Option<InputDevice>) -> Self {
132 match device {
133 None => Self::None,
134 Some(InputDevice::Zapper(z)) => Self::Zapper {
135 x: z.x,
136 y: z.y,
137 trigger: z.trigger,
138 },
139 Some(InputDevice::Vaus(v)) => Self::Vaus {
140 position: v.position,
141 fire: v.fire,
142 },
143 Some(InputDevice::PowerPad(p)) => Self::PowerPad(p.buttons),
144 Some(InputDevice::FamilyTrainer(p)) => Self::FamilyTrainer(p.buttons),
145 Some(InputDevice::SnesMouse(m)) => Self::SnesMouse {
146 dx: m.dx,
147 dy: m.dy,
148 left: m.left,
149 right: m.right,
150 sensitivity: m.sensitivity,
151 },
152 Some(InputDevice::FamilyKeyboard(k)) => Self::FamilyKeyboard(k.keys),
153 Some(InputDevice::SuborKeyboard(k)) => Self::SuborKeyboard(k.keys),
154 Some(InputDevice::KonamiHyperShot(h)) => Self::KonamiHyperShot(h.buttons),
155 Some(InputDevice::BandaiHyperShot(b)) => Self::BandaiHyperShot(b.sensors),
156 }
157 }
158
159 pub fn apply(self, nes: &mut Nes, port: usize) {
170 match self {
171 Self::None => {
172 if nes.expansion_device(port).is_some() {
173 nes.set_expansion_device(port, None);
174 }
175 }
176 Self::Zapper { x, y, trigger } => nes.set_zapper(port, x, y, trigger),
177 Self::Vaus { position, fire } => nes.set_paddle(port, position, fire),
178 Self::PowerPad(b) => nes.set_power_pad(port, b),
179 Self::FamilyTrainer(b) => nes.set_family_trainer(port, b),
180 Self::SnesMouse {
181 dx,
182 dy,
183 left,
184 right,
185 sensitivity,
186 } => nes.set_snes_mouse(port, dx, dy, left, right, sensitivity),
187 Self::FamilyKeyboard(k) => nes.set_family_keyboard(port, k),
188 Self::SuborKeyboard(k) => nes.set_subor_keyboard(port, k),
189 Self::KonamiHyperShot(b) => nes.set_konami_hyper_shot(port, b),
190 Self::BandaiHyperShot(b) => nes.set_bandai_hyper_shot(port, b),
191 }
192 }
193
194 const fn tag(self) -> u8 {
196 match self {
197 Self::None => 0,
198 Self::Zapper { .. } => 1,
199 Self::Vaus { .. } => 2,
200 Self::PowerPad(_) => 3,
201 Self::FamilyTrainer(_) => 4,
202 Self::SnesMouse { .. } => 5,
203 Self::FamilyKeyboard(_) => 6,
204 Self::SuborKeyboard(_) => 7,
205 Self::KonamiHyperShot(_) => 8,
206 Self::BandaiHyperShot(_) => 9,
207 }
208 }
209
210 fn payload(self, out: &mut [u8; DEVICE_PAYLOAD_MAX]) -> usize {
212 match self {
213 Self::None => 0,
214 Self::Zapper { x, y, trigger } => {
215 out[..2].copy_from_slice(&x.to_le_bytes());
216 out[2..4].copy_from_slice(&y.to_le_bytes());
217 out[4] = u8::from(trigger);
218 5
219 }
220 Self::Vaus { position, fire } => {
221 out[0] = position;
222 out[1] = u8::from(fire);
223 2
224 }
225 Self::PowerPad(b) | Self::FamilyTrainer(b) => {
229 out[..2].copy_from_slice(&(b & 0x0FFF).to_le_bytes());
230 2
231 }
232 Self::SnesMouse {
233 dx,
234 dy,
235 left,
236 right,
237 sensitivity,
238 } => {
239 out[..2].copy_from_slice(&dx.to_le_bytes());
240 out[2..4].copy_from_slice(&dy.to_le_bytes());
241 out[4] = u8::from(left) | (u8::from(right) << 1);
242 out[5] = sensitivity & 0b11;
243 6
244 }
245 Self::FamilyKeyboard(k) | Self::SuborKeyboard(k) => {
246 out.copy_from_slice(&k);
247 9
248 }
249 Self::KonamiHyperShot(b) => {
250 out[0] = b & 0x0F;
251 1
252 }
253 Self::BandaiHyperShot(b) => {
254 out[0] = b;
255 1
256 }
257 }
258 }
259
260 fn write(self, w: &mut BinWriter) {
261 let mut buf = [0u8; DEVICE_PAYLOAD_MAX];
262 let n = self.payload(&mut buf);
263 w.u8(self.tag());
264 w.bytes(&buf[..n]);
265 }
266
267 fn read(r: &mut BinReader<'_>) -> Result<Self, &'static str> {
271 let tag = r.u8().map_err(|_| EOF)?;
272 let dev = match tag {
273 0 => Self::None,
274 1 => Self::Zapper {
275 x: r.u16().map_err(|_| EOF)?,
276 y: r.u16().map_err(|_| EOF)?,
277 trigger: read_flag(r)?,
278 },
279 2 => Self::Vaus {
280 position: r.u8().map_err(|_| EOF)?,
281 fire: read_flag(r)?,
282 },
283 3 | 4 => {
284 let b = r.u16().map_err(|_| EOF)?;
285 if b > 0x0FFF {
286 return Err("a mat button mask has bits above button 12");
287 }
288 if tag == 3 {
289 Self::PowerPad(b)
290 } else {
291 Self::FamilyTrainer(b)
292 }
293 }
294 5 => {
295 let dx = r.i16().map_err(|_| EOF)?;
296 let dy = r.i16().map_err(|_| EOF)?;
297 let buttons = r.u8().map_err(|_| EOF)?;
298 if buttons & !0b11 != 0 {
299 return Err("a mouse button byte has bits beyond left and right");
300 }
301 let sensitivity = r.u8().map_err(|_| EOF)?;
302 if sensitivity > 3 {
303 return Err("a mouse sensitivity is above 3");
304 }
305 Self::SnesMouse {
306 dx,
307 dy,
308 left: buttons & 1 != 0,
309 right: buttons & 2 != 0,
310 sensitivity,
311 }
312 }
313 6 | 7 => {
314 let mut k = [0u8; 9];
315 r.read_into(&mut k).map_err(|_| EOF)?;
316 if tag == 6 {
317 Self::FamilyKeyboard(k)
318 } else {
319 Self::SuborKeyboard(k)
320 }
321 }
322 8 => {
323 let b = r.u8().map_err(|_| EOF)?;
324 if b > 0x0F {
325 return Err("a Konami Hyper Shot mask has bits above button 4");
326 }
327 Self::KonamiHyperShot(b)
328 }
329 9 => Self::BandaiHyperShot(r.u8().map_err(|_| EOF)?),
330 _ => return Err("an expansion device tag this build does not know"),
331 };
332 Ok(dev)
333 }
334}
335
336#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
346#[non_exhaustive]
347pub struct ExtraInput {
348 pub devices: [DeviceInput; 2],
350 pub microphone: bool,
352 pub vs_coin: u8,
354 pub vs_service: bool,
356 pub disk_side: Option<u8>,
360 pub barcode: Option<Barcode>,
363}
364
365impl ExtraInput {
366 #[must_use]
373 pub fn capture(nes: &Nes) -> Self {
374 Self {
375 devices: [
376 DeviceInput::capture(nes.expansion_device(0)),
377 DeviceInput::capture(nes.expansion_device(1)),
378 ],
379 microphone: nes.microphone(),
380 vs_coin: nes.vs_coin(),
381 vs_service: nes.vs_service(),
382 disk_side: nes
383 .inserted_disk_side()
384 .and_then(|s| u8::try_from(s).ok())
385 .filter(|&s| s != DISK_EJECTED),
386 barcode: nes.barcode_this_frame(),
387 }
388 }
389
390 pub fn apply(&self, nes: &mut Nes) {
403 self.devices[0].apply(nes, 0);
404 self.devices[1].apply(nes, 1);
405 nes.set_microphone(self.microphone);
406 if nes.vs_coin() != self.vs_coin {
407 nes.clear_coin();
408 for acceptor in 0..2u8 {
409 if self.vs_coin & (1 << acceptor) != 0 {
410 nes.insert_coin(acceptor);
411 }
412 }
413 }
414 nes.set_vs_service(self.vs_service);
415 let want = self.disk_side.map(usize::from);
416 if nes.inserted_disk_side() != want {
417 nes.set_disk_side(want);
418 }
419 if let Some(code) = &self.barcode {
420 let _ = nes.scan_barcode_code(code);
421 }
422 }
423
424 #[must_use]
427 pub const fn held(mut self) -> Self {
428 self.barcode = None;
429 self
430 }
431}
432
433const DISK_EJECTED: u8 = 0xFF;
435
436const EOF: &str = "the input events end mid-event";
438
439fn read_flag(r: &mut BinReader<'_>) -> Result<bool, &'static str> {
440 match r.u8().map_err(|_| EOF)? {
441 0 => Ok(false),
442 1 => Ok(true),
443 _ => Err("a boolean input is neither 0 nor 1"),
444 }
445}
446
447const EV_EXTRA_OFF: u8 = 0x00;
453const EV_EXTRA_ON: u8 = 0x01;
456const EV_DEVICE: u8 = 0x02;
458const EV_MICROPHONE: u8 = 0x03;
460const EV_VS_COIN: u8 = 0x04;
462const EV_VS_SERVICE: u8 = 0x05;
464const EV_DISK: u8 = 0x06;
466const EV_BARCODE: u8 = 0x07;
468
469const MIN_EVENT_LEN: usize = 5;
471
472pub fn decoded_events_bytes(block: &[u8]) -> u64 {
478 let Some(c) = block.get(..4) else {
479 return 0;
480 };
481 let declared = u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as usize;
482 let held = declared.min((block.len() - 4) / MIN_EVENT_LEN);
483 (held as u64).saturating_mul(core::mem::size_of::<(usize, Event)>() as u64)
484}
485
486pub fn encode_events<'a>(frames: impl Iterator<Item = Option<&'a ExtraInput>>) -> Vec<u8> {
494 let mut body = BinWriter::new();
495 let mut count = 0u32;
496 let mut prev: Option<ExtraInput> = None;
497 for (i, cur) in frames.enumerate() {
498 let frame = u32::try_from(i).expect("frame count exceeds u32");
499 let mut ev = |kind: u8, body: &mut BinWriter| {
500 body.u32(frame);
501 body.u8(kind);
502 count += 1;
503 };
504 match (prev, cur) {
505 (None, None) => {}
506 (Some(_), None) => ev(EV_EXTRA_OFF, &mut body),
507 (p, Some(c)) => {
508 let base = p.unwrap_or_else(|| {
509 ev(EV_EXTRA_ON, &mut body);
510 ExtraInput::default()
511 });
512 for port in 0..2u8 {
513 let p = usize::from(port);
514 if c.devices[p] != base.devices[p] {
515 ev(EV_DEVICE, &mut body);
516 body.u8(port);
517 c.devices[p].write(&mut body);
518 }
519 }
520 if c.microphone != base.microphone {
521 ev(EV_MICROPHONE, &mut body);
522 body.u8(u8::from(c.microphone));
523 }
524 if c.vs_coin & 0b11 != base.vs_coin & 0b11 {
526 ev(EV_VS_COIN, &mut body);
527 body.u8(c.vs_coin & 0b11);
528 }
529 if c.vs_service != base.vs_service {
530 ev(EV_VS_SERVICE, &mut body);
531 body.u8(u8::from(c.vs_service));
532 }
533 if c.disk_side != base.disk_side {
534 ev(EV_DISK, &mut body);
535 body.u8(c.disk_side.unwrap_or(DISK_EJECTED));
536 }
537 if let Some(code) = &c.barcode {
538 ev(EV_BARCODE, &mut body);
539 let digits = code.digits();
540 body.u8(digit_count(digits));
541 body.bytes(digits);
542 }
543 }
544 }
545 prev = cur.map(|c| c.held());
546 }
547 let mut out = BinWriter::with_capacity(4 + body.len());
548 out.u32(count);
549 out.bytes(&body.into_vec());
550 out.into_vec()
551}
552
553pub fn decode_events(
566 block: &[u8],
567 frame_count: usize,
568) -> Result<Vec<Option<ExtraInput>>, &'static str> {
569 let mut r = BinReader::new(block);
570 let declared = r.u32().map_err(|_| EOF)? as usize;
571 let mut events = Vec::with_capacity(declared.min(r.remaining() / MIN_EVENT_LEN));
575 let mut last_key: Option<(usize, u8, u8)> = None;
576 for _ in 0..declared {
577 let (frame, kind, ev) = read_event(&mut r, frame_count)?;
578 let port = if let Event::Device(p, _) = ev { p } else { 0 };
581 let key = (frame, kind, port);
582 if last_key.is_some_and(|k| k >= key) {
583 return Err("input events are out of order or repeated");
584 }
585 last_key = Some(key);
586 events.push((frame, ev));
587 }
588 if r.remaining() != 0 {
589 return Err("unexpected bytes after the input events");
590 }
591
592 let mut out = Vec::with_capacity(frame_count);
593 let mut cur: Option<ExtraInput> = None;
594 let mut pending = events.into_iter().peekable();
595 for frame in 0..frame_count {
596 let mut presence_changed = false;
597 while let Some((_, ev)) = pending.next_if(|&(f, _)| f == frame) {
598 if let Event::Presence(on) = ev {
599 if presence_changed || cur.is_some() == on {
600 return Err("an input presence event does not change presence");
601 }
602 presence_changed = true;
603 cur = on.then(ExtraInput::default);
604 continue;
605 }
606 let Some(state) = cur.as_mut() else {
607 return Err("an input event arrives while no input is recorded");
608 };
609 if !apply_event(state, ev) {
610 return Err("an input event repeats the value already held");
611 }
612 }
613 out.push(cur);
614 cur = cur.map(ExtraInput::held);
615 }
616 if pending.next().is_some() {
620 return Err("an input event was not reached");
621 }
622 Ok(out)
623}
624
625fn read_event(
627 r: &mut BinReader<'_>,
628 frame_count: usize,
629) -> Result<(usize, u8, Event), &'static str> {
630 let frame = r.u32().map_err(|_| EOF)? as usize;
631 if frame >= frame_count {
632 return Err("an input event lies past the last frame");
633 }
634 let kind = r.u8().map_err(|_| EOF)?;
635 let ev = match kind {
636 EV_EXTRA_OFF | EV_EXTRA_ON => Event::Presence(kind == EV_EXTRA_ON),
637 EV_DEVICE => {
638 let port = r.u8().map_err(|_| EOF)?;
639 if port > 1 {
640 return Err("an expansion device event names a port other than 0 or 1");
641 }
642 Event::Device(port, DeviceInput::read(r)?)
643 }
644 EV_MICROPHONE => Event::Microphone(read_flag(r)?),
645 EV_VS_COIN => {
646 let bits = r.u8().map_err(|_| EOF)?;
647 if bits > 0b11 {
648 return Err("a Vs. coin event sets acceptors other than #1 and #2");
649 }
650 Event::Coin(bits)
651 }
652 EV_VS_SERVICE => Event::Service(read_flag(r)?),
653 EV_DISK => {
654 let side = r.u8().map_err(|_| EOF)?;
655 Event::Disk((side != DISK_EJECTED).then_some(side))
656 }
657 EV_BARCODE => Event::Barcode(read_barcode(r)?),
658 _ => return Err("an input event kind this build does not know"),
659 };
660 Ok((frame, kind, ev))
661}
662
663fn read_barcode(r: &mut BinReader<'_>) -> Result<Barcode, &'static str> {
666 let len = usize::from(r.u8().map_err(|_| EOF)?);
667 if len != 8 && len != 13 {
668 return Err("a barcode event is neither 8 nor 13 digits");
669 }
670 let digits = r.take(len).map_err(|_| EOF)?;
671 let mut text = [0u8; 13];
672 for (t, &d) in text.iter_mut().zip(digits) {
673 if d > 9 {
674 return Err("a barcode event holds a digit above 9");
675 }
676 *t = b'0' + d;
677 }
678 let text = core::str::from_utf8(&text[..len]).map_err(|_| EOF)?;
679 Barcode::parse(text).map_err(|_| "a barcode event fails its check digit")
680}
681
682fn apply_event(state: &mut ExtraInput, ev: Event) -> bool {
685 match ev {
686 Event::Device(p, d) => replace(&mut state.devices[usize::from(p)], d),
687 Event::Microphone(v) => replace(&mut state.microphone, v),
688 Event::Coin(v) => replace(&mut state.vs_coin, v),
689 Event::Service(v) => replace(&mut state.vs_service, v),
690 Event::Disk(v) => replace(&mut state.disk_side, v),
691 Event::Barcode(code) => {
692 state.barcode = Some(code);
693 true
694 }
695 Event::Presence(_) => false,
697 }
698}
699
700fn digit_count(digits: &[u8]) -> u8 {
702 u8::try_from(digits.len()).unwrap_or(u8::MAX)
703}
704
705fn replace<T: PartialEq>(slot: &mut T, value: T) -> bool {
707 if *slot == value {
708 false
709 } else {
710 *slot = value;
711 true
712 }
713}
714
715#[derive(Clone, Copy)]
716enum Event {
717 Presence(bool),
718 Device(u8, DeviceInput),
719 Microphone(bool),
720 Coin(u8),
721 Service(bool),
722 Disk(Option<u8>),
723 Barcode(Barcode),
724}
725
726pub const ATTESTATION_EXTRA_LEN: usize = 1 + 2 * (1 + DEVICE_PAYLOAD_MAX) + 4 + 1 + 13;
728
729pub fn attestation_bytes(extra: Option<&ExtraInput>) -> [u8; ATTESTATION_EXTRA_LEN] {
733 let mut out = [0u8; ATTESTATION_EXTRA_LEN];
734 let Some(e) = extra else {
735 return out;
736 };
737 out[0] = 1;
738 let mut at = 1;
739 for dev in e.devices {
740 out[at] = dev.tag();
741 let mut buf = [0u8; DEVICE_PAYLOAD_MAX];
742 let n = dev.payload(&mut buf);
743 out[at + 1..at + 1 + n].copy_from_slice(&buf[..n]);
744 at += 1 + DEVICE_PAYLOAD_MAX;
745 }
746 out[at] = u8::from(e.microphone);
747 out[at + 1] = e.vs_coin & 0b11;
751 out[at + 2] = u8::from(e.vs_service);
752 out[at + 3] = e.disk_side.unwrap_or(DISK_EJECTED);
753 at += 4;
754 if let Some(code) = &e.barcode {
755 let d = code.digits();
756 out[at] = digit_count(d);
757 out[at + 1..at + 1 + d.len()].copy_from_slice(d);
758 }
759 out
760}
761
762#[cfg(test)]
763mod tests {
764 use super::*;
765 use alloc::vec;
766
767 fn zapper(x: u16, trigger: bool) -> DeviceInput {
768 DeviceInput::Zapper { x, y: 7, trigger }
769 }
770
771 fn mixed() -> Vec<Option<ExtraInput>> {
774 let mut a = ExtraInput::default();
775 a.devices[1] = zapper(3, false);
776 a.disk_side = Some(0);
777 let mut b = a;
778 b.devices[1] = zapper(4, true);
779 b.devices[0] = DeviceInput::SnesMouse {
780 dx: -3,
781 dy: 9,
782 left: true,
783 right: false,
784 sensitivity: 2,
785 };
786 b.microphone = true;
787 b.vs_coin = 0b10;
788 b.vs_service = true;
789 b.disk_side = None;
790 b.barcode = Some(Barcode::parse("4901234567894").unwrap());
791 let mut c = b.held();
792 c.devices[0] = DeviceInput::FamilyKeyboard([9; 9]);
793 vec![
794 None,
795 Some(a),
796 Some(a),
797 Some(b),
798 Some(c),
799 None,
800 Some(ExtraInput::default()),
801 ]
802 }
803
804 #[test]
805 fn a_mixed_stream_round_trips_exactly() {
806 let frames = mixed();
807 let block = encode_events(frames.iter().map(Option::as_ref));
808 let back = decode_events(&block, frames.len()).expect("decodes");
809 assert_eq!(back, frames);
810 assert_eq!(encode_events(back.iter().map(Option::as_ref)), block);
812 }
813
814 #[test]
815 fn a_barcode_is_one_frame_long() {
816 let frames = mixed();
817 let back = decode_events(&encode_events(frames.iter().map(Option::as_ref)), 7).unwrap();
818 assert!(back[3].unwrap().barcode.is_some());
819 assert!(back[4].unwrap().barcode.is_none(), "not carried forward");
820 }
821
822 #[test]
823 fn controller_only_movies_cost_four_bytes() {
824 let frames = vec![None; 100];
825 let block = encode_events(frames.iter().map(Option::as_ref));
826 assert_eq!(block, 0u32.to_le_bytes());
827 assert_eq!(decode_events(&block, 100).unwrap(), frames);
828 }
829
830 fn raw(events: &[(u32, u8, &[u8])]) -> Vec<u8> {
832 let mut w = BinWriter::new();
833 w.u32(u32::try_from(events.len()).unwrap());
834 for (f, k, p) in events {
835 w.u32(*f);
836 w.u8(*k);
837 w.bytes(p);
838 }
839 w.into_vec()
840 }
841
842 #[test]
843 fn malformed_blocks_are_refused_with_a_reason() {
844 let on = (0, EV_EXTRA_ON, &[][..]);
845 let cases: &[(&str, Vec<u8>, usize)] = &[
846 ("truncated count", vec![1, 0], 4),
847 ("truncated event", raw(&[(0, EV_MICROPHONE, &[])]), 4),
848 ("past the end", raw(&[(4, EV_EXTRA_ON, &[])]), 4),
849 ("unknown kind", raw(&[on, (0, 0x7E, &[])]), 4),
850 ("field while off", raw(&[(0, EV_MICROPHONE, &[1])]), 4),
851 ("redundant value", raw(&[on, (0, EV_MICROPHONE, &[0])]), 4),
852 ("bad bool", raw(&[on, (0, EV_MICROPHONE, &[2])]), 4),
853 ("bad port", raw(&[on, (0, EV_DEVICE, &[2, 0])]), 4),
854 ("bad device", raw(&[on, (0, EV_DEVICE, &[1, 42])]), 4),
855 ("bad mat", raw(&[on, (0, EV_DEVICE, &[1, 3, 0, 0x10])]), 4),
856 ("bad coin", raw(&[on, (0, EV_VS_COIN, &[4])]), 4),
857 (
858 "bad barcode length",
859 raw(&[on, (0, EV_BARCODE, &[3, 1, 2, 3])]),
860 4,
861 ),
862 (
863 "bad check digit",
864 raw(&[on, (0, EV_BARCODE, &[8, 1, 2, 3, 4, 5, 6, 7, 1])]),
866 4,
867 ),
868 ("off while off", raw(&[(0, EV_EXTRA_OFF, &[])]), 4),
869 ("on twice", raw(&[on, (1, EV_EXTRA_ON, &[])]), 4),
870 (
871 "out of order",
872 raw(&[on, (2, EV_MICROPHONE, &[1]), (1, EV_VS_SERVICE, &[1])]),
873 4,
874 ),
875 (
876 "repeated",
877 raw(&[on, (1, EV_MICROPHONE, &[1]), (1, EV_MICROPHONE, &[0])]),
878 4,
879 ),
880 (
881 "off then on in one frame",
882 raw(&[on, (1, EV_EXTRA_OFF, &[]), (1, EV_EXTRA_ON, &[])]),
883 4,
884 ),
885 ];
886 for (what, block, frames) in cases {
887 assert!(
888 decode_events(block, *frames).is_err(),
889 "{what} must be refused"
890 );
891 }
892 let mut trailing = raw(&[on]);
893 trailing.push(0);
894 assert!(decode_events(&trailing, 4).is_err(), "trailing bytes");
895 }
896
897 #[test]
898 fn a_hostile_event_count_does_not_reserve_memory() {
899 let block = u32::MAX.to_le_bytes();
901 assert!(decode_events(&block, 10).is_err());
902 }
903
904 #[test]
905 fn attestation_bytes_tell_absent_from_neutral_and_see_every_field() {
906 let none = attestation_bytes(None);
907 let neutral = attestation_bytes(Some(&ExtraInput::default()));
908 assert_ne!(none, neutral);
909 let frames = mixed();
910 let mut seen = alloc::collections::BTreeSet::new();
911 for f in &frames {
912 seen.insert(attestation_bytes(f.as_ref()));
913 }
914 assert_eq!(seen.len(), 5);
916 let stray = ExtraInput {
919 vs_coin: 0b1111_0001,
920 ..ExtraInput::default()
921 };
922 let clean = ExtraInput {
923 vs_coin: 0b01,
924 ..ExtraInput::default()
925 };
926 assert_eq!(
927 attestation_bytes(Some(&stray)),
928 attestation_bytes(Some(&clean))
929 );
930 }
931
932 #[test]
936 fn the_input_log_codec_keeps_everything() {
937 use crate::{Buttons, FrameInput};
938 let frames: Vec<FrameInput> = mixed()
939 .into_iter()
940 .enumerate()
941 .map(|(i, extra)| {
942 let b = Buttons::from_bits_truncate(u8::try_from(i * 37 % 256).unwrap());
943 let mut f = FrameInput::four_players(b, b, b, b);
944 f.extra = extra;
945 f
946 })
947 .collect();
948 let bytes = FrameInput::encode_log(&frames);
949 assert_eq!(FrameInput::decode_log(&bytes).unwrap(), frames);
950 let mut long = bytes;
951 long.push(0);
952 assert!(FrameInput::decode_log(&long).is_err());
953 assert!(FrameInput::decode_log(&u32::MAX.to_le_bytes()).is_err());
954 }
955}