[core] API: compiling Seam 1 skeleton (types, signatures, stubs)

This commit is contained in:
2026-11-22 22:58:26 +01:00
parent 8f2bf986af
commit 5c17aac8d4
19 changed files with 1084 additions and 1 deletions
+25
View File
@@ -0,0 +1,25 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Domi games: Atrium registry entries with `kind = "game"`, launched through their `domi-<app>://open` link, or
//! web games (Rosea, Moin) opened by URL.
use crate::error::ParseError;
use crate::model::Game;
/// How a Domi game starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DomiLaunch<'a> {
/// `domi-<app>://open`; `app` follows the Atrium id rules.
Link { app: &'a str },
/// A web game: `https://` only, the host must be one of `allowed_hosts`.
Web { url: &'a str, allowed_hosts: &'a [&'a str] },
}
/// The game for one Domi entry. `id` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end) and
/// becomes `domi:<id>`; `name` is the title. No install folder.
pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result<Game, ParseError> {
let _ = (id, name, launch);
Err(ParseError::BadId)
}
+18
View File
@@ -0,0 +1,18 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Epic Games Launcher: one JSON `.item` manifest per installed app in
//! `%ProgramData%\Epic\EpicGamesLauncher\Data\Manifests`. Launch is
//! `com.epicgames.launcher://apps/<AppName>?action=launch&silent=true`.
use crate::error::ParseError;
use crate::model::Game;
/// The game described by one `.item` manifest. Reads `AppName`, `DisplayName` and `InstallLocation` (all
/// required strings) and `MainGameAppName` (optional; when it names another app the file is an add-on and gives
/// [`ParseError::NotAGame`]). Other fields are ignored but must still be well-formed JSON within the caps.
pub fn item(json: &[u8]) -> Result<Game, ParseError> {
let _ = json;
Err(ParseError::Syntax { at: 0 })
}
+61
View File
@@ -0,0 +1,61 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
/// Why an input was refused. The `&'static str` names the field or the token kind; it never carries input text,
/// so an error is always safe to log.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseError {
/// The input is larger than [`crate::limits::MAX_FILE`].
TooLarge,
/// Objects are nested deeper than [`crate::limits::MAX_DEPTH`].
TooDeep,
/// A string or the whole input is not valid UTF-8.
NotUtf8,
/// The text is malformed at this byte offset.
Syntax { at: usize },
/// A required field is absent.
Missing(&'static str),
/// A field has the wrong type (an object where a string belongs, a number where a string belongs, ...).
WrongType(&'static str),
/// A path field is not a valid [`crate::WinPath`] or escapes where it must stay.
BadPath(&'static str),
/// An id (Steam app id, Epic app name, GOG id, Domi id, [`crate::GameId`]) is malformed or out of range.
BadId,
/// A key or an entry appears twice.
Duplicate(&'static str),
/// A key, value or field is longer than its cap.
TooLong(&'static str),
/// More entries than the cap allows.
TooMany(&'static str),
/// A text field, URL or argument holds characters it may not hold.
BadValue(&'static str),
/// The file is valid but describes something that is not a game (a Steam redistributable, an Epic add-on).
/// Callers skip these quietly.
NotAGame(&'static str),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::TooLarge => write!(f, "input is larger than {} bytes", crate::limits::MAX_FILE),
ParseError::TooDeep => write!(f, "nesting is deeper than {} levels", crate::limits::MAX_DEPTH),
ParseError::NotUtf8 => f.write_str("text is not valid UTF-8"),
ParseError::Syntax { at } => write!(f, "syntax error at byte {at}"),
ParseError::Missing(what) => write!(f, "missing field: {what}"),
ParseError::WrongType(what) => write!(f, "wrong type for field: {what}"),
ParseError::BadPath(what) => write!(f, "invalid path: {what}"),
ParseError::BadId => f.write_str("invalid id"),
ParseError::Duplicate(what) => write!(f, "duplicate: {what}"),
ParseError::TooLong(what) => write!(f, "too long: {what}"),
ParseError::TooMany(what) => write!(f, "too many: {what}"),
ParseError::BadValue(what) => write!(f, "invalid value: {what}"),
ParseError::NotAGame(what) => write!(f, "not a game: {what}"),
}
}
}
impl std::error::Error for ParseError {}
+33
View File
@@ -0,0 +1,33 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! GOG: the app reads one registry key per installed game (assumption, verify on the PC:
//! `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\<gameID>` with the values `gameID`, `gameName`, `path`, `exe`,
//! `workingDir`, `launchParam`) and passes the values in. Launch is the `.exe` directly.
use crate::error::ParseError;
use crate::model::Game;
/// The registry values of one GOG game, as the app read them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GogEntry {
/// `gameID`: 1 to 20 digits.
pub game_id: String,
/// `gameName`: the title.
pub name: String,
/// `path`: the install folder, absolute.
pub path: String,
/// `exe`: the program, absolute or relative to `path`; must end in `.exe` and lie inside `path`.
pub exe: String,
/// `workingDir`: absolute or relative to `path`; empty or absent means the exe's folder.
pub working_dir: Option<String>,
/// `launchParam`: arguments, split on spaces with `"` grouping.
pub launch_params: Option<String>,
}
/// The game for one GOG entry.
pub fn game(e: &GogEntry) -> Result<Game, ParseError> {
let _ = e;
Err(ParseError::BadId)
}
+127
View File
@@ -0,0 +1,127 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::error::ParseError;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// Where a game came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Source {
Steam,
Epic,
Gog,
Manual,
Domi,
}
impl Source {
/// Every source, in declaration order.
pub const ALL: [Source; 5] = [Source::Steam, Source::Epic, Source::Gog, Source::Manual, Source::Domi];
/// The lowercase name used in a [`GameId`] and in JSON: `steam`, `epic`, `gog`, `manual`, `domi`.
pub fn as_str(self) -> &'static str {
match self {
Source::Steam => "steam",
Source::Epic => "epic",
Source::Gog => "gog",
Source::Manual => "manual",
Source::Domi => "domi",
}
}
/// Which source wins when two games share an install folder: Steam > Epic > GOG > Domi > Manual.
pub fn priority(self) -> u8 {
match self {
Source::Steam => 5,
Source::Epic => 4,
Source::Gog => 3,
Source::Domi => 2,
Source::Manual => 1,
}
}
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Source {
type Err = ParseError;
/// Strict: exactly one of the lowercase names.
fn from_str(s: &str) -> Result<Self, Self::Err> {
Source::ALL.into_iter().find(|src| src.as_str() == s).ok_or(ParseError::BadId)
}
}
/// A game's id: `<source>:<native id>`, only `[a-z0-9:._-]`, at most [`crate::limits::MAX_GAME_ID`] bytes.
///
/// The native part is checked per source: Steam a canonical non-zero `u32`, Epic `[a-z0-9_-]{1,64}` (the app
/// name, lowercased), GOG 1 to 20 digits, Manual 16 lowercase hex digits, Domi an Atrium id.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct GameId(String);
impl GameId {
/// Builds and checks `<source>:<native>`.
pub fn new(source: Source, native: &str) -> Result<GameId, ParseError> {
let _ = (source, native);
Err(ParseError::BadId)
}
pub fn as_str(&self) -> &str {
&self.0
}
/// The source named by the prefix.
pub fn source(&self) -> Source {
Source::Manual
}
/// The part after `<source>:`.
pub fn native(&self) -> &str {
""
}
}
impl fmt::Display for GameId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for GameId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let _ = s;
Err(ParseError::BadId)
}
}
impl TryFrom<String> for GameId {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl From<GameId> for String {
fn from(id: GameId) -> String {
id.0
}
}
impl AsRef<str> for GameId {
fn as_ref(&self) -> &str {
&self.0
}
}
+103
View File
@@ -0,0 +1,103 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::error::ParseError;
use crate::path::WinPath;
use serde::{Deserialize, Serialize};
/// How to start a game. The protocol variants become a URI through [`Launch::uri`]; [`Launch::Exe`] is started
/// directly (never through a shell) with an explicit working folder.
///
/// The fields are public so callers can match on them, but every builder ([`Launch::steam`], [`Launch::epic`],
/// [`Launch::exe`], [`Launch::domi_link`], [`Launch::web`]) validates, deserialising validates, and
/// [`Launch::uri`] validates again, so a hand-built bad value yields no URI.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", try_from = "LaunchRepr")]
pub enum Launch {
/// `steam://rungameid/<id>`.
SteamRunGameId(u32),
/// `com.epicgames.launcher://apps/<app_name>?action=launch&silent=true`; `app_name` is `[A-Za-z0-9_-]{1,64}`.
Epic { app_name: String },
/// GOG and manual games: the `.exe`, its working folder and the arguments, passed as separate arguments.
Exe { exe: WinPath, working_dir: WinPath, args: Vec<String> },
/// `domi-<app>://open`; `app` follows the Atrium id rules.
DomiLink { app: String },
/// A web game: `https://` only, the host on an allow-list the caller passes in.
Url(String),
}
impl Launch {
/// A Steam launch; the app id may not be 0.
pub fn steam(app_id: u32) -> Result<Launch, ParseError> {
let _ = app_id;
Err(ParseError::BadId)
}
/// An Epic launch; `app_name` must match `[A-Za-z0-9_-]{1,64}`.
pub fn epic(app_name: &str) -> Result<Launch, ParseError> {
let _ = app_name;
Err(ParseError::BadId)
}
/// A direct launch. `exe` must end in `.exe` (so never a `.bat`, `.cmd` or `.lnk`, which Windows would hand to
/// a shell); each argument is checked (no control characters, caps on count and length).
pub fn exe(exe: WinPath, working_dir: WinPath, args: Vec<String>) -> Result<Launch, ParseError> {
let _ = (exe, working_dir, args);
Err(ParseError::BadPath("exe"))
}
/// A Domi app link; `app` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end).
pub fn domi_link(app: &str) -> Result<Launch, ParseError> {
let _ = app;
Err(ParseError::BadId)
}
/// A web game. The URL must be `https://<host>[/path][?query][#fragment]` with no user info and no port, and
/// `host` must equal (ignoring case) one of `allowed_hosts`. The scheme and host are lowercased.
pub fn web(url: &str, allowed_hosts: &[&str]) -> Result<Launch, ParseError> {
let _ = (url, allowed_hosts);
Err(ParseError::BadValue("url"))
}
/// The exact URI for the protocol variants, rebuilt from the validated fields; `None` for [`Launch::Exe`] and
/// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only; use
/// [`Launch::uri_checked`] to apply the host allow-list again.
pub fn uri(&self) -> Option<String> {
None
}
/// As [`Launch::uri`], and a [`Launch::Url`] must also have its host in `allowed_hosts`.
pub fn uri_checked(&self, allowed_hosts: &[&str]) -> Option<String> {
let _ = allowed_hosts;
None
}
}
/// The wire shape of [`Launch`]; deserialising goes through it so every field is validated.
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum LaunchRepr {
SteamRunGameId(u32),
Epic { app_name: String },
Exe { exe: WinPath, working_dir: WinPath, args: Vec<String> },
DomiLink { app: String },
Url(String),
}
impl TryFrom<LaunchRepr> for Launch {
type Error = ParseError;
fn try_from(r: LaunchRepr) -> Result<Self, Self::Error> {
match r {
LaunchRepr::SteamRunGameId(id) => Launch::steam(id),
LaunchRepr::Epic { app_name } => Launch::epic(&app_name),
LaunchRepr::Exe { exe, working_dir, args } => Launch::exe(exe, working_dir, args),
LaunchRepr::DomiLink { app } => Launch::domi_link(&app),
LaunchRepr::Url(url) => {
let _ = url;
Err(ParseError::BadValue("url"))
}
}
}
}
+50
View File
@@ -0,0 +1,50 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The pure core of Arena Domi: strict parsers for game launcher files and the game library model.
//!
//! Nothing here touches the file system, processes, the network, the environment, the registry or the clock.
//! Inputs are bytes or values; outputs are [`Game`]s and a merged [`Library`]. Every parser treats its input as
//! hostile: sizes, depth, lengths and counts are capped ([`limits`]), errors are typed ([`ParseError`]) and no input
//! can make the crate panic.
//!
//! Sources: [`steam`] (`libraryfolders.vdf`, `appmanifest_<id>.acf`), [`epic`] (`.item` JSON), [`gog`] (registry
//! values the app passes in), [`manual`] (an `.exe` the user picked) and [`domi`] (Domi games from the Atrium
//! registry). [`merge`] dedupes the scans into one library.
//!
//! Launch strings are built by [`Launch::uri`] only from validated, parsed fields.
#![forbid(unsafe_code)]
#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::string_slice,
clippy::panic,
clippy::todo,
clippy::unimplemented,
clippy::unreachable
)]
mod error;
mod id;
mod launch;
pub mod limits;
mod model;
mod path;
mod text;
pub mod vdf;
pub mod domi;
pub mod epic;
pub mod gog;
pub mod manual;
pub mod steam;
pub use domi::DomiLaunch;
pub use error::ParseError;
pub use id::{GameId, Source};
pub use launch::Launch;
pub use model::{CoverHint, Game, Library, merge};
pub use path::WinPath;
+45
View File
@@ -0,0 +1,45 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Every cap the parsers enforce. Anything over a cap is refused, never truncated. `docs/FORMATS.md` lists them
//! with the error each one gives.
/// Largest input file (VDF, ACF, `.item` JSON), in bytes.
pub const MAX_FILE: usize = 1 << 20;
/// Deepest nesting of objects (VDF `{`, JSON `{` and `[`).
pub const MAX_DEPTH: usize = 32;
/// Longest VDF key, in bytes after unescaping.
pub const MAX_KEY: usize = 256;
/// Longest VDF value, in bytes after unescaping.
pub const MAX_VALUE: usize = 4096;
/// Most escape sequences in one VDF string.
pub const MAX_ESCAPES: usize = 256;
/// Most key/value pairs in one VDF document, counted over every level.
pub const MAX_ENTRIES: usize = 65_536;
/// Most Steam library folders in one `libraryfolders.vdf`.
pub const MAX_LIBRARIES: usize = 64;
/// Longest Windows path, in UTF-16 code units (`MAX_PATH`).
pub const MAX_PATH: usize = 260;
/// Longest game title, in characters after trimming.
pub const MAX_TITLE: usize = 256;
/// Longest [`crate::GameId`], in bytes.
pub const MAX_GAME_ID: usize = 96;
/// Longest Epic app name, in bytes (`[A-Za-z0-9_-]{1,64}`).
pub const MAX_EPIC_APP: usize = 64;
/// Longest Domi app id, in bytes (Atrium id rules: `[a-z0-9-]{1,32}`, no `-` at either end).
pub const MAX_DOMI_ID: usize = 32;
/// Longest GOG game id, in digits.
pub const MAX_GOG_ID: usize = 20;
/// Longest launch-parameter string a GOG entry may carry, in bytes.
pub const MAX_ARGS_LINE: usize = 4096;
/// Most arguments an [`crate::Launch::Exe`] may carry.
pub const MAX_ARGS: usize = 32;
/// Longest single argument, in bytes.
pub const MAX_ARG: usize = 1024;
/// Longest web-game URL, in bytes.
pub const MAX_URL: usize = 2048;
/// Longest host name in a web-game URL, in bytes.
pub const MAX_HOST: usize = 253;
/// Most games one [`crate::merge`] call accepts over all scans; the rest are dropped.
pub const MAX_GAMES: usize = 100_000;
+16
View File
@@ -0,0 +1,16 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! A game the user added by picking its `.exe`.
use crate::error::ParseError;
use crate::model::Game;
/// The game for an `.exe` the user picked. The id is `manual:<16 hex>`, a stable hash of the path ignoring case,
/// so adding the same file twice gives the same id. The title defaults to the file name without `.exe`; the
/// install and working folder are the exe's folder; no arguments.
pub fn game(exe: &str, title: Option<&str>) -> Result<Game, ParseError> {
let _ = (exe, title);
Err(ParseError::BadPath("exe"))
}
+74
View File
@@ -0,0 +1,74 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::id::{GameId, Source};
use crate::launch::Launch;
use crate::path::WinPath;
use serde::{Deserialize, Serialize};
/// One game in the library.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Game {
pub id: GameId,
pub source: Source,
/// Display title: trimmed, 1 to [`crate::limits::MAX_TITLE`] characters, no control characters.
pub title: String,
pub install_dir: Option<WinPath>,
pub launch: Launch,
pub cover: Option<CoverHint>,
}
/// Where the tile's picture comes from. No online lookups, ever.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CoverHint {
/// Steam's own local library cache for this app id (the app finds the file).
SteamLibraryCache { app_id: u32 },
/// A picture file on disk.
LocalFile(WinPath),
/// A lettered tile: the title's first letter or digit on a colour of this hue (0 to 359).
Lettered { letter: char, hue: u16 },
}
impl CoverHint {
/// The lettered tile for a game: the first letter or digit of `title` (uppercased; `#` when there is none) and a
/// hue derived from `id`, so a game keeps its colour across scans.
pub fn lettered(title: &str, id: &GameId) -> CoverHint {
crate::text::lettered(title, id)
}
}
/// The merged library, ordered by title.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Library {
pub games: Vec<Game>,
}
impl Library {
/// The game with this id.
pub fn get(&self, id: &GameId) -> Option<&Game> {
self.games.iter().find(|g| &g.id == id)
}
pub fn len(&self) -> usize {
self.games.len()
}
pub fn is_empty(&self) -> bool {
self.games.is_empty()
}
}
/// Merges per-source scans into one library.
///
/// - The same [`GameId`] is kept once (its first occurrence).
/// - Games of different sources with the same install folder (compared ignoring case): only the highest
/// [`Source::priority`] stays (Steam > Epic > GOG > Domi > Manual). Games of the same source are never dropped
/// for sharing a folder.
/// - The result is sorted by title (ignoring case), then by id, so the order does not depend on scan order.
/// - At most [`crate::limits::MAX_GAMES`] games are considered; the rest are dropped.
pub fn merge(scans: Vec<Vec<Game>>) -> Library {
let _ = scans;
Library::default()
}
+104
View File
@@ -0,0 +1,104 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::error::ParseError;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// An absolute Windows path with a drive letter, checked and normalised.
///
/// Refused: anything not starting with `X:\` (so UNC `\\server\share`, `\\?\` and `\\.\` too), `.` and `..`
/// components, NUL and other control characters, `<>:"|?*` (a `:` only after the drive letter), device names
/// (`CON`, `NUL`, `COM1`, ...) as any component, components ending in a dot or a space, and paths over
/// [`crate::limits::MAX_PATH`] UTF-16 units. Normalised: `/` becomes `\`, repeated separators collapse, the drive
/// letter is uppercase and a trailing separator is dropped (except on the drive root `X:\`).
///
/// Equality is exact on the normalised text; [`WinPath::eq_ignore_case`] compares the way Windows does.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct WinPath(String);
impl WinPath {
/// Checks and normalises `s`.
pub fn parse(s: &str) -> Result<WinPath, ParseError> {
let _ = s;
Err(ParseError::BadPath("path"))
}
pub fn as_str(&self) -> &str {
&self.0
}
/// Appends a relative path (`a\b` or `a/b`); the same component rules apply and it may not climb out.
pub fn join(&self, relative: &str) -> Result<WinPath, ParseError> {
let _ = relative;
Err(ParseError::BadPath("path"))
}
/// The containing folder, or `None` for a drive root.
pub fn parent(&self) -> Option<WinPath> {
None
}
/// The last component, or `None` for a drive root.
pub fn file_name(&self) -> Option<&str> {
None
}
/// The components after the drive root.
pub fn components(&self) -> impl Iterator<Item = &str> {
std::iter::empty()
}
/// The case-folded form Windows treats as the same place, for comparing and deduping.
pub fn key(&self) -> String {
self.0.to_lowercase()
}
/// True when both name the same place, ignoring case.
pub fn eq_ignore_case(&self, other: &WinPath) -> bool {
self.key() == other.key()
}
/// True when `self` is `base` or lies inside it (component-wise, ignoring case).
pub fn starts_with(&self, base: &WinPath) -> bool {
let _ = base;
false
}
}
impl fmt::Display for WinPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for WinPath {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
WinPath::parse(s)
}
}
impl TryFrom<String> for WinPath {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
WinPath::parse(&s)
}
}
impl From<WinPath> for String {
fn from(p: WinPath) -> String {
p.0
}
}
impl AsRef<str> for WinPath {
fn as_ref(&self) -> &str {
&self.0
}
}
+38
View File
@@ -0,0 +1,38 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Steam: `config/libraryfolders.vdf` lists the library folders; each installed app has
//! `<library>/steamapps/appmanifest_<id>.acf`. Launch is `steam://rungameid/<id>`.
use crate::error::ParseError;
use crate::model::Game;
use crate::path::WinPath;
/// The library folders listed in `libraryfolders.vdf` (both the current layout, `"0" { "path" "..." }`, and the
/// old one, `"1" "D:\\SteamLibrary"`). At most [`crate::limits::MAX_LIBRARIES`]; a path listed twice is refused.
pub fn library_folders(vdf: &[u8]) -> Result<Vec<WinPath>, ParseError> {
let _ = vdf;
Err(ParseError::Syntax { at: 0 })
}
/// The game described by `appmanifest_<id>.acf` inside `library` (the folder holding `steamapps`). The install
/// folder is `<library>\steamapps\common\<installdir>`, where `installdir` must be one plain folder name.
/// Steam's own redistributables and runtimes ([`is_tool`]) give [`ParseError::NotAGame`].
pub fn app_manifest(acf: &[u8], library: &WinPath) -> Result<Game, ParseError> {
let _ = (acf, library);
Err(ParseError::Syntax { at: 0 })
}
/// The app id in a file name `appmanifest_<id>.acf` (exact, lowercase, canonical id), for filtering a folder
/// listing; `None` for any other name.
pub fn app_id_from_manifest_name(name: &str) -> Option<u32> {
let _ = name;
None
}
/// Steam apps that are not games: the common redistributables and the Linux runtimes.
pub fn is_tool(app_id: u32) -> bool {
let _ = app_id;
false
}
+30
View File
@@ -0,0 +1,30 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Small shared helpers: title checks, a stable hash, the lettered cover.
use crate::error::ParseError;
use crate::id::GameId;
use crate::model::CoverHint;
/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control characters.
pub(crate) fn title(s: &str, field: &'static str) -> Result<String, ParseError> {
let _ = s;
Err(ParseError::Missing(field))
}
/// FNV-1a, 64 bit: stable across builds and platforms (unlike `std`'s hasher).
pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub(crate) fn lettered(title: &str, id: &GameId) -> CoverHint {
let _ = (title, id);
CoverHint::Lettered { letter: '#', hue: 0 }
}
+92
View File
@@ -0,0 +1,92 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! A strict tokenizer, parser and writer for Valve's KeyValues text format (VDF), as used by Steam's
//! `libraryfolders.vdf` and `appmanifest_<id>.acf`.
//!
//! Accepted: quoted strings with the escapes `\\`, `\"`, `\n`, `\t` and `\r`; `{` and `}`; whitespace (space, tab,
//! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: unquoted
//! tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control characters or line breaks inside
//! a string, NUL anywhere, empty keys, a key repeated on the same level (ignoring ASCII case), and anything over the
//! caps in [`crate::limits`].
use crate::error::ParseError;
/// One token and the byte offset where it starts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
pub kind: TokenKind,
pub at: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenKind {
/// `{`
Open,
/// `}`
Close,
/// A quoted string, unescaped.
Str(String),
}
/// A value: a string or a nested object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
Str(String),
Obj(Obj),
}
/// An ordered list of key/value pairs with unique keys (ignoring ASCII case).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Obj {
entries: Vec<(String, Value)>,
}
impl Obj {
pub fn new() -> Obj {
Obj::default()
}
/// Appends a pair. Refuses an empty key, a key or value over its cap, and a key already present.
pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> {
let _ = (key, value);
Err(ParseError::Missing("key"))
}
/// The value under `key`, ignoring ASCII case.
pub fn get(&self, key: &str) -> Option<&Value> {
self.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v)
}
/// The pairs in file order.
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
self.entries.iter().map(|(k, v)| (k.as_str(), v))
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
/// Splits `input` into tokens. Checks size, UTF-8, escapes and string lengths; not nesting.
pub fn tokenize(input: &[u8]) -> Result<Vec<Token>, ParseError> {
let _ = input;
Err(ParseError::Syntax { at: 0 })
}
/// Parses a whole document: a sequence of top-level pairs.
pub fn parse(input: &[u8]) -> Result<Obj, ParseError> {
let _ = input;
Err(ParseError::Syntax { at: 0 })
}
/// Writes a document in Valve's layout (tabs, one pair per line). [`parse`] of the result gives `doc` back.
pub fn write(doc: &Obj) -> String {
let _ = doc;
String::new()
}