bms-rs 1.0.0

The BMS format parser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Definitions of command argument data.
//!
//! Structures in this module can be used in `Lex` part, `Parse` part, and the output models.

use std::collections::{HashMap, HashSet, VecDeque};

use super::parse::ParseWarning;

pub mod channel;
pub mod graphics;
pub mod mixin;
/// String value wrapper that preserves original string representation.
pub mod string_value;
pub mod time;

// Re-export StringValue for convenience
pub use string_value::StringValue;

/// Minor command types and utilities.
///
/// This module contains types and utilities for minor BMS commands that are only available
/// when the `minor-command` feature is enabled.
pub mod minor_command;

/// A play style of the score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PlayerMode {
    /// For single play, a player uses 5 or 7 keys.
    Single,
    /// For couple play, two players use each 5 or 7 keys.
    Two,
    /// For double play, a player uses 10 or 14 keys.
    Double,
}

impl std::fmt::Display for PlayerMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Single => write!(f, "1"),
            Self::Two => write!(f, "2"),
            Self::Double => write!(f, "3"),
        }
    }
}

impl std::str::FromStr for PlayerMode {
    type Err = ParseWarning;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s {
            "1" => Self::Single,
            "2" => Self::Two,
            "3" => Self::Double,
            _ => {
                return Err(ParseWarning::SyntaxError(
                    "expected one of 0, 1 or 2".into(),
                ));
            }
        })
    }
}

/// A rank to determine judge level, but treatment differs among the BMS players.
///
/// IIDX/LR2/beatoraja judge windows: <https://iidx.org/misc/iidx_lr2_beatoraja_diff>
///
/// Note: The difficulty `VeryEasy` is decided to be unimplemented.
/// See [discussions in the PR](https://github.com/MikuroXina/bms-rs/pull/122).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum JudgeLevel {
    /// Rank 0, the most difficult rank.
    VeryHard,
    /// Rank 1, the harder rank.
    Hard,
    /// Rank 2, the normal rank.
    Normal,
    /// Rank 3, the easier rank.
    Easy,
    /// Other integer value. Please See `JudgeLevel` for more details.
    /// If used for `#EXRANK`, representing percentage.
    OtherInt(i64),
}

impl From<i64> for JudgeLevel {
    fn from(value: i64) -> Self {
        match value {
            0 => Self::VeryHard,
            1 => Self::Hard,
            2 => Self::Normal,
            3 => Self::Easy,
            val => Self::OtherInt(val),
        }
    }
}

impl<'a> TryFrom<&'a str> for JudgeLevel {
    type Error = &'a str;
    fn try_from(value: &'a str) -> core::result::Result<Self, Self::Error> {
        value.parse::<i64>().map(Self::from).map_err(|_| value)
    }
}

impl std::fmt::Display for JudgeLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::VeryHard => write!(f, "0"),
            Self::Hard => write!(f, "1"),
            Self::Normal => write!(f, "2"),
            Self::Easy => write!(f, "3"),
            Self::OtherInt(value) => write!(f, "{value}"),
        }
    }
}

pub(crate) fn char_to_base62(ch: char) -> Option<u8> {
    ch.is_ascii_alphanumeric().then_some(ch as u8)
}

pub(crate) fn base62_to_byte(base62: u8) -> u8 {
    #[allow(clippy::panic)]
    match base62 {
        b'0'..=b'9' => base62 - b'0',
        b'A'..=b'Z' => base62 - b'A' + 10,
        b'a'..=b'z' => base62 - b'a' + 36,
        _ => panic!("invalid base62 byte: {base62}"),
    }
}

/// An object id. Its meaning is determined by the channel belonged to.
///
/// The representation is 2 digits of ASCII characters.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ObjId([u8; 2]);

impl std::fmt::Debug for ObjId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("ObjId")
            .field(&format!("{}{}", self.0[0] as char, self.0[1] as char))
            .finish()
    }
}

