rosu-mods 0.4.1

Library for osu! mods
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use std::{
    collections::HashMap,
    fmt::{Debug, Formatter, Result as FmtResult},
};

use crate::{Acronym, GameModIntermode};

/// A simplified version of [`GameMod`].
///
/// [`GameMod`]: crate::GameMod
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[derive(Clone, Debug, PartialEq)]
pub struct GameModSimple {
    pub acronym: Acronym,
    #[cfg_attr(feature = "serde", serde(default))]
    pub settings: HashMap<Box<str>, SettingSimple>,
}

impl GameModSimple {
    /// Convert a [`GameModSimple`] to a [`GameModIntermode`].
    pub fn as_intermode(&self) -> GameModIntermode {
        GameModIntermode::from_acronym(self.acronym)
    }

    /// Convert a [`GameModSimple`] into a [`GameMod`].
    ///
    /// The `seed` controls which [`GameMode`] to target and whether unknown
    /// fields are rejected:
    ///
    /// - [`GameModSeed::Mode`] targets a specific mode.
    /// - [`GameModSeed::GuessMode`] tries each mode in turn and picks the
    ///   first one whose settings all match.
    ///
    /// Returns `Ok(GameMod::Unknown*(..))` if the acronym is not valid for the
    /// resolved mode — that is a legitimate, expected outcome rather than an
    /// error.
    ///
    /// Returns `Err` only when the settings themselves are malformed: a value
    /// has the wrong type for its field, or — when `deny_unknown_fields` is
    /// `true` in the seed — a key is not recognised by the target mod.
    ///
    /// [`GameMode`]: crate::GameMode
    /// [`GameMod`]: crate::GameMod
    /// [`GameModSeed::Mode`]: crate::serde::GameModSeed::Mode
    /// [`GameModSeed::GuessMode`]: crate::serde::GameModSeed::GuessMode
    #[cfg(feature = "serde")]
    #[cfg_attr(all(docsrs, not(doctest)), doc(cfg(feature = "serde")))]
    pub fn try_as_mod(
        self,
        seed: crate::serde::GameModSeed,
    ) -> Result<crate::GameMod, GameModSimpleConversionError> {
        use serde::de::DeserializeSeed;

        use crate::serde::GameModSettings;

        let settings = GameModSettings::from_simple_settings(&self.settings);

        // Drive GameModSeed::visit_map by presenting a two-entry map:
        //   { "acronym": <str>, "settings": <fields> }
        let d = simple_deserializer::SimpleMapDeserializer::new(self.acronym.as_str(), &settings);

        seed.deserialize(d)
            .map_err(|e| GameModSimpleConversionError {
                msg: e.to_string().into_boxed_str(),
            })
    }
}

/// Error returned by [`GameModSimple::try_as_mod`].
///
/// This is produced when the settings stored in a [`GameModSimple`] are
/// incompatible with the target [`GameMod`] variant — for example when a
/// value has the wrong type for its field, or when an unrecognised field key
/// is encountered and `deny_unknown_fields` is `true`.
///
/// An *unknown acronym* is **not** an error; [`GameModSimple::try_as_mod`]
/// returns `Ok(GameMod::Unknown*(..))` in that case.
///
/// [`GameMod`]: crate::GameMod
#[cfg(feature = "serde")]
#[cfg_attr(all(docsrs, not(doctest)), doc(cfg(feature = "serde")))]
#[derive(Debug)]
pub struct GameModSimpleConversionError {
    msg: Box<str>,
}

/// A setting value for [`GameModSimple`].
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[derive(Clone, PartialEq)]
pub enum SettingSimple {
    Bool(bool),
    Number(f64),
    String(String),
}

impl Debug for SettingSimple {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            SettingSimple::Bool(value) => Debug::fmt(value, f),
            SettingSimple::Number(value) => Debug::fmt(value, f),
            SettingSimple::String(value) => Debug::fmt(value, f),
        }
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(all(docsrs, not(doctest)), doc(cfg(feature = "serde")))]
const _: () = {
    use std::{error::Error, fmt::Display};

    use serde::de::{Deserialize, Deserializer};

    use crate::serde::Value;

    impl<'de> Deserialize<'de> for SettingSimple {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            match Value::deserialize(d)? {
                Value::Bool(value) => Ok(Self::Bool(value)),
                Value::Str(value) => Ok(Self::String(value.into_owned())),
                Value::Number(value) => Ok(Self::Number(value)),
            }
        }
    }

    impl Display for GameModSimpleConversionError {
        fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
            f.write_str(&self.msg)
        }
    }

    impl Error for GameModSimpleConversionError {}
};

