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
use std::{
    error::Error,
    fs::File,
    io,
    io::{BufRead, BufReader, Cursor},
    ops::ControlFlow,
    path::Path,
};

use crate::{format_version, reader::Decoder, section::Section};

/// Parse a type that implements [`DecodeBeatmap`] by providing a path to a
/// `.osu` file.
///
/// # Example
///
/// ```rust,no_run
/// use rosu_map::section::hit_objects::HitObjects;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let path = "/path/to/file.osu";
/// let content: HitObjects = rosu_map::from_path(path)?;
/// # Ok(()) }
/// ```
pub fn from_path<D: DecodeBeatmap>(path: impl AsRef<Path>) -> Result<D, io::Error> {
    File::open(path).map(BufReader::new).and_then(D::decode)
}

/// Parse a type that implements [`DecodeBeatmap`] by providing the content of
/// a `.osu` file as a slice of bytes.
///
/// # Example
///
/// ```rust
/// use rosu_map::section::metadata::Metadata;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let bytes: &[u8] = b"[General]
/// Mode: 2
///
/// [Metadata]
/// Creator: pishifat";
///
/// let metadata: Metadata = rosu_map::from_bytes(bytes)?;
/// assert_eq!(metadata.creator, "pishifat");
/// # Ok(()) }
/// ```
pub fn from_bytes<D: DecodeBeatmap>(bytes: &[u8]) -> Result<D, io::Error> {
    D::decode(Cursor::new(bytes))
}

/// Parse a type that implements [`DecodeBeatmap`] by providing the content of
/// a `.osu` file as a string.
///
/// # Example
///
/// ```rust
/// use rosu_map::section::difficulty::Difficulty;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let s: &str = "[Difficulty]
/// SliderMultiplier: 3
///
/// [Editor]
/// BeatDivisor: 4";
///
/// let difficulty: Difficulty = rosu_map::from_str(s)?;
/// assert_eq!(difficulty.slider_multiplier, 3.0);
/// # Ok(()) }
/// ```
pub fn from_str<D: DecodeBeatmap>(s: &str) -> Result<D, io::Error> {
    D::decode(Cursor::new(s))
}

/// Intermediate state while parsing via [`DecodeBeatmap`].
pub trait DecodeState: Sized {
    /// Given the format version, create an instance.
    ///
    /// If the version is not of interest, this is basically
    /// `Default::default()`.
    fn create(version: i32) -> Self;
}