impl std::fmt::Display for ObjId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}{}", self.0[0] as char, self.0[1] as char)
    }
}

impl From<ObjId> for u16 {
    fn from(value: ObjId) -> Self {
        base62_to_byte(value.0[0]) as Self * 62 + base62_to_byte(value.0[1]) as Self
    }
}

impl From<ObjId> for u32 {
    fn from(value: ObjId) -> Self {
        Into::<u16>::into(value) as Self
    }
}

impl From<ObjId> for u64 {
    fn from(value: ObjId) -> Self {
        Into::<u16>::into(value) as Self
    }
}

impl ObjId {
    /// Instances a special null id, which means the rest object.
    #[must_use]
    pub const fn null() -> Self {
        Self([b'0', b'0'])
    }

    /// Returns whether the id is `00`.
    #[must_use]
    pub fn is_null(self) -> bool {
        self.0 == [b'0', b'0']
    }

    /// Parses the object id from the string `value`.
    ///
    /// If `case_sensitive_obj_id` is true, then the object id considered as a case-sensitive. Otherwise, it will be all uppercase characters.
    ///
    /// # Errors
    ///
    /// Returns [`ParseWarning::SyntaxError`] if `value` is not exactly two ASCII-alphanumeric characters.
    pub fn try_from(
        value: &str,
        case_sensitive_obj_id: bool,
    ) -> core::result::Result<Self, ParseWarning> {
        if value.len() != 2 {
            return Err(ParseWarning::SyntaxError(format!(
                "expected 2 digits as object id but found: {value}"
            )));
        }
        let mut chars = value.bytes();
        let [Some(ch1), Some(ch2), None] = [chars.next(), chars.next(), chars.next()] else {
            return Err(ParseWarning::SyntaxError(format!(
                "expected 2 digits as object id but found: {value}"
            )));
        };
        if !(ch1.is_ascii_alphanumeric() && ch2.is_ascii_alphanumeric()) {
            return Err(ParseWarning::SyntaxError(format!(
                "expected alphanumeric characters as object id but found: {value}"
            )));
        }
        if case_sensitive_obj_id {
            Ok(Self([ch1, ch2]))
        } else {
            Ok(Self([ch1.to_ascii_uppercase(), ch2.to_ascii_uppercase()]))
        }
    }

    /// Converts the object id into an `u16` value.
    #[must_use]
    pub fn as_u16(self) -> u16 {
        self.into()
    }

    /// Converts the object id into an `u32` value.
    #[must_use]
    pub fn as_u32(self) -> u32 {
        self.into()
    }

    /// Converts the object id into an `u64` value.
    #[must_use]
    pub fn as_u64(self) -> u64 {
        self.into()
    }

    /// Converts the object id into 2 `char`s.
    #[must_use]
    pub fn into_chars(self) -> [char; 2] {
        self.0.map(|c| c as char)
    }

    /// Makes the object id uppercase.
    pub const fn make_uppercase(&mut self) {
        self.0[0] = self.0[0].to_ascii_uppercase();
        self.0[1] = self.0[1].to_ascii_uppercase();
    }

    /// Returns whether both characters are valid Base36 characters (0-9, A-Z).
    #[must_use]
    pub fn is_base36(self) -> bool {
        self.0
            .iter()
            .all(|c| c.is_ascii_digit() || c.is_ascii_uppercase())
    }

    /// Returns whether both characters are valid Base62 characters (0-9, A-Z, a-z).
    #[must_use]
    pub fn is_base62(self) -> bool {
        self.0
            .iter()
            .all(|c| c.is_ascii_digit() || c.is_ascii_uppercase() || c.is_ascii_lowercase())
    }