#[cfg(feature = "serde")]
mod simple_deserializer {
    use serde::{
        de::{value::BorrowedStrDeserializer, DeserializeSeed, Error, MapAccess, Visitor},
        Deserializer,
    };

    use crate::serde::{GameModDeserializeError, GameModSettings};

    // -------------------------------------------------------------------------
    // SimpleMapDeserializer
    //
    // Presents a two-entry map  { "acronym": <str>, "settings": <fields> }
    // to GameModSeed::visit_map, which expects exactly that shape. This lets
    // us fully reuse GameModSeed's dispatch logic — including the GuessMode
    // path that tries every mode — without duplicating any of it.
    // -------------------------------------------------------------------------

    pub(super) struct SimpleMapDeserializer<'a> {
        acronym: &'a str,
        settings: &'a GameModSettings<'a>,
    }

    impl<'a> SimpleMapDeserializer<'a> {
        pub(super) const fn new(acronym: &'a str, settings: &'a GameModSettings<'a>) -> Self {
            Self { acronym, settings }
        }
    }

    impl<'de, 'a: 'de> Deserializer<'de> for SimpleMapDeserializer<'a> {
        type Error = GameModDeserializeError;

        fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
            self.deserialize_map(visitor)
        }

        fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
            visitor.visit_map(SimpleMapAccess::new(self.acronym, self.settings))
        }

        serde::forward_to_deserialize_any! {
            bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
            byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct
            struct enum identifier ignored_any
        }
    }

    // State machine driving the two-entry map:
    //   key1 → value1 → key2 → value2 → done.
    enum MapState {
        AcronymKey,
        AcronymValue,
        SettingsKey,
        SettingsValue,
        Done,
    }

    struct SimpleMapAccess<'a> {
        acronym: &'a str,
        settings: &'a GameModSettings<'a>,
        state: MapState,
    }

    impl<'a> SimpleMapAccess<'a> {
        const fn new(acronym: &'a str, settings: &'a GameModSettings<'a>) -> Self {
            Self {
                acronym,
                settings,
                state: MapState::AcronymKey,
            }
        }
    }

    impl<'de, 'a: 'de> MapAccess<'de> for SimpleMapAccess<'a> {
        type Error = GameModDeserializeError;

        fn next_key_seed<K: DeserializeSeed<'de>>(
            &mut self,
            seed: K,
        ) -> Result<Option<K::Value>, Self::Error> {
            match self.state {
                MapState::AcronymKey => {
                    self.state = MapState::AcronymValue;
                    let d = BorrowedStrDeserializer::new("acronym");

                    seed.deserialize(d).map(Some)
                }
                MapState::SettingsKey => {
                    self.state = MapState::SettingsValue;
                    let d = BorrowedStrDeserializer::new("settings");

                    seed.deserialize(d).map(Some)
                }
                _ => Ok(None),
            }
        }

        fn next_value_seed<V: DeserializeSeed<'de>>(
            &mut self,
            seed: V,
        ) -> Result<V::Value, Self::Error> {
            match self.state {
                MapState::AcronymValue => {
                    self.state = MapState::SettingsKey;
                    let d = BorrowedStrDeserializer::<GameModDeserializeError>::new(self.acronym);

                    seed.deserialize(d)
                }
                MapState::SettingsValue => {
                    self.state = MapState::Done;

                    // GameModSettings<'a> implements Deserializer, so
                    // feeding it to the seed drives the per-mod field visitor.
                    seed.deserialize(self.settings)
                }
                _ => Err(GameModDeserializeError::custom(
                    "next_value called out of sequence",
                )),
            }
        }

        fn size_hint(&self) -> Option<usize> {
            Some(2)
        }
    }
}

#[cfg(test)]
mod tests {
    mod common {
        #![allow(unused, reason = "depends on enabled features")]

        pub(super) use crate::{GameMod, GameMode};

        pub(super) use super::super::*;

