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
//! Simple line-based parser for Skytraxx airspace files.
//!
//! If you want to use this library, you need the [`parse`](fn.parse.html)
//! function as entry point.
//!
//! For an example on how to use the parse function, see the examples in the
//! source repository.
#![deny(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::many_single_char_names)]
#![allow(clippy::non_ascii_literal)]

use std::fmt;
use std::io::BufRead;

use log::trace;

/// Airspace class.
#[derive(Debug, PartialEq, Eq)]
pub enum Class {
    /// Airspace C
    C,
    /// Airspace D
    D,
    /// Airspace E
    E,
    /// Airspace G
    G,
    /// Controlled Traffic Region
    CTR,
    /// Danger area (LS-D)
    Danger,
    /// Restricted area (LS-R)
    Restricted,
    /// Prohibited area (LS-P)
    Prohibited,
}

impl fmt::Display for Class {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Class {
    fn parse(data: &str) -> Result<Self, String> {
        match data {
            "C" => Ok(Class::C),
            "D" => Ok(Class::D),
            "E" => Ok(Class::E),
            "G" => Ok(Class::G),
            "CTR" => Ok(Class::CTR),
            "Q" => Ok(Class::Danger),
            "R" => Ok(Class::Restricted),
            "P" => Ok(Class::Prohibited),
            other => Err(format!("Invalid class: {}", other))
        }
    }
}

/// Altitude, either ground or a certain height AMSL in feet.
#[derive(Debug, PartialEq, Eq)]
pub enum Altitude {
    /// Ground level
    Gnd,
    /// Feet above mean sea level
    FeetAmsl(i32),
    /// Feet above ground level
    FeetAgl(i32),
}

impl fmt::Display for Altitude {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Altitude::Gnd => write!(f, "GND"),
            Altitude::FeetAmsl(ft) => write!(f, "{} ft AMSL", ft),
            Altitude::FeetAgl(ft) => write!(f, "{} ft AGL", ft),
        }
    }
}

impl Altitude {
    fn parse(data: &str) -> Result<Self, String> {
        if data == "GND" {
            Ok(Altitude::Gnd)
        } else {
            let is_digit = |c: &char| c.is_digit(10);
            let number: String = data.chars().take_while(is_digit).collect();
            let rest: String = data.chars().skip_while(is_digit).collect();
            match (number.parse::<i32>().ok(), &*rest) {
                (Some(ft), " ft") => Ok(Altitude::FeetAmsl(ft)),
                (Some(ft), " ft AGL") => Ok(Altitude::FeetAgl(ft)),
                _ => Err(format!("Invalid altitude: {:?}", data))
            }
        }
    }
}

/// A coordinate pair (WGS84).
#[derive(Debug, PartialEq)]
pub struct Coord {
    lat: f64,
    lng: f64,
}

impl Coord {
    fn parse_number_opt(val: Option<&str>) -> Result<u16, ()> {
        val.and_then(|v| v.parse::<u16>().ok()).ok_or(())
    }

    fn parse_component(val: &str) -> Result<f64, ()> {
        let mut parts = val.split(':');
        let deg = Self::parse_number_opt(parts.next())?;
        let min = Self::parse_number_opt(parts.next())?;
        let sec = Self::parse_number_opt(parts.next())?;
        Ok(f64::from(deg) + f64::from(min) / 60.0 + f64::from(sec) / 3600.0)
    }

    fn multiplier_lat(val: &str) -> Result<f64, ()> {
        match val {
            "N" => Ok(1.0),
            "S" => Ok(-1.0),
            _ => Err(())
        }
    }

    fn multiplier_lng(val: &str) -> Result<f64, ()> {
        match val {
            "E" => Ok(1.0),
            "W" => Ok(-1.0),
            _ => Err(())
        }
    }

    fn parse(data: &str) -> Result<Self, String> {
        let parts: Vec<&str> = data.split(' ').collect();
        let invalid = |_| format!("Invalid coord: {}", data);
        if parts.len() != 4 {
            return Err(invalid(()));
        }
        let lat = Self::multiplier_lat(parts[1]).map_err(invalid)?
                * Self::parse_component(parts[0]).map_err(invalid)?;
        let lng = Self::multiplier_lng(parts[3]).map_err(invalid)?
                * Self::parse_component(parts[2]).map_err(invalid)?;
        Ok(Self { lat, lng })
    }
}

#[derive(Debug, PartialEq)]
pub enum Geometry {
    Polygon {
        /// Points describing the polygon.
        ///
        /// The polygon may be open or closed.
        points: Vec<Coord>
    },
    Circle {
        /// The centerpoint of the circle.
        centerpoint: Coord,
        /// Radius of the circle in nautical miles (1 NM = 1852 m).
        radius: f32,
    },
}

impl fmt::Display for Geometry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Geometry::Polygon { points } => write!(f, "Polygon[{}]", points.len()),
            Geometry::Circle { radius, .. } => write!(f, "Circle[r={}NM]", radius),
        }
    }
}

/// An airspace.
#[derive(Debug)]
pub struct Airspace {
    /// The name / description of the airspace
    pub name: String,
    /// The airspace class
    pub class: Class,
    /// The lower bound of the airspace
    pub lower_bound: Altitude,
    /// The upper bound of the airspace
    pub upper_bound: Altitude,
    /// The airspace geometry
    pub geom: Geometry,
}

impl fmt::Display for Airspace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} [{}] ({} → {}) {{{}}}",
            self.name,
            self.class,
            self.lower_bound,
            self.upper_bound,
            self.geom,
        )
    }
}

