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
pub mod parser;

use fmt::Display;
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, fmt};

/// Container for raw image data (assumed to be a valid jpg)
#[derive(Serialize, Deserialize)]
pub struct JPEGData(pub Vec<u8>);

impl fmt::Display for JPEGData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "JPEG({}B)", self.0.len())
    }
}

impl fmt::Debug for JPEGData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// Container for any data extracted from a GBX file.
///
/// See [parse_from_file](parser::parse_from_file) and [parse_from_buffer](parser::parse_from_buffer).
/// Serde is not used internally to Deserialize, but added to enable easier integration of these datatypes in other applications.
#[derive(Debug, Serialize, Deserialize)]
pub struct GBX {
    pub origin: GBXOrigin,
    pub filesize: usize,
    header_start: usize,
    header_length: usize,
    thumbnail_start: Option<usize>,
    thumbnail_length: Option<usize>,
    pub thumbnail: Option<JPEGData>,
    pub header: Option<GBXHeader>,
    pub header_xml: String,
}

impl Display for GBX {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.header {
            Some(h) => write!(
                f,
                "GBX Info Dump (Size={}B)\nFrom file={}\nHeader Infos\n============\n{}",
                self.filesize, self.origin, h
            ),
            None => write!(
                f,
                "GBX Info Dump (Size={}B)\nFrom file={}\nNo header present",
                self.filesize, self.origin
            ),
        }
    }
}

/// Stores the source of the GBX struct.
/// By default a GBX struct will be `Unknown`, the [parser](parser) methods set the
/// `origin` field of the [GBX](GBX) struct accordingly. If you don't want to expose
/// this information about your local filesystem remember to overwrite that field.
#[derive(Debug, Serialize, Deserialize)]
pub enum GBXOrigin {
    File {
        path: String,
    },
    Buffer,
    Unknown,
    /// Added field to allow hiding the origin (library will never use this)
    Hidden,
}

impl Default for GBXOrigin {
    fn default() -> Self {
        GBXOrigin::Unknown
    }
}

impl Display for GBXOrigin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GBXOrigin::File { path } => write!(f, "{}", path),
            GBXOrigin::Buffer => write!(f, "<buffer>"),
            GBXOrigin::Unknown => write!(f, "<unknown>"),
            GBXOrigin::Hidden => write!(f, "<hidden>"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct GBXHeader {
    pub maptype: MapType,
    pub mapversion: MapVersion,
    pub exever: String,
    pub uid: String,
    pub name: String,
    pub author: String,
    pub envir: Environment,
    pub mood: Mood,
    pub desctype: DescType,
    pub nblaps: u32,
    pub price: u32,
    /// Completion times and scores for the challenge, None if none set.
    pub times: Option<Times>,
    pub dependencies: Vec<Dependency>,
}

impl fmt::Display for GBXHeader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let dependency_files: Vec<&String> = self.dependencies.iter().map(|x| &x.file).collect();
        write!(f, "Map is {:?}/{:?} made in {:?}/{}\nUID: {}\nName: {}\nAuthor: {}\nSetting: {:?}/{:?}\nNumber of laps: {}\nPrice: {}\nTimes: {}\nDependencies[{}]: {:?}",
            self.maptype, self.desctype, self.mapversion, self.exever, self.uid, self.name, self.author, self.envir, self.mood, self.nblaps, self.price, self.times.as_ref().map_or(String::from("<not set>"), |x| format!("{}", x)), self.dependencies.len(), dependency_files,
        )
    }
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Times {
    pub bronze: Option<u32>,
    pub silver: Option<u32>,
    pub gold: Option<u32>,
    pub authortime: Option<u32>,
    pub authorscore: Option<u32>,
}

impl fmt::Display for Times {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Bronze: {}, Silver: {}, Gold: {}, Authortime: {}, Authorscore: {}",
            self.bronze
                .map_or(String::from("<not set>"), |x| format!("{}", x)),
            self.silver
                .map_or(String::from("<not set>"), |x| format!("{}", x)),
            self.gold
                .map_or(String::from("<not set>"), |x| format!("{}", x)),
            self.authortime
                .map_or(String::from("<not set>"), |x| format!("{}", x)),
            self.authorscore
                .map_or(String::from("<not set>"), |x| format!("{}", x))
        )
    }
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Dependency {
    pub file: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum MapType {
    Challenge,
}

impl TryFrom<&str> for MapType {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "challenge" => Ok(MapType::Challenge),
            _ => Err(format!("Unknown map type: {}", value)),
        }
    }
}

impl Default for MapType {
    fn default() -> Self {
        MapType::Challenge
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum MapVersion {
    TMc6,
}

impl TryFrom<&str> for MapVersion {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "tmc.6" => Ok(MapVersion::TMc6),
            _ => Err(format!("Unknown map version: {}", value)),
        }
    }
}

impl Default for MapVersion {
    fn default() -> Self {
        MapVersion::TMc6
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum Environment {
    Stadium,
}

impl TryFrom<&str> for Environment {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "stadium" => Ok(Environment::Stadium),
            _ => Err(format!("Unknown environment: {}", value)),
        }
    }
}

impl Default for Environment {
    fn default() -> Self {
        Environment::Stadium
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum Mood {
    Day,
    Sunset,
    Sunrise,
    Night,
}

impl TryFrom<&str> for Mood {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "day" => Ok(Mood::Day),
            "sunset" => Ok(Mood::Sunset),
            "sunrise" => Ok(Mood::Sunrise),
            "night" => Ok(Mood::Night),
            _ => Err(format!("Unknown mood: {}", value)),
        }
    }
}

impl Default for Mood {
    fn default() -> Self {
        Mood::Day
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum DescType {
    Race,
}

impl TryFrom<&str> for DescType {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "race" => Ok(DescType::Race),
            _ => Err(format!("Unknown desc.type: {}", value)),
        }
    }
}

impl Default for DescType {
    fn default() -> Self {
        DescType::Race
    }
}