// SPDX-License-Identifier: MIT //! CartDescription: what the board must build for one cartridge, with where each fact came from. //! //! The vocabulary is the A78 v4 header's (docs/cartridge.md "What comes out"; //! the 7800 Development Wiki's "A78 header specification"), because that is what //! flash carts and the homebrew toolchain write. `provenance` names the source //! of every field that is not a default; `certainty` is the weakest source among //! the fields the board needs to build the hardware (scheme, $4000, sound chips). //! The vocabulary, sources and defaults are a data model, not hardware values; each //! field's evidence is its `provenance` (DOC for header and table sources). //! //! Rust-forced differences (a7800-python `cartridge/description.py` at d6b220d): the //! frozen dataclass is a `Clone` struct; `with_fields(source, **fields)` takes //! `(name, Value)` pairs, [`Value`] holding the field types the reference's keyword //! arguments carry; `provenance` is an insertion-ordered list of pairs (a Python dict); //! the properties `sha256`, `sha1`, `crc32` and `size` are methods; `Refused` is an //! error value. use sha1::Sha1; use sha2::{Digest, Sha256}; pub const SCHEMES: [&str; 5] = ["linear", "supergame", "activision", "absolute", "souper"]; pub const AT_4000: [&str; 9] = [ "none", "ram16", "ram8-mirror", "ram32-halt", "ram32-latch", "rom", "fixed-bank", "mirror-ram-2k", "pokey", ]; // Sources, strongest first (docs/cartridge.md "When an .a78 header contradicts the table"). pub const SOURCES: [&str; 8] = [ "override", "softlist", "confirmed", "a78 header v4", "a78 header v3", "a78 header", "size", "default", ]; /// A field's value, as the reference's keyword arguments carry it. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Value { Str(String), Bool(bool), Pokey(Vec), Strings(Vec), Pair(String, String), OptStr(Option), } impl Value { pub fn s(text: &str) -> Value { Value::Str(text.to_string()) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CartDescription { pub payload: Vec, pub console: String, // or "2600" pub scheme: String, pub bankset: bool, pub at_4000: String, pub pokey: Vec, // base addresses: 0x440, 0x450, 0x800, 0x4000 pub pokey_write_only: bool, pub ym2151: bool, pub covox: bool, pub adpcm: bool, pub bupchip: bool, pub irq_sources: Vec, pub hsc: bool, pub xm: bool, pub save: String, // or "savekey" pub controllers: (String, String), pub region: String, // ntsc | pal | both | unknown pub composite_artifacts: bool, pub title: String, pub provenance: Vec<(String, String)>, pub certainty: String, pub notes: Vec, // matched after trimming, header/table conflicts, labels pub a2600_scheme: Option, // for console == "2600": a2600-python's family } impl CartDescription { /// `CartDescription(payload=..., title=...)` with every other field its default. pub fn new(payload: &[u8]) -> CartDescription { CartDescription { payload: payload.to_vec(), console: "7800".to_string(), scheme: "linear".to_string(), bankset: false, at_4000: "none".to_string(), pokey: Vec::new(), pokey_write_only: false, ym2151: false, covox: false, adpcm: false, bupchip: false, irq_sources: Vec::new(), hsc: false, xm: false, save: "none".to_string(), controllers: ("proline".to_string(), "proline".to_string()), region: "ntsc".to_string(), composite_artifacts: false, title: String::new(), provenance: Vec::new(), certainty: "default".to_string(), notes: Vec::new(), a2600_scheme: None, } } pub fn sha256(&self) -> String { hex(&Sha256::digest(&self.payload)) } pub fn sha1(&self) -> String { hex(&Sha1::digest(&self.payload)) } pub fn crc32(&self) -> u32 { crc32fast::hash(&self.payload) } pub fn size(&self) -> usize { self.payload.len() } /// Set one field by name (the reference's `replace(self, **{name: value})`). pub fn set(&mut self, name: &str, value: Value) { match (name, value) { ("console", Value::Str(v)) => self.console = v, ("scheme", Value::Str(v)) => self.scheme = v, ("bankset", Value::Bool(v)) => self.bankset = v, ("at_4000", Value::Str(v)) => self.at_4000 = v, ("pokey", Value::Pokey(v)) => self.pokey = v, ("pokey_write_only", Value::Bool(v)) => self.pokey_write_only = v, ("ym2151", Value::Bool(v)) => self.ym2151 = v, ("covox", Value::Bool(v)) => self.covox = v, ("adpcm", Value::Bool(v)) => self.adpcm = v, ("bupchip", Value::Bool(v)) => self.bupchip = v, ("irq_sources", Value::Strings(v)) => self.irq_sources = v, ("hsc", Value::Bool(v)) => self.hsc = v, ("xm", Value::Bool(v)) => self.xm = v, ("save", Value::Str(v)) => self.save = v, ("controllers", Value::Pair(a, b)) => self.controllers = (a, b), ("region", Value::Str(v)) => self.region = v, ("composite_artifacts", Value::Bool(v)) => self.composite_artifacts = v, ("title", Value::Str(v)) => self.title = v, ("a2600_scheme", Value::OptStr(v)) => self.a2600_scheme = v, (name, value) => panic!("CartDescription has no field {name} of type {value:?}"), } } /// A field's value by name (for the loader's header/table comparison). pub fn get(&self, name: &str) -> Value { match name { "scheme" => Value::Str(self.scheme.clone()), "at_4000" => Value::Str(self.at_4000.clone()), "pokey" => Value::Pokey(self.pokey.clone()), "bankset" => Value::Bool(self.bankset), "ym2151" => Value::Bool(self.ym2151), "hsc" => Value::Bool(self.hsc), "xm" => Value::Bool(self.xm), "region" => Value::Str(self.region.clone()), _ => panic!("get({name}) is not used"), } } /// A copy with `fields` set and attributed to `source`. pub fn with_fields(&self, source: &str, fields: &[(&str, Value)]) -> CartDescription { let mut out = self.clone(); for (name, value) in fields { match out.provenance.iter_mut().find(|(n, _)| n == name) { Some(entry) => entry.1 = source.to_string(), None => out.provenance.push((name.to_string(), source.to_string())), } out.set(name, value.clone()); } out } pub fn provenance_of(&self, field: &str) -> Option<&str> { self.provenance .iter() .find(|(n, _)| n == field) .map(|(_, s)| s.as_str()) } pub fn summary(&self) -> String { let mut parts = vec![self.console.clone(), self.scheme.clone()]; if self.bankset { parts.push("bankset".to_string()); } if self.at_4000 != "none" { parts.push(format!("$4000={}", self.at_4000)); } parts.extend(self.pokey.iter().map(|a| format!("pokey@{a:X}"))); for (flag, on) in [ ("ym2151", self.ym2151), ("covox", self.covox), ("hsc", self.hsc), ("xm", self.xm), ("bupchip", self.bupchip), ] { if on { parts.push(flag.to_string()); } } if self.controllers != ("proline".to_string(), "proline".to_string()) { parts.push(format!("{}/{}", self.controllers.0, self.controllers.1)); } parts.join(" ") + &format!(" [{}; {}]", self.region, self.certainty) } } /// The documented refusal: the loader cannot say what hardware this payload needs. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Refused { pub message: String, pub sha256: String, } impl Refused { pub fn new(message: impl Into) -> Refused { Refused { message: message.into(), sha256: String::new(), } } } impl std::fmt::Display for Refused { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.message) } } impl std::error::Error for Refused {} pub fn hex(digest: &[u8]) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() }