peppi/io/slippi/
mod.rs

1//! Slippi (`.slp`) serialization.
2
3pub mod de;
4pub mod ser;
5
6use serde::{Deserialize, Serialize};
7use std::{fmt, str};
8
9use crate::io::{Error, Result, parse_u8};
10
11pub use de::read;
12pub use ser::write;
13
14/// Peppi can read replays with higher versions than this, but that discards information.
15/// So we refuse to re-serialze such replays, to avoid inadvertent information loss.
16/// This restriction may be removed in the future.
17pub const MAX_SUPPORTED_VERSION: Version = Version(3, 18, 0);
18
19/// Every `.slp` file starts with a UBJSON opening brace, "raw" key & type (`{U\x03raw[$U#l`).
20pub const FILE_SIGNATURE: [u8; 11] = [
21	0x7b, 0x55, 0x03, 0x72, 0x61, 0x77, 0x5b, 0x24, 0x55, 0x23, 0x6c,
22];
23
24/// Slippi format version.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
26pub struct Version(pub u8, pub u8, pub u8);
27
28impl Version {
29	pub fn gte(&self, major: u8, minor: u8) -> bool {
30		self.0 > major || (self.0 == major && self.1 >= minor)
31	}
32
33	pub fn lt(&self, major: u8, minor: u8) -> bool {
34		!self.gte(major, minor)
35	}
36}
37
38impl str::FromStr for Version {
39	type Err = Error;
40	fn from_str(s: &str) -> Result<Self> {
41		let mut i = s.split('.');
42		match (i.next(), i.next(), i.next(), i.next()) {
43			(Some(major), Some(minor), Some(patch), None) => Ok(Version(
44				parse_u8(major)?,
45				parse_u8(minor)?,
46				parse_u8(patch)?,
47			)),
48			_ => Err(err!("invalid Slippi version: {}", s.to_string())),
49		}
50	}
51}
52
53impl fmt::Display for Version {
54	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55		write!(f, "{}.{}.{}", self.0, self.1, self.2)
56	}
57}
58
59/// Slippi format options.
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Slippi {
62	pub version: Version,
63}
64
65pub(crate) fn assert_max_version(version: Version) -> Result<()> {
66	if version <= MAX_SUPPORTED_VERSION {
67		Ok(())
68	} else {
69		Err(err!(
70			"unsupported version ({} > {})",
71			version,
72			MAX_SUPPORTED_VERSION
73		))
74	}
75}