Skip to main content

sm64_binds/sm64/mupen/
st.rs

1//! Reading (and, for tests and tools, writing) Mupen64 savestates.
2//!
3//! Two formats, both usually called `.st`, are recognised. The layouts are
4//! documented byte for byte in `docs/mupen64-st.md`; in short:
5//!
6//! - **Mupen64-rr / mupen64-rr-lua** (the TAS emulator): no magic. The file is
7//!   gzip (or, in newer rr-lua builds with `st_lz4` on, an LZ4 frame) around
8//!   a 32-character ROM MD5, the RCP register blocks, 8 MB of RDRAM at offset
9//!   0x1B0, SP memory, PIF RAM, the TLB lookup tables, the CPU registers, the
10//!   TLB entries, the PC and the event queue, then (rr-lua) a movie block.
11//! - **Mupen64Plus**: gzip around the magic `M64+SAVE`, a big-endian version,
12//!   the ROM MD5, the register blocks, and 8 MB of RDRAM at offset 0x1BC.
13//!
14//! Both store RDRAM as the emulator's host-order (little-endian) `u32` words.
15//! [`MupenState`] keeps it in N64 (big-endian) byte order instead, so N64
16//! address `0x80000000 + i` is byte `i`.
17
18use std::io::Read;
19
20use anyhow::{Error, Result, bail};
21
22/// Bytes of RDRAM both formats store (the 8 MB of an Expansion Pak, even
23/// when the game only uses 4 MB).
24pub const RDRAM_SIZE: usize = 0x80_0000;
25
26/// The MD5 of the US `.z64` ROM, as both emulators write it (upper case hex).
27pub const US_ROM_MD5: &str = "20B854B239203BAF6C961B850A4A51A2";
28
29const M64P_MAGIC: &[u8; 8] = b"M64+SAVE";
30
31/// Mupen64Plus: everything before the RDRAM is 44 header bytes and 400
32/// register bytes, and the fixed part ends after `vi_field`.
33const M64P_RDRAM: usize = 0x1BC;
34const M64P_FIXED_LEN: usize = 16_788_288;
35
36/// Mupen64-rr: the RDRAM follows 0x190 bytes of register blocks, and the
37/// fixed part (up to and including `vi_field`) is 0xA02BB4 bytes.
38const RR_RDRAM: usize = 0x1B0;
39const RR_FIXED_LEN: usize = 0xA0_2BB4;
40/// rr's LUT tables are 0x100000 *bytes* each (m64p's are that many words).
41const RR_LUT_BYTES: usize = 0x10_0000;
42
43/// Which emulator wrote a [`MupenState`].
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum MupenFormat {
46    /// Mupen64-rr or mupen64-rr-lua (no version field in the file).
47    Rr,
48    /// Mupen64Plus, with the file's version (e.g. `0x00010200` for 1.2).
49    Mupen64Plus { version: u32 },
50}
51
52/// How the file was compressed.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Compression {
55    None,
56    Gzip,
57    Lz4,
58}
59
60/// The movie block mupen64-rr-lua appends when a movie was playing or
61/// recording (its "freeze" data). `current_sample` is the number of input
62/// samples (controller polls) played so far: the movie frame of the state.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct RrMovie {
65    pub uid: u32,
66    pub current_sample: u32,
67    pub current_vi: u32,
68    pub length_samples: u32,
69    /// The movie's inputs up to `length_samples`, one `u32` per sample
70    /// (Mupen's `BUTTONS` layout, as in an `.m64`).
71    pub inputs: Vec<u32>,
72}
73
74/// A parsed Mupen64 savestate: the N64's RDRAM and CPU state.
75#[derive(Clone)]
76pub struct MupenState {
77    pub format: MupenFormat,
78    pub compression: Compression,
79    /// The ROM's MD5 as stored in the state (32 hex characters).
80    pub rom_md5: String,
81    /// RDRAM in N64 byte order: byte `i` is physical address `i`.
82    rdram: Vec<u8>,
83    /// General purpose registers.
84    pub gpr: [u64; 32],
85    /// Coprocessor 0 registers (Count is 9, Status 12, EPC 14).
86    pub cp0: [u32; 32],
87    /// Floating point registers, as 64-bit values.
88    pub fpr: [u64; 32],
89    pub fcr31: u32,
90    pub lo: u64,
91    pub hi: u64,
92    pub pc: u32,
93    pub next_interrupt: u32,
94    pub vi_field: u32,
95    /// The event queue, as (event type, count) pairs.
96    pub events: Vec<(u32, u32)>,
97    /// rr-lua's movie block, if the state has one.
98    pub movie: Option<RrMovie>,
99}
100
101impl std::fmt::Debug for MupenState {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("MupenState")
104            .field("format", &self.format)
105            .field("compression", &self.compression)
106            .field("rom_md5", &self.rom_md5)
107            .field("pc", &format_args!("{:#010x}", self.pc))
108            .field("events", &self.events.len())
109            .field("movie", &self.movie.as_ref().map(|m| m.current_sample))
110            .finish()
111    }
112}
113
114/// Reads little-endian values from a byte slice at a cursor.
115struct Cursor<'a> {
116    bytes: &'a [u8],
117    at: usize,
118}
119
120impl<'a> Cursor<'a> {
121    fn new(bytes: &'a [u8], at: usize) -> Self {
122        Cursor { bytes, at }
123    }
124    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
125        let end = self.at.checked_add(n).filter(|&e| e <= self.bytes.len());
126        let Some(end) = end else {
127            bail!("savestate truncated at {:#x}", self.at);
128        };
129        let s = &self.bytes[self.at..end];
130        self.at = end;
131        Ok(s)
132    }
133    fn u32(&mut self) -> Result<u32> {
134        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
135    }
136    fn u64(&mut self) -> Result<u64> {
137        Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
138    }
139    fn skip(&mut self, n: usize) -> Result<()> {
140        self.take(n).map(|_| ())
141    }
142}
143
144/// Undoes the file's compression. Gzip and LZ4 frames are recognised by their
145/// magic; anything else is taken as uncompressed.
146pub fn decompress(bytes: &[u8]) -> Result<(Vec<u8>, Compression)> {
147    // A generous cap: the largest states (rr-lua with a long movie and a
148    // screenshot) are a few tens of MB.
149    const LIMIT: u64 = 256 << 20;
150    if bytes.starts_with(&[0x1F, 0x8B]) {
151        let mut out = Vec::with_capacity(M64P_FIXED_LEN + 8192);
152        flate2::read::MultiGzDecoder::new(bytes)
153            .take(LIMIT)
154            .read_to_end(&mut out)
155            .map_err(|e| Error::msg(format!("bad gzip savestate: {e}")))?;
156        Ok((out, Compression::Gzip))
157    } else if bytes.starts_with(&[0x04, 0x22, 0x4D, 0x18]) {
158        let mut out = Vec::with_capacity(RR_FIXED_LEN + 8192);
159        lz4_flex::frame::FrameDecoder::new(bytes)
160            .take(LIMIT)
161            .read_to_end(&mut out)
162            .map_err(|e| Error::msg(format!("bad LZ4 savestate: {e}")))?;
163        Ok((out, Compression::Lz4))
164    } else {
165        Ok((bytes.to_vec(), Compression::None))
166    }
167}
168
169/// N64 byte order from the file's little-endian words.
170fn rdram_from_words(words: &[u8]) -> Vec<u8> {
171    let mut out = words.to_vec();
172    for w in out.as_chunks_mut::<4>().0 {
173        w.reverse();
174    }
175    out
176}
177
178fn md5_string(bytes: &[u8]) -> String {
179    String::from_utf8_lossy(bytes)
180        .trim_end_matches('\0')
181        .to_string()
182}
183
184impl MupenState {
185    /// Parses a savestate file's bytes (compressed or not), detecting the
186    /// format. Treats the input as untrusted: every read is bounds checked.
187    pub fn from_bytes(file: &[u8]) -> Result<MupenState> {
188        let (raw, compression) = decompress(file)?;
189        if raw.starts_with(M64P_MAGIC) {
190            Self::parse_m64p(&raw, compression)
191        } else if raw.starts_with(&[0xC8, 0xA6, 0xD8, 0x23]) || file.starts_with(b"PK\x03\x04") {
192            bail!(
193                "Project64-format states (.pj / zip) are not supported; save a Mupen64Plus .st instead"
194            )
195        } else if raw.len() >= RR_FIXED_LEN && raw[..32].iter().all(u8::is_ascii_hexdigit) {
196            Self::parse_rr(&raw, compression)
197        } else {
198            bail!(
199                "not a Mupen64 savestate ({} bytes after decompression, no M64+SAVE magic or ROM MD5)",
200                raw.len()
201            )
202        }
203    }
204
205    #[cfg(feature = "fs")]
206    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<MupenState> {
207        Self::from_bytes(&std::fs::read(path)?)
208    }
209
210    fn parse_m64p(raw: &[u8], compression: Compression) -> Result<MupenState> {
211        if raw.len() < M64P_FIXED_LEN {
212            bail!("Mupen64Plus savestate truncated ({} bytes)", raw.len());
213        }
214        let version = u32::from_be_bytes(raw[8..12].try_into().unwrap());
215        if version >> 16 != 1 {
216            bail!("Mupen64Plus savestate version {version:#010x} is not 1.x");
217        }
218        let rom_md5 = md5_string(&raw[12..44]);
219        let rdram = rdram_from_words(&raw[M64P_RDRAM..M64P_RDRAM + RDRAM_SIZE]);
220        let mut c = Cursor::new(raw, M64P_RDRAM + RDRAM_SIZE);
221        c.skip(0x2000)?; // SP DMEM + IMEM
222        c.skip(0x40)?; // PIF RAM
223        c.skip(4 + 20)?; // use_flashram, old flashram state
224        c.skip(2 * 0x10_0000 * 4)?; // TLB LUT_r, LUT_w (u32 each)
225        let mut s = Self::read_cpu(&mut c, rdram, rom_md5, compression, false)?;
226        s.format = MupenFormat::Mupen64Plus { version };
227        // The event queue: 1024 bytes of (type, count) pairs (1.1 and
228        // later; 1.0 wrote only up to the terminator).
229        let queue = &raw[M64P_FIXED_LEN..raw.len().min(M64P_FIXED_LEN + 1024)];
230        s.events = read_events(queue);
231        Ok(s)
232    }
233
234    fn parse_rr(raw: &[u8], compression: Compression) -> Result<MupenState> {
235        let rom_md5 = md5_string(&raw[..32]);
236        let rdram = rdram_from_words(&raw[RR_RDRAM..RR_RDRAM + RDRAM_SIZE]);
237        let mut c = Cursor::new(raw, RR_RDRAM + RDRAM_SIZE);
238        c.skip(0x2000)?; // SP DMEM + IMEM
239        c.skip(0x40)?; // PIF RAM
240        c.skip(24)?; // flashram
241        c.skip(2 * RR_LUT_BYTES)?;
242        let mut s = Self::read_cpu(&mut c, rdram, rom_md5, compression, true)?;
243        debug_assert_eq!(c.at, RR_FIXED_LEN);
244        // The event queue, up to and including the 0xFFFFFFFF terminator,
245        // then (rr-lua, and rr 1.1+) whether a movie block follows.
246        let mut events = Vec::new();
247        loop {
248            let ty = c.u32()?;
249            if ty == 0xFFFF_FFFF {
250                break;
251            }
252            events.push((ty, c.u32()?));
253            if events.len() > 128 {
254                bail!("rr savestate event queue has no terminator");
255            }
256        }
257        s.events = events;
258        if c.at + 4 <= raw.len() && c.u32()? != 0 {
259            let _size = c.u32()?;
260            let uid = c.u32()?;
261            let current_sample = c.u32()?;
262            let current_vi = c.u32()?;
263            let length_samples = c.u32()?;
264            let n = (length_samples as usize).saturating_add(1);
265            let inputs = c
266                .take(n.saturating_mul(4))
267                .map(|b| {
268                    b.as_chunks::<4>()
269                        .0
270                        .iter()
271                        .map(|w| u32::from_le_bytes(*w))
272                        .collect()
273                })
274                .unwrap_or_default();
275            s.movie = Some(RrMovie {
276                uid,
277                current_sample,
278                current_vi,
279                length_samples,
280                inputs,
281            });
282        }
283        Ok(s)
284    }
285
286    /// The CPU block common to both formats, from `llbit` to `vi_field`.
287    /// rr writes each CP0 register as 8 bytes (value, then 4 unused).
288    fn read_cpu(
289        c: &mut Cursor,
290        rdram: Vec<u8>,
291        rom_md5: String,
292        compression: Compression,
293        rr: bool,
294    ) -> Result<MupenState> {
295        let _llbit = c.u32()?;
296        let mut gpr = [0u64; 32];
297        for r in &mut gpr {
298            *r = c.u64()?;
299        }
300        let mut cp0 = [0u32; 32];
301        for r in &mut cp0 {
302            *r = c.u32()?;
303            if rr {
304                c.skip(4)?;
305            }
306        }
307        let lo = c.u64()?;
308        let hi = c.u64()?;
309        let mut fpr = [0u64; 32];
310        for r in &mut fpr {
311            *r = c.u64()?;
312        }
313        let _fcr0 = c.u32()?;
314        let fcr31 = c.u32()?;
315        c.skip(32 * 52)?; // TLB entries
316        let pc = c.u32()?;
317        let next_interrupt = c.u32()?;
318        let _next_vi = c.u32()?;
319        let vi_field = c.u32()?;
320        Ok(MupenState {
321            format: MupenFormat::Rr,
322            compression,
323            rom_md5,
324            rdram,
325            gpr,
326            cp0,
327            fpr,
328            fcr31,
329            lo,
330            hi,
331            pc,
332            next_interrupt,
333            vi_field,
334            events: Vec::new(),
335            movie: None,
336        })
337    }
338
339    /// Whether the state is from the US ROM, by the MD5 it stores.
340    pub fn is_us_rom(&self) -> bool {
341        self.rom_md5.eq_ignore_ascii_case(US_ROM_MD5)
342    }
343
344    /// All of RDRAM, in N64 (big-endian) byte order.
345    pub fn rdram(&self) -> &[u8] {
346        &self.rdram
347    }
348
349    /// `len` bytes at N64 address `addr` (KSEG0/KSEG1 virtual or physical).
350    pub fn bytes(&self, addr: u32, len: usize) -> Option<&[u8]> {
351        let p = (addr & 0x1FFF_FFFF) as usize;
352        self.rdram.get(p..p.checked_add(len)?)
353    }
354    pub fn u8(&self, addr: u32) -> Option<u8> {
355        self.bytes(addr, 1).map(|b| b[0])
356    }
357    pub fn u16(&self, addr: u32) -> Option<u16> {
358        self.bytes(addr, 2)
359            .map(|b| u16::from_be_bytes(b.try_into().unwrap()))
360    }
361    pub fn s16(&self, addr: u32) -> Option<i16> {
362        self.u16(addr).map(|v| v as i16)
363    }
364    pub fn u32(&self, addr: u32) -> Option<u32> {
365        self.bytes(addr, 4)
366            .map(|b| u32::from_be_bytes(b.try_into().unwrap()))
367    }
368    pub fn f32(&self, addr: u32) -> Option<f32> {
369        self.u32(addr).map(f32::from_bits)
370    }
371
372    /// A state with this RDRAM (N64 byte order, padded or cut to 8 MB) and
373    /// zeroed CPU registers, for tests and tools that make synthetic states.
374    pub fn from_rdram(format: MupenFormat, rdram: &[u8]) -> MupenState {
375        let mut r = rdram.to_vec();
376        r.resize(RDRAM_SIZE, 0);
377        MupenState {
378            format,
379            compression: Compression::Gzip,
380            rom_md5: US_ROM_MD5.to_string(),
381            rdram: r,
382            gpr: [0; 32],
383            cp0: [0; 32],
384            fpr: [0; 32],
385            fcr31: 0,
386            lo: 0,
387            hi: 0,
388            pc: 0x8000_0000,
389            next_interrupt: 0,
390            vi_field: 0,
391            events: Vec::new(),
392            movie: None,
393        }
394    }
395
396    /// Mutable RDRAM, for building synthetic states.
397    pub fn rdram_mut(&mut self) -> &mut [u8] {
398        &mut self.rdram
399    }
400
401    /// The state as an uncompressed file in its format, with the CPU
402    /// registers, PC and event queue it holds and every other register block
403    /// zeroed. Emulators would not run it as is (the RCP registers are
404    /// missing); it is for round-trip tests and synthetic loader tests.
405    pub fn to_uncompressed_bytes(&self) -> Vec<u8> {
406        let rr = matches!(self.format, MupenFormat::Rr);
407        let mut b = Vec::with_capacity(M64P_FIXED_LEN + 8192);
408        let mut md5 = self.rom_md5.as_bytes().to_vec();
409        md5.resize(32, 0);
410        if let MupenFormat::Mupen64Plus { version } = self.format {
411            b.extend_from_slice(M64P_MAGIC);
412            b.extend_from_slice(&version.to_be_bytes());
413            b.extend_from_slice(&md5);
414            b.resize(M64P_RDRAM, 0);
415        } else {
416            b.extend_from_slice(&md5);
417            b.resize(RR_RDRAM, 0);
418        }
419        for w in self.rdram.as_chunks::<4>().0 {
420            b.extend_from_slice(&[w[3], w[2], w[1], w[0]]);
421        }
422        b.resize(b.len() + 0x2000 + 0x40 + 24, 0); // SP memory, PIF RAM, flashram
423        b.resize(
424            b.len() + 2 * if rr { RR_LUT_BYTES } else { 0x10_0000 * 4 },
425            0,
426        );
427        b.extend_from_slice(&0u32.to_le_bytes()); // llbit
428        for r in self.gpr {
429            b.extend_from_slice(&r.to_le_bytes());
430        }
431        for r in self.cp0 {
432            b.extend_from_slice(&r.to_le_bytes());
433            if rr {
434                b.extend_from_slice(&[0; 4]);
435            }
436        }
437        b.extend_from_slice(&self.lo.to_le_bytes());
438        b.extend_from_slice(&self.hi.to_le_bytes());
439        for r in self.fpr {
440            b.extend_from_slice(&r.to_le_bytes());
441        }
442        b.extend_from_slice(&0u32.to_le_bytes());
443        b.extend_from_slice(&self.fcr31.to_le_bytes());
444        b.resize(b.len() + 32 * 52, 0);
445        for v in [self.pc, self.next_interrupt, 0, self.vi_field] {
446            b.extend_from_slice(&v.to_le_bytes());
447        }
448        let mut queue = Vec::new();
449        for &(t, n) in &self.events {
450            queue.extend_from_slice(&t.to_le_bytes());
451            queue.extend_from_slice(&n.to_le_bytes());
452        }
453        queue.extend_from_slice(&0xFFFF_FFFFu32.to_le_bytes());
454        if rr {
455            b.extend_from_slice(&queue);
456            match &self.movie {
457                None => b.extend_from_slice(&0u32.to_le_bytes()),
458                Some(m) => {
459                    b.extend_from_slice(&1u32.to_le_bytes());
460                    let size = 4 * (m.inputs.len() as u32) + 20;
461                    for v in [
462                        size,
463                        m.uid,
464                        m.current_sample,
465                        m.current_vi,
466                        m.length_samples,
467                    ] {
468                        b.extend_from_slice(&v.to_le_bytes());
469                    }
470                    let mut inputs = m.inputs.clone();
471                    inputs.resize(m.length_samples as usize + 1, 0);
472                    for v in inputs {
473                        b.extend_from_slice(&v.to_le_bytes());
474                    }
475                }
476            }
477        } else {
478            debug_assert_eq!(b.len(), M64P_FIXED_LEN);
479            queue.resize(1024, 0);
480            b.extend_from_slice(&queue);
481            b.extend_from_slice(&[0; 4]); // using_tlb
482            b.extend_from_slice(&[0; 4096]); // 1.2+ extra state
483        }
484        b
485    }
486
487    /// [`MupenState::to_uncompressed_bytes`], gzip-compressed like the
488    /// emulators write it.
489    pub fn to_gzip_bytes(&self) -> Vec<u8> {
490        use std::io::Write;
491        let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
492        e.write_all(&self.to_uncompressed_bytes()).unwrap();
493        e.finish().unwrap()
494    }
495}
496
497/// (type, count) pairs up to the 0xFFFFFFFF terminator.
498fn read_events(queue: &[u8]) -> Vec<(u32, u32)> {
499    let mut out = Vec::new();
500    for e in queue.as_chunks::<8>().0 {
501        let ty = u32::from_le_bytes(e[..4].try_into().unwrap());
502        if ty == 0xFFFF_FFFF {
503            break;
504        }
505        out.push((ty, u32::from_le_bytes(e[4..].try_into().unwrap())));
506    }
507    out
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    fn sample(format: MupenFormat) -> MupenState {
515        let mut s = MupenState::from_rdram(format, &[]);
516        // gGlobalTimer at 0x8032D5D4, big endian.
517        s.rdram_mut()[0x32D5D4..0x32D5D8].copy_from_slice(&0x1234_5678u32.to_be_bytes());
518        s.gpr[29] = 0xFFFF_FFFF_8020_0000;
519        s.cp0[9] = 77;
520        s.pc = 0x8024_6000;
521        s.events = vec![(1, 500), (8, 900)];
522        s
523    }
524
525    #[test]
526    fn m64p_round_trip() {
527        let s = sample(MupenFormat::Mupen64Plus {
528            version: 0x0001_0200,
529        });
530        let raw = s.to_uncompressed_bytes();
531        assert_eq!(&raw[..8], b"M64+SAVE");
532        // RDRAM word for 0x8032D5D4 stored little endian at 0x1BC + offset.
533        assert_eq!(&raw[0x1BC + 0x32D5D4..][..4], &0x1234_5678u32.to_le_bytes());
534        for bytes in [raw.clone(), s.to_gzip_bytes()] {
535            let p = MupenState::from_bytes(&bytes).unwrap();
536            assert_eq!(
537                p.format,
538                MupenFormat::Mupen64Plus {
539                    version: 0x0001_0200
540                }
541            );
542            assert_eq!(p.u32(0x8032_D5D4), Some(0x1234_5678));
543            assert_eq!(p.u16(0x8032_D5D4), Some(0x1234));
544            assert_eq!(p.gpr[29], 0xFFFF_FFFF_8020_0000);
545            assert_eq!(p.cp0[9], 77);
546            assert_eq!(p.pc, 0x8024_6000);
547            assert_eq!(p.events, vec![(1, 500), (8, 900)]);
548            assert!(p.is_us_rom());
549        }
550    }
551
552    #[test]
553    fn rr_round_trip_with_movie() {
554        let mut s = sample(MupenFormat::Rr);
555        s.movie = Some(RrMovie {
556            uid: 0xABCD,
557            current_sample: 3,
558            current_vi: 7,
559            length_samples: 4,
560            inputs: vec![1, 2, 3, 4, 5],
561        });
562        let raw = s.to_uncompressed_bytes();
563        assert_eq!(&raw[0x1B0 + 0x32D5D4..][..4], &0x1234_5678u32.to_le_bytes());
564        // The PC sits 16 bytes before the end of the fixed part.
565        assert_eq!(
566            &raw[RR_FIXED_LEN - 16..][..4],
567            &0x8024_6000u32.to_le_bytes()
568        );
569        let p = MupenState::from_bytes(&s.to_gzip_bytes()).unwrap();
570        assert_eq!(p.format, MupenFormat::Rr);
571        assert_eq!(p.compression, Compression::Gzip);
572        assert_eq!(p.u32(0x8032_D5D4), Some(0x1234_5678));
573        assert_eq!(p.pc, 0x8024_6000);
574        assert_eq!(p.cp0[9], 77);
575        assert_eq!(p.events, vec![(1, 500), (8, 900)]);
576        assert_eq!(p.movie, s.movie);
577    }
578
579    #[test]
580    fn rr_lz4() {
581        use std::io::Write;
582        let s = sample(MupenFormat::Rr);
583        let mut e = lz4_flex::frame::FrameEncoder::new(Vec::new());
584        e.write_all(&s.to_uncompressed_bytes()).unwrap();
585        let p = MupenState::from_bytes(&e.finish().unwrap()).unwrap();
586        assert_eq!(p.compression, Compression::Lz4);
587        assert_eq!(p.u32(0x8032_D5D4), Some(0x1234_5678));
588    }
589
590    #[test]
591    fn rejects_garbage_and_truncation() {
592        assert!(MupenState::from_bytes(b"hello").is_err());
593        let s = sample(MupenFormat::Rr);
594        let raw = s.to_uncompressed_bytes();
595        assert!(MupenState::from_bytes(&raw[..RR_FIXED_LEN - 1]).is_err());
596        let s = sample(MupenFormat::Mupen64Plus {
597            version: 0x0001_0200,
598        });
599        let raw = s.to_uncompressed_bytes();
600        assert!(MupenState::from_bytes(&raw[..M64P_FIXED_LEN - 1]).is_err());
601    }
602}