#[derive(Debug)]
enum ParsingState {
    New,
    HasClass(Class),
    HasName(Class, String),
    HasLowerBound(Class, String, Altitude),
    HasUpperBound(Class, String, Altitude, Altitude),
    ParsingPolygon(Class, String, Altitude, Altitude, Vec<Coord>),
    ParsingCircle(Class, String, Altitude, Altitude, Coord),
    Done(Airspace),
}

impl fmt::Display for ParsingState {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", match self {
            ParsingState::New => "New",
            ParsingState::HasClass(..) => "HasClass",
            ParsingState::HasName(..) => "HasName",
            ParsingState::HasLowerBound(..) => "HasLowerBound",
            ParsingState::HasUpperBound(..) => "HasUpperBound",
            ParsingState::ParsingPolygon(..) => "ParsingPolygon",
            ParsingState::ParsingCircle(..) => "ParsingCircle",
            ParsingState::Done(..) => "Done",
        })
    }
}

/// Process a line based on the current state. Return a new state or an error.
fn process(state: ParsingState, line: &str) -> Result<ParsingState, String> {
    let mut chars = line.chars();
    let t1 = chars.next().ok_or_else(|| "Line too short".to_string())?;
    let t2 = chars.next().ok_or_else(|| "Line too short".to_string())?;
    let data = line.get(3..).unwrap_or("").trim();
    trace!("State: \"{}\", Input: \"{:1}{:1}\"", state, t1, t2);
    match (state, t1, t2) {
        (ParsingState::New, '*', _) => {
            // Comment, ignore
            trace!("-> Ignore");
            Ok(ParsingState::New)
        }
        (ParsingState::New, 'A', 'C') => {
            // Airspace class
            trace!("-> Found class");
            let class = Class::parse(data)?;
            Ok(ParsingState::HasClass(class))
        }
        (ParsingState::HasClass(c), 'A', 'N') => {
            trace!("-> Found name");
            Ok(ParsingState::HasName(c, data.to_string()))
        }
        (ParsingState::HasName(c, n), 'A', 'L') => {
            trace!("-> Found lower bound");
            let lower = Altitude::parse(data)?;
            Ok(ParsingState::HasLowerBound(c, n, lower))
        }
        (ParsingState::HasLowerBound(c, n, l), 'A', 'H') => {
            trace!("-> Found upper bound");
            let upper = Altitude::parse(data)?;
            Ok(ParsingState::HasUpperBound(c, n, l, upper))
        }
        (ParsingState::HasUpperBound(c, n, l, u), 'D', 'P') => {
            trace!("-> Found point");
            let coords = vec![Coord::parse(data)?];
            Ok(ParsingState::ParsingPolygon(c, n, l, u, coords))
        }
        (ParsingState::HasUpperBound(c, n, l, u), 'V', _) => {
            trace!("-> Found centerpoint");
            let centerpoint = Coord::parse(data.get(1..).unwrap_or(""))?;
            Ok(ParsingState::ParsingCircle(c, n, l, u, centerpoint))
        }
        (ParsingState::ParsingPolygon(c, n, l, u, mut p), 'D', 'P') => {
            trace!("-> Found point");
            p.push(Coord::parse(data)?);
            Ok(ParsingState::ParsingPolygon(c, n, l, u, p))
        }
        (ParsingState::ParsingPolygon(c, n, l, u, p), '*', _) => {
            trace!("-> Done parsing polygon");
            if p.len() < 2 {
                return Err(format!("Invalid airspace polygon (only {} points)", p.len()));
            }
            Ok(ParsingState::Done(Airspace {
                name: n,
                class: c,
                lower_bound: l,
                upper_bound: u,
                geom: Geometry::Polygon { points: p },
            }))
        }
        (ParsingState::ParsingCircle(c, n, l, u, p), 'D', 'C') => {
            trace!("-> Found point");
            let radius = data.parse::<f32>().map_err(|_| format!("Invalid radius: {}", data))?;
            Ok(ParsingState::Done(Airspace {
                name: n,
                class: c,
                lower_bound: l,
                upper_bound: u,
                geom: Geometry::Circle { centerpoint: p, radius },
            }))
        }
        (state, t1, t2) => {
            Err(format!("Parse error in state \"{}\" (unexpected \"{:1}{:1}\")", state, t1, t2))
        }
    }
}

/// Process the reader line by line and return the next complete airspace.
///
/// When the end of the reader has been reached, return `None`.
pub fn parse<R: BufRead>(reader: &mut R) -> Result<Option<Airspace>, String> {
    let mut state = ParsingState::New;
    loop {
        // Read next line
        let mut line = String::new();
        let bytes_read = reader.read_line(&mut line)
            .map_err(|e| format!("Could not read line: {}", e))?;
        if bytes_read == 0 {
            // EOF
            return Ok(None);
        }

        // Trim BOM
        let trimmed_line = line.trim_start_matches('\u{feff}');

        // Find next state
        state = process(state, trimmed_line)?;

        if let ParsingState::Done(airspace) = state {
            return Ok(Some(airspace))
        }
    }
}

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

    #[test]
    #[allow(clippy::unreadable_literal)]
    fn parse_coord() {
        assert_eq!(
            Coord::parse("46:51:44 N 009:19:42 E"),
            Ok(Coord { lat: 46.86222222222222, lng: 9.328333333333333 })
        );
        assert_eq!(
            Coord::parse("46:51:44 S 009:19:42 W"),
            Ok(Coord { lat: -46.86222222222222, lng: -9.328333333333333 })
        );
        assert_eq!(
            Coord::parse("46:51:44 Q 009:19:42 R"),
            Err("Invalid coord: 46:51:44 Q 009:19:42 R".to_string())
        );
    }
}