    /// Returns an iterator over all possible `ObjId` values, ordered by priority:
    /// first all Base36 values (0-9, A-Z), then remaining Base62 values.
    ///
    /// Total: 3843 values (excluding null "00"), with first 1295 being Base36.
    pub fn all_values() -> impl Iterator<Item = Self> {
        const BASE36_CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const BASE62_CHARS: &[u8] =
            b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        // Generate all Base36 values first (1296 values: "00" to "ZZ")
        let base36_values = BASE36_CHARS.iter().copied().flat_map(|first| {
            BASE36_CHARS
                .iter()
                .copied()
                .map(move |second| Self([first, second]))
        });

        // Generate all Base62 values, then filter out Base36 ones and "00"
        let remaining_values = BASE62_CHARS.iter().copied().flat_map(|first| {
            BASE62_CHARS
                .iter()
                .copied()
                .map(move |second| Self([first, second]))
                .filter(move |obj_id| {
                    // Skip "00" and Base36 values (already yielded above)
                    !obj_id.is_null() && !obj_id.is_base36() && obj_id.is_base62()
                })
        });

        // Chain them: first Base36 (1296 values), then remaining (2548 values)
        // Total: 1296 + 2548 = 3844 values
        // Skip the first Base36 value ("00") to get 1295 Base36 + 2548 remaining = 3843 total
        base36_values.skip(1).chain(remaining_values)
    }
}

/// A play volume of the sound in the score. Defaults to 100.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Volume {
    /// A play volume percentage of the sound.
    pub relative_percent: u8,
}

impl Default for Volume {
    fn default() -> Self {
        Self {
            relative_percent: 100,
        }
    }
}

/// A POOR BGA display mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PoorMode {
    /// To hide the normal BGA and display the POOR BGA.
    #[default]
    Interrupt,
    /// To overlap the POOR BGA onto the normal BGA.
    Overlay,
    /// Not to display the POOR BGA.
    Hidden,
}

impl std::str::FromStr for PoorMode {
    type Err = ParseWarning;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(match s {
            "0" => Self::Interrupt,
            "1" => Self::Overlay,
            "2" => Self::Hidden,
            _ => {
                return Err(ParseWarning::SyntaxError(
                    "expected one of 0, 1 or 2".into(),
                ));
            }
        })
    }
}

impl PoorMode {
    /// Converts an display type of Poor BGA into the corresponding string literal.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Interrupt => "0",
            Self::Overlay => "1",
            Self::Hidden => "2",
        }
    }
}

/// A notation type about LN in the score. But you don't have to take care of how the notes are actually placed in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LnType {
    /// The RDM type.
    #[default]
    Rdm,
    /// The MGQ type.
    Mgq,
}

/// Long Note Mode Type
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum LnMode {
    /// Normal Long Note, no tail judge (LN)
    #[default]
    Ln = 1,
    /// IIDX Classic Long Note, with tail judge (CN)
    Cn = 2,
    /// IIDX Hell Long Note, with tail judge. holding add gurge, un-holding lose gurge (HCN)
    Hcn = 3,
}

impl From<LnMode> for u8 {
    fn from(mode: LnMode) -> Self {
        match mode {
            LnMode::Ln => 1,
            LnMode::Cn => 2,
            LnMode::Hcn => 3,
        }
    }
}

impl TryFrom<u8> for LnMode {
    type Error = u8;
    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
        Ok(match value {
            1 => Self::Ln,
            2 => Self::Cn,
            3 => Self::Hcn,
            _ => return Err(value),
        })
    }
}

/// Associates between object `K` and [`ObjId`] with memoization.
/// It is useful to assign object ids for many objects with its equality.
pub struct ObjIdManager<'a, K: ?Sized> {
    value_to_id: HashMap<&'a K, ObjId>,
    used_ids: HashSet<ObjId>,
    unused_ids: VecDeque<ObjId>,
}

impl<K> Default for ObjIdManager<'_, K>
where
    K: std::hash::Hash + Eq + ?Sized,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, K> ObjIdManager<'a, K>
