// 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 checks: titles, ids, numbers, a stable hash, the lettered cover. use crate::error::ParseError; use crate::id::GameId; use crate::limits::{MAX_DOMI_ID, MAX_EPIC_APP, MAX_TITLE}; use crate::model::CoverHint; use crate::path::WinPath; /// Bidirectional-override characters, which could make a title display as something else. fn is_bidi_control(c: char) -> bool { matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{200e}' | '\u{200f}' | '\u{061c}') } /// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control or bidi-override characters. pub(crate) fn title(s: &str, field: &'static str) -> Result { let t = s.trim(); if t.is_empty() { return Err(ParseError::Missing(field)); } if t.chars().nth(MAX_TITLE).is_some() { return Err(ParseError::TooLong(field)); } if t.chars().any(|c| c.is_control() || is_bidi_control(c)) { return Err(ParseError::BadValue(field)); } Ok(t.to_owned()) } /// A canonical decimal `u32` other than 0: digits only, no sign, no leading zero, no whitespace. pub(crate) fn canonical_u32(s: &str) -> Option { let b = s.as_bytes(); if b.is_empty() || b.len() > 10 || !b.iter().all(u8::is_ascii_digit) || b.first() == Some(&b'0') { return None; } s.parse::().ok() } /// `[A-Za-z0-9_-]{1,64}`. pub(crate) fn is_epic_app(s: &str) -> bool { (1..=MAX_EPIC_APP).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') } /// Atrium id rules: `[a-z0-9-]{1,32}`, not starting or ending with `-`. pub(crate) fn is_atrium_id(s: &str) -> bool { (1..=MAX_DOMI_ID).contains(&s.len()) && !s.starts_with('-') && !s.ends_with('-') && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } /// True when the last component ends in `.exe` (ignoring case) and has a name before it. pub(crate) fn is_exe(p: &WinPath) -> bool { p.file_name() .is_some_and(|n| n.len() > 4 && n.get(n.len() - 4..).is_some_and(|ext| ext.eq_ignore_ascii_case(".exe"))) } /// 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 letter = title .chars() .find(|c| c.is_alphanumeric()) .map(|c| { let mut up = c.to_uppercase(); match (up.next(), up.next()) { (Some(u), None) => u, _ => c, } }) .unwrap_or('#'); let hue = u16::try_from(fnv1a64(id.as_str().as_bytes()) % 360).unwrap_or(0); CoverHint::Lettered { letter, hue } }