Skip to main content

twbm_idmap/
lib.rs

1// SPDX-FileCopyrightText: 2026 Manuel Quarneti <mq1@ik.me>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4#![warn(clippy::all, rust_2018_idioms)]
5
6include!(concat!(env!("OUT_DIR"), "/id_map_meta.rs"));
7
8#[repr(C)]
9struct Data {
10    pub game_ids: [u32; COUNT],
11    #[cfg(feature = "gamehacking")]
12    pub ghids: [Option<std::num::NonZero<u32>>; COUNT],
13    pub title_offsets: [u32; COUNT + 1],
14    pub titles: [u8; TITLES_LEN],
15}
16
17#[cfg(not(feature = "compress"))]
18static DATA: Data = {
19    let bytes = *include_bytes!(concat!(env!("OUT_DIR"), "/id_map.bin"));
20    unsafe { std::mem::transmute(bytes) }
21};
22
23#[cfg(feature = "compress")]
24static DATA: std::sync::LazyLock<Box<Data>> = std::sync::LazyLock::new(|| {
25    let compressed = include_bytes!(concat!(env!("OUT_DIR"), "/id_map.bin"));
26
27    let mut buf = Box::<Data>::new_uninit();
28
29    // inflate
30    let ptr = buf.as_mut_ptr().cast::<u8>();
31    let slice = unsafe { std::slice::from_raw_parts_mut(ptr, std::mem::size_of::<Data>()) };
32    let it = std::iter::once(compressed.as_slice());
33    miniz_oxide::inflate::decompress_slice_iter_to_slice(slice, it, false, true).unwrap();
34
35    unsafe { buf.assume_init() }
36});
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[repr(transparent)]
40pub struct GameEntry(usize);
41
42impl GameEntry {
43    #[inline]
44    pub fn lookup(id: impl AsRef<str>) -> Option<Self> {
45        let id = u32::from_str_radix(id.as_ref(), 36).ok()?;
46        DATA.game_ids.binary_search(&id).ok().map(Self)
47    }
48
49    #[cfg(feature = "gamehacking")]
50    #[inline]
51    pub fn ghid(&self) -> Option<std::num::NonZero<u32>> {
52        unsafe { *DATA.ghids.get_unchecked(self.0) }
53    }
54
55    #[inline]
56    pub fn title(&self) -> &'static str {
57        let start = unsafe { *DATA.title_offsets.get_unchecked(self.0) } as usize;
58        let end = unsafe { *DATA.title_offsets.get_unchecked(self.0 + 1) } as usize;
59        let slice = unsafe { DATA.titles.get_unchecked(start..end) };
60
61        unsafe { std::str::from_utf8_unchecked(slice) }
62    }
63}