/// Trait to handle reading and parsing content of `.osu` files.
///
/// Generally, the only way to interact with this trait should be calling the
/// [`decode`] method.
///
/// Each section has its own `parse_[section]` method in which, given the next
/// line, the state should be updated. Note that the given lines will be
/// non-empty but comments (text starting with `//`) are **not trimmed**.
///
/// # Example
///
/// [`DecodeBeatmap`] is implemented for structs like [`HitObjects`] or
/// [`Beatmap`] so it can be used out the box.
///
/// ```
/// use std::io::Cursor;
/// use rosu_map::{Beatmap, DecodeBeatmap};
/// use rosu_map::section::general::GameMode;
/// use rosu_map::section::hit_objects::HitObjects;
///
/// let content: &str = "osu file format v14
///
/// [General]
/// Mode: 1 // Some comment
///
/// [Metadata]
/// Title: Some song title";
///
/// // Converting &str to &[u8] so that io::BufRead is satisfied
/// let mut reader = content.as_bytes();
/// let decoded = HitObjects::decode(&mut reader).unwrap();
/// assert_eq!(decoded.mode, GameMode::Taiko);
/// assert!(decoded.hit_objects.is_empty());
///
/// let mut reader = content.as_bytes();
/// let decoded = Beatmap::decode(&mut reader).unwrap();
/// assert_eq!(decoded.mode, GameMode::Taiko);
/// assert_eq!(decoded.title, "Some song title");
/// ```
///
/// Let's assume only the beatmap title and difficulty attributes are of
/// interest. Using [`Beatmap`] will parse **everything** which will be much
/// slower than implementing this trait on a custom type:
///
/// ```
/// use rosu_map::{DecodeBeatmap, DecodeState};
/// use rosu_map::section::difficulty::{Difficulty, DifficultyState, ParseDifficultyError};
/// use rosu_map::section::metadata::MetadataKey;
/// use rosu_map::util::KeyValue;
///
/// // Our final struct that we want to parse into.
/// struct CustomBeatmap {
///     title: String,
///     ar: f32,
///     cs: f32,
///     hp: f32,
///     od: f32,
/// }
///
/// // The struct that will be built gradually while parsing.
/// struct CustomBeatmapState {
///     title: String,
///     // Built-in way to handle difficulty parsing.
///     difficulty: DifficultyState,
/// }
///
/// // Required to implement for the `DecodeBeatmap` trait.
/// impl DecodeState for CustomBeatmapState {
///     fn create(version: i32) -> Self {
///         Self {
///             title: String::new(),
///             difficulty: DifficultyState::create(version),
///         }
///     }
/// }
///
/// // Also required for the `DecodeBeatmap` trait
/// impl From<CustomBeatmapState> for CustomBeatmap {
///     fn from(state: CustomBeatmapState) -> Self {
///         let difficulty = Difficulty::from(state.difficulty);
///
///         Self {
///             title: state.title,
///             ar: difficulty.approach_rate,
///             cs: difficulty.circle_size,
///             hp: difficulty.hp_drain_rate,
///             od: difficulty.overall_difficulty,
///         }
///     }
/// }
///
/// impl DecodeBeatmap for CustomBeatmap {
///     type State = CustomBeatmapState;
///
///     // In our case, only parsing the difficulty can fail so we can just use
///     // its error type.
///     type Error = ParseDifficultyError;
///
///     fn parse_metadata(state: &mut Self::State, line: &str) -> Result<(), Self::Error> {
///         // Note that comments are *not* trimmed at this point.
///         // To do that, one can use the `rosu_map::util::StrExt` trait and
///         // its `trim_comment` method.
///         let Ok(KeyValue { key, value }) = KeyValue::parse(line) else {
///             // Unknown key, discard line
///             return Ok(());
///         };
///
///         match key {
///             MetadataKey::Title => state.title = value.to_owned(),
///             _ => {}
///         }
///
///         Ok(())
///     }
///
///     fn parse_difficulty(state: &mut Self::State, line: &str) -> Result<(), Self::Error> {
///         // Let `Difficulty` and its state handle the difficulty parsing.
///         Difficulty::parse_difficulty(&mut state.difficulty, line)
///     }
///
///     // None of the other sections are of interest.
///     fn parse_general(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_editor(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_events(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_timing_points(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_colors(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_hit_objects(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_variables(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_catch_the_beat(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
///     fn parse_mania(_state: &mut Self::State, _line: &str) -> Result<(), Self::Error> {
///         Ok(())
///     }
/// }
/// ```
///
/// For more examples, check out how structs like [`TimingPoints`] or
/// [`Beatmap`] implement the [`DecodeBeatmap`] trait.
///
/// [`decode`]: DecodeBeatmap::decode
/// [`Beatmap`]: crate::beatmap::Beatmap
/// [`HitObjects`]: crate::section::hit_objects::HitObjects
/// [`TimingPoints`]: crate::section::timing_points::TimingPoints
pub trait DecodeBeatmap: Sized {
    /// Error type in case something goes wrong while parsing.
    ///
    /// Note that this error is not thrown by the [`decode`] method. Instead,
    /// when a `parse_[section]` method returns such an error, it will be
    /// handled silently. That means, if the `tracing` feature is enabled, the
    /// error and its causes will be logged on the `ERROR` level. If `tracing`
    /// is not enabled, the error will be ignored entirely.
    ///
    /// [`decode`]: DecodeBeatmap::decode
    type Error: Error;

    /// The parsing state which will be updated on each line and turned into
    /// `Self` at the end.
    type State: DecodeState + Into<Self>;

    /// The key method to read and parse content of a `.osu` file into `Self`.
    ///
    /// This method should not be implemented manually.
    fn decode<R: BufRead>(src: R) -> Result<Self, io::Error> {
        let mut reader = Decoder::new(src)?;

        let (version, use_curr_line) = parse_version(&mut reader)?;
        let mut state =
            Self::State::create(version.unwrap_or(format_version::LATEST_FORMAT_VERSION));

        let Some(mut section) = parse_first_section(&mut reader, use_curr_line)? else {
            return Ok(state.into());
        };

        loop {
            let parse_fn = match section {
                Section::General => Self::parse_general,
                Section::Editor => Self::parse_editor,
                Section::Metadata => Self::parse_metadata,
                Section::Difficulty => Self::parse_difficulty,
                Section::Events => Self::parse_events,
                Section::TimingPoints => Self::parse_timing_points,
                Section::Colors => Self::parse_colors,
                Section::HitObjects => Self::parse_hit_objects,
                Section::Variables => Self::parse_variables,
                Section::CatchTheBeat => Self::parse_catch_the_beat,
                Section::Mania => Self::parse_mania,
            };

            match parse_section::<_, Self>(&mut reader, &mut state, parse_fn) {
                Ok(SectionFlow::Continue(next)) => section = next,
                Ok(SectionFlow::Break(())) => break,
                Err(err) => return Err(err),
            }
        }

        Ok(state.into())
    }