        pub(super) const JSON: &str = r#"[
            {
                "acronym":"DA",
                "settings":{
                    "scroll_speed":2
                }
            },
            {
                "acronym":"CS"
            }
        ]"#;
    }

    #[allow(unused, reason = "depends on enabled features")]
    use common::*;

    #[test]
    #[cfg(feature = "serde")]
    fn roundtrip_serde() {
        let mods: Vec<GameModSimple> = serde_json::from_str(JSON).unwrap();

        let expected = vec![
            GameModSimple {
                acronym: "DA".parse().unwrap(),
                settings: vec![("scroll_speed".into(), SettingSimple::Number(2.0))]
                    .into_iter()
                    .collect(),
            },
            GameModSimple {
                acronym: "CS".parse().unwrap(),
                settings: HashMap::new(),
            },
        ];

        assert_eq!(mods, expected);

        let serialized = serde_json::to_string(&mods).unwrap();
        let deserialized: Vec<GameModSimple> = serde_json::from_str(&serialized).unwrap();

        assert_eq!(mods, deserialized);
    }

    /// Converting a mod whose acronym is valid for the given mode, with a
    /// correctly typed setting that exists on that variant.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_known_with_setting() {
        use crate::{generated_mods::DifficultyAdjustTaiko, serde::GameModSeed};

        let simple = GameModSimple {
            acronym: "DA".parse().unwrap(),
            settings: [("scroll_speed".into(), SettingSimple::Number(2.0))]
                .into_iter()
                .collect(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Taiko,
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::DifficultyAdjustTaiko(DifficultyAdjustTaiko {
                scroll_speed: Some(2.0),
                ..Default::default()
            })
        );
    }

    /// Multiple settings are all forwarded correctly.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_multiple_settings() {
        use crate::serde::GameModSeed;

        let simple = GameModSimple {
            acronym: "DA".parse().unwrap(),
            settings: [
                ("approach_rate".into(), SettingSimple::Number(9.5)),
                ("circle_size".into(), SettingSimple::Number(4.0)),
            ]
            .into_iter()
            .collect(),
        };

        let GameMod::DifficultyAdjustOsu(da) = simple
            .try_as_mod(GameModSeed::Mode {
                mode: GameMode::Osu,
                deny_unknown_fields: true,
            })
            .unwrap()
        else {
            panic!("expected DifficultyAdjustOsu");
        };

        assert_eq!(da.approach_rate, Some(9.5));
        assert_eq!(da.circle_size, Some(4.0));
    }

    /// A mod with an empty settings map converts to its default variant.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_no_settings() {
        use crate::serde::GameModSeed;

        let simple = GameModSimple {
            acronym: "CS".parse().unwrap(),
            settings: HashMap::new(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Taiko,
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::ConstantSpeedTaiko(Default::default())
        );
    }

    /// An acronym that does not exist for the given mode produces the
    /// appropriate `Unknown*` variant — this is `Ok`, not `Err`.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_unknown_acronym_is_ok() {
        use crate::{generated_mods::UnknownMod, serde::GameModSeed};

        let simple = GameModSimple {
            acronym: "XX".parse().unwrap(),
            settings: HashMap::new(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Osu,
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::UnknownOsu(UnknownMod {
                acronym: "XX".parse().unwrap()
            })
        );
    }

    /// A mode-specific acronym produces `Unknown*` when a different mode is
    /// requested — also `Ok`.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_wrong_mode_is_ok_unknown() {
        use crate::{generated_mods::UnknownMod, serde::GameModSeed};

        // "FI" (FadeIn) only exists for Mania.
        let simple = GameModSimple {
            acronym: "FI".parse().unwrap(),
            settings: HashMap::new(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Osu,
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::UnknownOsu(UnknownMod {
                acronym: "FI".parse().unwrap()
            })
        );
    }

    /// GuessMode picks the correct mode-specific variant automatically.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_guess_mode_picks_correct_variant() {
        use crate::{generated_mods::FadeInMania, serde::GameModSeed};

        // "FI" only exists for Mania; GuessMode should find it.
        let simple = GameModSimple {
            acronym: "FI".parse().unwrap(),
            settings: HashMap::new(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::GuessMode {
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::FadeInMania(FadeInMania::default())
        );
    }

    /// GuessMode with a setting that only matches one mode's variant selects
    /// that mode even when the acronym exists across multiple modes.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_guess_mode_uses_settings_to_disambiguate() {
        use crate::{generated_mods::DifficultyAdjustTaiko, serde::GameModSeed};

        // "DA" exists for every mode, but `scroll_speed` is only a field on
        // the Taiko variant — GuessMode with deny_unknown_fields should pick it.
        let simple = GameModSimple {
            acronym: "DA".parse().unwrap(),
            settings: [("scroll_speed".into(), SettingSimple::Number(1.5))]
                .into_iter()
                .collect(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::GuessMode {
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::DifficultyAdjustTaiko(DifficultyAdjustTaiko {
                scroll_speed: Some(1.5),
                ..Default::default()
            })
        );
    }

    /// An unrecognised field key with `deny_unknown_fields: true` is an error.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_unknown_field_denied_is_err() {
        use crate::serde::GameModSeed;

        let simple = GameModSimple {
            acronym: "CS".parse().unwrap(),
            settings: [("not_a_real_field".into(), SettingSimple::Bool(true))]
                .into_iter()
                .collect(),
        };

        assert!(simple
            .try_as_mod(GameModSeed::Mode {
                mode: GameMode::Taiko,
                deny_unknown_fields: true
            })
            .is_err());
    }

    /// The same unrecognised field is silently ignored with
    /// `deny_unknown_fields: false`, producing the default variant.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_unknown_field_allowed_is_ok() {
        use crate::serde::GameModSeed;

        let simple = GameModSimple {
            acronym: "CS".parse().unwrap(),
            settings: [("not_a_real_field".into(), SettingSimple::Bool(true))]
                .into_iter()
                .collect(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Taiko,
                    deny_unknown_fields: false
                })
                .unwrap(),
            GameMod::ConstantSpeedTaiko(Default::default())
        );
    }

    /// A setting value with the wrong type for its field (a bool where a
    /// number is expected) is an error regardless of `deny_unknown_fields`.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_wrong_value_type_is_err() {
        use crate::serde::GameModSeed;

        // `scroll_speed` on DifficultyAdjustTaiko expects an f64, not a bool.
        let simple = GameModSimple {
            acronym: "DA".parse().unwrap(),
            settings: [("scroll_speed".into(), SettingSimple::Bool(true))]
                .into_iter()
                .collect(),
        };

        assert!(simple
            .clone()
            .try_as_mod(GameModSeed::Mode {
                mode: GameMode::Taiko,
                deny_unknown_fields: false
            })
            .is_err());
        assert!(simple
            .try_as_mod(GameModSeed::Mode {
                mode: GameMode::Taiko,
                deny_unknown_fields: true
            })
            .is_err());
    }

    /// String settings are forwarded correctly.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_string_setting() {
        use crate::serde::GameModSeed;

        let simple = GameModSimple {
            acronym: "AC".parse().unwrap(),
            settings: [(
                "accuracy_judge_mode".into(),
                SettingSimple::String("standard_all".into()),
            )]
            .into_iter()
            .collect(),
        };

        let GameMod::AccuracyChallengeOsu(ac) = simple
            .try_as_mod(GameModSeed::Mode {
                mode: GameMode::Osu,
                deny_unknown_fields: true,
            })
            .unwrap()
        else {
            panic!("expected AccuracyChallengeOsu");
        };

        assert_eq!(ac.accuracy_judge_mode.as_deref(), Some("standard_all"));
    }

    /// Bool settings are forwarded correctly.
    #[test]
    #[cfg(feature = "serde")]
    fn try_as_mod_bool_setting() {
        use crate::{generated_mods::SuddenDeathOsu, serde::GameModSeed};

        let simple = GameModSimple {
            acronym: "SD".parse().unwrap(),
            settings: [("restart".into(), SettingSimple::Bool(true))]
                .into_iter()
                .collect(),
        };

        assert_eq!(
            simple
                .try_as_mod(GameModSeed::Mode {
                    mode: GameMode::Osu,
                    deny_unknown_fields: true
                })
                .unwrap(),
            GameMod::SuddenDeathOsu(SuddenDeathOsu {
                restart: Some(true),
                ..Default::default()
            })
        );
    }

    #[test]
    #[cfg(feature = "rkyv")]
    fn roundtrip_rkyv() {
        use rkyv::{
            rancor::{BoxedError as Err, Strategy},
            Archived, Deserialize,
        };

        let mods: Vec<GameModSimple> = serde_json::from_str(JSON).unwrap();

        let bytes = rkyv::to_bytes::<Err>(&mods).unwrap();
        let archived = rkyv::access::<Archived<Vec<GameModSimple>>, Err>(&bytes).unwrap();
        let deserialized: Vec<GameModSimple> = archived
            .deserialize(Strategy::<_, Err>::wrap(&mut ()))
            .unwrap();

        assert_eq!(mods, deserialized);
    }
}