where
    K: std::hash::Hash + Eq + ?Sized,
{
    /// Creates a new empty `ObjIdManager`.
    #[must_use]
    pub fn new() -> Self {
        let unused_ids: VecDeque<ObjId> = ObjId::all_values().collect();

        Self {
            value_to_id: HashMap::new(),
            used_ids: HashSet::new(),
            unused_ids,
        }
    }

    /// Creates a new `ObjIdManager` with iterator of assigned entries.
    pub fn from_entries<I: IntoIterator<Item = (&'a K, ObjId)>>(iter: I) -> Self {
        let mut value_to_id: HashMap<&'a K, ObjId> = HashMap::new();
        let mut used_ids: HashSet<ObjId> = HashSet::new();

        // Collect all entries first
        let entries: Vec<_> = iter.into_iter().collect();

        // Mark used IDs and build the mapping
        for (key, assigned_id) in entries {
            value_to_id.insert(key, assigned_id);
            used_ids.insert(assigned_id);
        }

        let unused_ids: VecDeque<ObjId> = ObjId::all_values()
            .filter(|id| !used_ids.contains(id))
            .collect();

        Self {
            value_to_id,
            used_ids,
            unused_ids,
        }
    }

    /// Returns whether the key is already assigned any id.
    pub fn is_assigned(&self, key: &'a K) -> bool {
        self.value_to_id.contains_key(key)
    }

    /// Gets or allocates an `ObjId` for a key without creating tokens.
    pub fn get_or_new_id(&mut self, key: &'a K) -> Option<ObjId> {
        if let Some(&id) = self.value_to_id.get(key) {
            return Some(id);
        }

        let new_id = self.unused_ids.pop_front()?;
        self.used_ids.insert(new_id);
        self.value_to_id.insert(key, new_id);
        Some(new_id)
    }

    /// Get assigned ids as an iterator.
    pub fn into_assigned_ids(self) -> impl Iterator<Item = ObjId> {
        self.used_ids.into_iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_base62() {
        assert_eq!(char_to_base62('/'), None);
        assert_eq!(char_to_base62('0'), Some(b'0'));
        assert_eq!(char_to_base62('9'), Some(b'9'));
        assert_eq!(char_to_base62(':'), None);
        assert_eq!(char_to_base62('@'), None);
        assert_eq!(char_to_base62('A'), Some(b'A'));
        assert_eq!(char_to_base62('Z'), Some(b'Z'));
        assert_eq!(char_to_base62('['), None);
        assert_eq!(char_to_base62('`'), None);
        assert_eq!(char_to_base62('a'), Some(b'a'));
        assert_eq!(char_to_base62('z'), Some(b'z'));
        assert_eq!(char_to_base62('{'), None);
    }

    #[test]
    fn test_all_values() {
        let all_values: Vec<ObjId> = ObjId::all_values().collect();

        // Should have exactly 3843 values
        assert_eq!(all_values.len(), 3843);

        // First 1295 values should be Base36 (0-9, A-Z)
        for (i, obj_id) in all_values.iter().enumerate() {
            if i < 1295 {
                assert!(
                    obj_id.is_base36(),
                    "Value at index {i} should be Base36: {obj_id:?}"
                );
            } else {
                assert!(
                    !obj_id.is_base36(),
                    "Value at index {i} should NOT be Base36: {obj_id:?}"
                );
            }
        }

        // Verify some specific values
        let Some(first) = all_values.first().copied() else {
            panic!("expected ObjId::all_values() to be non-empty");
        };
        assert_eq!(first, ObjId::try_from("01", false).unwrap()); // First Base36 value
        let Some(last_base36) = all_values.get(1294).copied() else {
            panic!("expected ObjId::all_values() to contain Base36 values");
        };
        assert_eq!(last_base36, ObjId::try_from("ZZ", false).unwrap()); // Last Base36 value

        // Verify that "00" is not included
        assert!(!all_values.contains(&ObjId::null()));

        // Verify that all values are unique
        let mut unique_values = std::collections::HashSet::new();
        for value in &all_values {
            assert!(
                unique_values.insert(*value),
                "Duplicate value found: {value:?}"
            );
        }
    }
}