    /// Whether a line should *not* be forwarded to the parsing methods.
    fn should_skip_line(line: &str) -> bool {
        line.is_empty() || line.starts_with("//") || line.starts_with(' ') || line.starts_with('_')
    }

    /// Update the state based on a line of the `[General]` section.
    #[allow(unused_variables)]
    fn parse_general(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Editor]` section.
    #[allow(unused_variables)]
    fn parse_editor(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Metadata]` section.
    #[allow(unused_variables)]
    fn parse_metadata(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Difficulty]` section.
    #[allow(unused_variables)]
    fn parse_difficulty(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Events]` section.
    #[allow(unused_variables)]
    fn parse_events(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[TimingPoints]` section.
    #[allow(unused_variables)]
    fn parse_timing_points(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Colours]` section.
    #[allow(unused_variables)]
    fn parse_colors(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[HitObjects]` section.
    #[allow(unused_variables)]
    fn parse_hit_objects(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Variables]` section.
    #[allow(unused_variables)]
    fn parse_variables(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[CatchTheBeat]` section.
    #[allow(unused_variables)]
    fn parse_catch_the_beat(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;

    /// Update the state based on a line of the `[Mania]` section.
    #[allow(unused_variables)]
    fn parse_mania(state: &mut Self::State, line: &str) -> Result<(), Self::Error>;
}

struct UseCurrentLine(bool);

fn parse_version<R>(reader: &mut Decoder<R>) -> Result<(Option<i32>, UseCurrentLine), io::Error>
where
    R: BufRead,
{
    loop {
        let (version, use_curr_line) = match reader.read_line() {
            Ok(Some(line)) => match format_version::try_version_from_line(line) {
                ControlFlow::Continue(()) => continue,
                ControlFlow::Break(Ok(version)) => (Some(version), false),
                // Only used when `tracing` feature is enabled
                #[allow(unused)]
                ControlFlow::Break(Err(err)) => {
                    #[cfg(feature = "tracing")]
                    {
                        tracing::error!("Failed to parse format version: {err}");
                        log_error_cause(&err);
                    }

                    (None, true)
                }
            },
            Ok(None) => (None, false),
            Err(err) => return Err(err),
        };

        return Ok((version, UseCurrentLine(use_curr_line)));
    }
}

fn parse_first_section<R: BufRead>(
    reader: &mut Decoder<R>,
    UseCurrentLine(use_curr_line): UseCurrentLine,
) -> Result<Option<Section>, io::Error> {
    if use_curr_line {
        if let opt @ Some(_) = Section::try_from_line(reader.curr_line()) {
            return Ok(opt);
        }
    }

    loop {
        match reader.read_line() {
            Ok(Some(line)) => {
                if let Some(section) = Section::try_from_line(line) {
                    return Ok(Some(section));
                }
            }
            Ok(None) => return Ok(None),
            Err(err) => return Err(err),
        }
    }
}

type SectionFlow = ControlFlow<(), Section>;

fn parse_section<R, D>(
    reader: &mut Decoder<R>,
    state: &mut D::State,
    f: fn(&mut D::State, &str) -> Result<(), D::Error>,
) -> Result<SectionFlow, io::Error>
where
    R: BufRead,
    D: DecodeBeatmap,
{
    loop {
        match reader.read_line() {
            Ok(Some(line)) => {
                if D::should_skip_line(line) {
                    continue;
                }

                if let Some(next) = Section::try_from_line(line) {
                    return Ok(SectionFlow::Continue(next));
                }

                // Only used when `tracing` feature is enabled
                #[allow(unused)]
                let res = f(state, line);

                #[cfg(feature = "tracing")]
                if let Err(err) = res {
                    tracing::error!("Failed to process line {line:?}: {err}");
                    log_error_cause(&err);
                }
            }
            Ok(None) => return Ok(SectionFlow::Break(())),
            Err(err) => return Err(err),
        }
    }
}

#[cfg(feature = "tracing")]
fn log_error_cause(mut err: &dyn Error) {
    while let Some(src) = err.source() {
        tracing::error!("  - caused by: {src}");
        err = src;
    }
}