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
//! DerbyJSON parser, based on serde.


#![feature(custom_attribute)]
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;

use std::collections::HashMap;
use std::io::Read;

mod jamdata;
pub use jamdata::*;
mod teamdata;
pub use teamdata::*;

/// Version of DerbyJSON supported
pub const VERSION: &str = "0.2";


/// The root DerbyJSON object. This can store information about a game, or about
/// a league or a team. Which one it is is determined by the "objecttype" field
/// and determines which fields are valid.
#[derive(Serialize, Deserialize)]
pub struct DerbyJSON {
    pub version: Option<String>,
    pub metadata: serde_json::Map<String, serde_json::Value>,
    #[serde(rename = "type")]
    pub objecttype: ObjectType,
    pub teams: HashMap<String, Team>,
    pub periods: Vec<Period>,
    pub ruleset: Option<Ruleset>,
    pub venue: Option<Venue>,
    #[serde(default)]
    pub uuid: Vec<String>,
    pub notes: Vec<Note>,
    pub date: String,
    pub time: String,
    pub end_time: String,
    pub leagues: Option<Vec<League>>,
    pub timers: Timers,
    pub tournament: Option<String>,
    #[serde(rename = "host-league")]
    pub host_league: Option<String>,
    pub expulsions: Vec<Expulsion>,
    pub suspensions: Vec<String>,
    pub signatures: Vec<serde_json::Value>, // XXX: spec says signature objects
    pub sanctioned: bool,
    pub association: Option<Association>,
}

impl DerbyJSON {
    /// Create an empty DerbyJSON structure corresponding to a game.
    /// It fills in default/empty values for almost everything and
    /// creates two periods.
    pub fn new_game(teams: HashMap<String, Team>) -> DerbyJSON {
        let timers = Timers {
            countdown: None,
            halftime: None,
            jam: None,
            period: Timer {
                duration: 30 * 60,
                counts_down: true,
                running: false,
            }
        };

        DerbyJSON {
            version: Some(VERSION.to_string()),
            objecttype: ObjectType::Game,
            metadata: serde_json::Map::new(),
            ruleset: None,
            venue: None,
            uuid: Vec::new(),
            notes: Vec::new(),
            leagues: None,
            tournament: None,
            host_league: None,
            expulsions: Vec::new(),
            suspensions: Vec::new(),
            signatures: Vec::new(),
            association: None,

            date: String::new(),
            time: String::new(),
            end_time: String::new(),

            sanctioned: false,
            teams: teams,

            periods: vec![Period::default(), Period::default()],
            timers: timers,
        }
    }
}

/// A subset of the general DerbyJSON object, just storing information on
/// team/league rosters.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rosters {
    pub version: Option<String>,
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(rename = "type")]
    pub objecttype: ObjectType,
    pub teams: HashMap<String, Team>,
    #[serde(default)]
    pub uuid: Vec<String>,
    #[serde(default)]
    pub notes: Vec<Note>,
    #[serde(default)]
    pub leagues: Vec<League>,
}

impl Rosters {
    pub fn new(teams: HashMap<String, Team>) -> Rosters {
        Rosters {
            version: Some(VERSION.to_string()),
            metadata: None,
            objecttype: ObjectType::Rosters,
            teams: teams,
            uuid: vec!(),
            notes: vec!(),
            leagues: vec!(),
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum ObjectType { Game, Rosters, Stats, League }

#[derive(Serialize, Deserialize)]
pub struct Expulsion {
    pub skater: String,
    pub suspension: bool,
    pub notes: Vec<Note>,
}

/// Information about the ruleset used for a game.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Ruleset {
    pub version: String,
    pub period_count: u8,
    pub period: String,
    pub jam: String,
    pub lineup: String,
    pub timeout: String,
    pub timeout_count: u8,
    pub official_review_count: u8,
    pub official_review_retained: bool,
    pub official_review_maximum: u8,
    pub penalty: String,
    pub minors: bool,
    pub minors_per_major: u8,
    pub foulout: u8,
}

#[derive(Serialize, Deserialize)]
pub struct Timers {
    pub countdown: Option<Timer>,
    pub period: Timer,
    pub halftime: Option<Timer>,
    pub jam: Option<Timer>,
}

#[derive(Serialize, Deserialize)]
pub struct Timer {
    pub duration: u16,
    pub counts_down: bool,
    pub running: bool,
}

/// A note about something that happened. These notes may be attached to
/// quite a few objects found elsewhere in the spec.
#[derive(Serialize,Deserialize)]
pub struct Note {
    pub note: String,
    pub author: Option<String>,
}

#[derive(Debug)]
pub enum Error {
    Serde(serde_json::Error),
    UnexpectedType(String),
    UnexpectedVersion(String),
}

type SDE = serde_json::Error;
impl From<SDE> for Error {
    fn from(e: serde_json::Error) -> Error {
        Error::Serde(e)
    }
}

/** Load a roster from the given input stream. This specifically checks that 
    the loaded DerbyJSON is a valid roster object. */
pub fn load_roster<R>(reader: R) -> Result<Rosters, Error>
    where R: Read
{
    let obj: Rosters = serde_json::from_reader(reader)?;
    if obj.objecttype != ObjectType::Rosters {
        let t = format!("{:?}", obj.objecttype);
        return Err(Error::UnexpectedType(t));
    }
    if let Some(ref version) = obj.version {
        if version != VERSION {
            return Err(Error::UnexpectedVersion(version.clone()));
        }
    }
    return Ok(obj);
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;
    #[test]
    fn it_works() {
        let text = include_bytes!("rosters.json");
        let reader = Cursor::new(&text[..]);
        let res = super::load_roster(reader);
        println!("{:?}",res.as_ref().err());
        assert!(res.is_ok());
        let djson = res.unwrap();
        assert!(djson.teams.len() == 2);
    }
}