vadeen_osm 0.1.3

IO and builder library for Open Street Map data.
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
use std::io;
use std::io::Write;

use super::*;
use crate::geo::{Boundary, Coordinate};
use crate::osm_io::error::ErrorKind;
use crate::osm_io::o5m::varint::VarInt;
use crate::osm_io::o5m::Delta::{
    ChangeSet, Id, Lat, Lon, RelNodeRef, RelRelRef, RelWayRef, Time, WayRef,
};
use crate::osm_io::OsmWriter;
use crate::{Meta, Node, Osm, Relation, RelationMember, Way};

/// A writer for the o5m binary format.
#[derive(Debug)]
pub struct O5mWriter<W> {
    inner: W,
    encoder: O5mEncoder,
}

/// Encodes data into bytes according the o5m specification. Keeps track of string references and
/// delta values.
#[derive(Debug)]
struct O5mEncoder {
    string_table: StringReferenceTable,
    delta: DeltaState,
}

impl<W: Write> O5mWriter<W> {
    pub fn new(writer: W) -> O5mWriter<W> {
        O5mWriter {
            inner: writer,
            encoder: O5mEncoder::new(),
        }
    }

    /// See: https://wiki.openstreetmap.org/wiki/O5m#Reset
    fn reset(&mut self) -> io::Result<()> {
        self.inner.write_all(&[O5M_RESET])?;
        self.encoder.reset();
        Ok(())
    }

    /// See: https://wiki.openstreetmap.org/wiki/O5m#Bounding_Box
    fn write_bounding_box(&mut self, boundary: &Boundary) -> io::Result<()> {
        let mut bytes = Vec::new();
        bytes.append(&mut VarInt::create_bytes(boundary.min.lon));
        bytes.append(&mut VarInt::create_bytes(boundary.min.lat));
        bytes.append(&mut VarInt::create_bytes(boundary.max.lon));
        bytes.append(&mut VarInt::create_bytes(boundary.max.lat));

        self.inner.write_all(&[O5M_BOUNDING_BOX])?;
        self.inner
            .write_all(&VarInt::create_bytes(bytes.len() as u64))?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }

    /// See: https://wiki.openstreetmap.org/wiki/O5m#Node
    fn write_node(&mut self, node: &Node) -> io::Result<()> {
        let bytes = self.encoder.node_to_bytes(node);
        self.inner.write_all(&[O5M_NODE])?;
        self.inner
            .write_all(&VarInt::create_bytes(bytes.len() as u64))?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }

    /// See: https://wiki.openstreetmap.org/wiki/O5m#Way
    fn write_way(&mut self, way: &Way) -> io::Result<()> {
        let bytes = self.encoder.way_to_bytes(way);
        self.inner.write_all(&[O5M_WAY])?;
        self.inner
            .write_all(&VarInt::create_bytes(bytes.len() as u64))?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }

    /// See: https://wiki.openstreetmap.org/wiki/O5m#Relation
    fn write_relation(&mut self, rel: &Relation) -> io::Result<()> {
        let bytes = self.encoder.relation_to_bytes(rel);
        self.inner.write_all(&[O5M_RELATION])?;
        self.inner
            .write_all(&VarInt::create_bytes(bytes.len() as u64))?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }
}

impl<W: Write> OsmWriter<W> for O5mWriter<W> {
    fn write(&mut self, osm: &Osm) -> std::result::Result<(), ErrorKind> {
        self.reset()?;
        self.inner.write_all(&[O5M_HEADER])?;
        self.inner.write_all(O5M_HEADER_DATA)?;

        if let Some(boundary) = &osm.boundary {
            self.write_bounding_box(&boundary)?;
        }

        self.reset()?;
        for node in &osm.nodes {
            self.write_node(&node)?;
        }

        self.reset()?;
        for way in &osm.ways {
            self.write_way(&way)?;
        }

        self.reset()?;
        for rel in &osm.relations {
            self.write_relation(&rel)?;
        }

        self.inner.write_all(&[O5M_EOF])?;
        Ok(())
    }

    fn into_inner(self: Box<Self>) -> W {
        self.inner
    }
}

impl O5mEncoder {
    pub fn new() -> Self {
        O5mEncoder {
            string_table: StringReferenceTable::new(),
            delta: DeltaState::new(),
        }
    }

    /// Resets string reference table and all deltas.
    pub fn reset(&mut self) {
        self.string_table.clear();
        self.delta = DeltaState::new();
    }

    /// Converts a node into a byte vector that can be written to file.
    /// See: https://wiki.openstreetmap.org/wiki/O5m#Node
    pub fn node_to_bytes(&mut self, node: &Node) -> Vec<u8> {
        let delta_id = self.delta.encode(Id, node.id);
        let delta_coordinate = self.delta_coordinate(node.coordinate);

        let mut bytes = Vec::new();
        bytes.append(&mut VarInt::create_bytes(delta_id));
        bytes.append(&mut self.meta_to_bytes(&node.meta));
        bytes.append(&mut VarInt::create_bytes(delta_coordinate.lon));
        bytes.append(&mut VarInt::create_bytes(delta_coordinate.lat));

        for tag in &node.meta.tags {
            bytes.append(&mut self.string_pair_to_bytes(&tag.key, &tag.value));
        }

        bytes
    }

    /// Converts a way into a byte vector that can be written to file.
    /// See: https://wiki.openstreetmap.org/wiki/O5m#Way
    pub fn way_to_bytes(&mut self, way: &Way) -> Vec<u8> {
        let delta_id = self.delta.encode(Id, way.id);
        let mut ref_bytes = self.way_refs_to_bytes(&way.refs);

        let mut bytes = Vec::new();
        bytes.append(&mut VarInt::create_bytes(delta_id));
        bytes.append(&mut self.meta_to_bytes(&way.meta));
        bytes.append(&mut VarInt::create_bytes(ref_bytes.len() as u64));
        bytes.append(&mut ref_bytes);

        for tag in &way.meta.tags {
            bytes.append(&mut self.string_pair_to_bytes(&tag.key, &tag.value));
        }

        bytes
    }

    /// Converts way references to bytes.
    fn way_refs_to_bytes(&mut self, refs: &[i64]) -> Vec<u8> {
        let mut bytes = Vec::new();
        for i in refs {
            let delta = self.delta.encode(WayRef, *i);
            bytes.append(&mut VarInt::create_bytes(delta));
        }
        bytes
    }

    /// Converts a relation into a byte vector that can be written to file.
    /// See: https://wiki.openstreetmap.org/wiki/O5m#Relation
    pub fn relation_to_bytes(&mut self, rel: &Relation) -> Vec<u8> {
        let delta_id = self.delta.encode(Id, rel.id);
        let mut mem_bytes = self.rel_members_to_bytes(&rel.members);

        let mut bytes = Vec::new();
        bytes.append(&mut VarInt::create_bytes(delta_id));
        bytes.append(&mut self.meta_to_bytes(&rel.meta));
        bytes.append(&mut VarInt::create_bytes(mem_bytes.len() as u64));
        bytes.append(&mut mem_bytes);

        for tag in &rel.meta.tags {
            bytes.append(&mut self.string_pair_to_bytes(&tag.key, &tag.value));
        }

        bytes
    }

    /// Converts relation members to bytes.
    fn rel_members_to_bytes(&mut self, members: &[RelationMember]) -> Vec<u8> {
        let mut bytes = Vec::new();
        for m in members {
            let mem_type = member_type(m);
            let mem_role = m.role();
            let delta = self.delta_rel_member(m);

            bytes.append(&mut VarInt::create_bytes(delta));
            bytes.push(0x00);
            for b in mem_type.bytes() {
                bytes.push(b);
            }
            for b in mem_role.bytes() {
                bytes.push(b);
            }
            bytes.push(0x00);
        }
        bytes
    }

    /// Converts meta to bytes. It's positioned directly after the id of the element.
    pub fn meta_to_bytes(&mut self, meta: &Meta) -> Vec<u8> {
        let mut bytes = Vec::new();
        if let Some(version) = meta.version {
            bytes.append(&mut VarInt::create_bytes(version));

            if let Some(author) = meta.author.as_ref() {
                let delta_time = self.delta.encode(Time, author.created);
                let delta_change_set = self.delta.encode(ChangeSet, author.change_set as i64);

                bytes.append(&mut VarInt::create_bytes(delta_time));
                bytes.append(&mut VarInt::create_bytes(delta_change_set));
                bytes.append(&mut self.user_to_bytes(author.uid, &author.user));
            } else {
                bytes.push(0x00); // No author info.
            }
        } else {
            bytes.push(0x00); // No version, no timestamp and no author info.
        }
        bytes
    }

    /// Converts a string pair into a byte vector that can be written to file.
    /// If the string has appeared previously after the last reset a reference is returned.
    ///
    /// See: https://wiki.openstreetmap.org/wiki/O5m#Strings
    fn string_pair_to_bytes(&mut self, key: &str, value: &str) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.push(0x00);
        for byte in key.bytes() {
            bytes.push(byte);
        }

        bytes.push(0x00);
        for byte in value.bytes() {
            bytes.push(byte);
        }
        bytes.push(0x00);

        self.string_table.reference(bytes)
    }

    /// Converts a user to a byte vector that can be written to file.
    /// See: https://wiki.openstreetmap.org/wiki/O5m#Strings
    fn user_to_bytes(&mut self, uid: u64, username: &str) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.push(0);
        bytes.append(&mut VarInt::create_bytes(uid));

        bytes.push(0);
        for byte in username.bytes() {
            bytes.push(byte);
        }
        bytes.push(0);

        self.string_table.reference(bytes)
    }

    /// Relation members have delta split on the relation type.
    fn delta_rel_member(&mut self, member: &RelationMember) -> i64 {
        match member {
            RelationMember::Node(id, _) => self.delta.encode(RelNodeRef, *id),
            RelationMember::Way(id, _) => self.delta.encode(RelWayRef, *id),
            RelationMember::Relation(id, _) => self.delta.encode(RelRelRef, *id),
        }
    }

    fn delta_coordinate(&mut self, coordinate: Coordinate) -> Coordinate {
        Coordinate {
            lat: self.delta.encode(Lat, coordinate.lat as i64) as i32,
            lon: self.delta.encode(Lon, coordinate.lon as i64) as i32,
        }
    }
}

/// See: https://wiki.openstreetmap.org/wiki/O5m#cite_note-1
fn member_type(member: &RelationMember) -> &str {
    match member {
        RelationMember::Node(_, _) => "0",
        RelationMember::Way(_, _) => "1",
        RelationMember::Relation(_, _) => "2",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AuthorInformation, Meta, Relation, RelationMember, Way};

    #[test]
    fn string_pair_bytes() {
        let mut encoder = O5mEncoder::new();
        let bytes = encoder.string_pair_to_bytes("oneway", "yes");
        let expected: Vec<u8> = vec![
            0x00, 0x6f, 0x6e, 0x65, 0x77, 0x61, 0x79, 0x00, 0x79, 0x65, 0x73, 0x00,
        ];
        assert_eq!(bytes, expected);
    }

    #[test]
    fn string_references() {
        let mut references = O5mEncoder::new();
        assert_eq!(
            references.string_pair_to_bytes("oneway", "yes"),
            vec![0x00, 0x6f, 0x6e, 0x65, 0x77, 0x61, 0x79, 0x00, 0x79, 0x65, 0x73, 0x00]
        );
        assert_eq!(
            references.string_pair_to_bytes("atm", "no"),
            vec![0x00, 0x61, 0x74, 0x6d, 0x00, 0x6e, 0x6f, 0x00]
        );
        assert_eq!(references.string_pair_to_bytes("oneway", "yes"), vec![0x02]);
        assert_eq!(
            references.user_to_bytes(1020, "John"),
            vec![0x00, 0xfc, 0x07, 0x00, 0x4a, 0x6f, 0x68, 0x6e, 0x00]
        );
        assert_eq!(references.string_pair_to_bytes("atm", "no"), vec![0x02]);
        assert_eq!(references.string_pair_to_bytes("oneway", "yes"), vec![0x03]);
        assert_eq!(references.user_to_bytes(1020, "John"), vec![0x01]);
    }

    #[test]
    fn write_node() {
        let expected: Vec<u8> = vec![
            0x10, // Node type
            0x26, // Length
            0x80, 0x01, // Id, delta
            0x01, // Version
            0xe4, 0x8e, 0xa7, 0xca, 0x09, // Timestamp
            0x94, 0xfe, 0xd2, 0x05, // Changeset
            0x00, 0x85, 0xe3, 0x02, 0x00, // Uid
            0x55, 0x53, 0x63, 0x68, 0x61, 0x00, // User
            0x08, // Lon, delta
            0x81, 0x01, // Lat, delta
            // oneway=yes
            0x00, 0x6F, 0x6E, 0x65, 0x77, 0x61, 0x79, 0x00, 0x79, 0x65, 0x73, 0x00,
        ];

        let node = Node {
            id: 64,
            coordinate: Coordinate { lat: -65, lon: 4 },
            meta: Meta {
                tags: vec![("oneway", "yes").into()],
                version: Some(1),
                author: Some(AuthorInformation {
                    created: 1285874610,
                    change_set: 5922698,
                    uid: 45445,
                    user: "UScha".to_string(),
                }),
                ..Default::default()
            },
        };

        let mut writer = O5mWriter::new(Vec::new());
        writer.write_node(&node).unwrap();
        assert_eq!(writer.inner, expected)
    }

    #[test]
    fn write_way() {
        let expected: Vec<u8> = vec![
            0x11, // Way type
            0x1B, // Length
            0x80, 0x01, // Id, delta
            0x01, // Version
            0x00, // Timestamp
            0x03, // Length of ref section
            0x80, 0x01, // Ref1
            0x02, // Ref2
            // highway=secondary
            0x00, 0x68, 0x69, 0x67, 0x68, 0x77, 0x61, 0x79, 0x00, 0x73, 0x65, 0x63, 0x6f, 0x6e,
            0x64, 0x61, 0x72, 0x79, 0x00,
        ];

        let way = Way {
            id: 64,
            refs: vec![64, 65],
            meta: Meta {
                tags: vec![("highway", "secondary").into()],
                version: Some(1),
                ..Default::default()
            },
        };

        let mut writer = O5mWriter::new(Vec::new());
        writer.write_way(&way).unwrap();
        assert_eq!(writer.inner, expected)
    }

    #[test]
    fn relation_bytes() {
        let expected: Vec<u8> = vec![
            0x12, // Relation type
            0x29, // Length
            0x80, 0x01, // Id, delta
            0x00, // Version
            0x12, // Length of ref section
            0x08, // Ref id, delta
            0x00, 0x31, // Way
            0x6F, 0x75, 0x74, 0x65, 0x72, 0x00, // Outer
            0x08, // Ref id, delta
            0x00, 0x31, // Way
            0x69, 0x6e, 0x6e, 0x65, 0x72, 0x00, // Inner
            // type=multipolygon
            0x00, 0x74, 0x79, 0x70, 0x65, 0x00, 0x6D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6F, 0x6C,
            0x79, 0x67, 0x6F, 0x6E, 0x00,
        ];
        let relation = Relation {
            id: 64,
            members: vec![
                RelationMember::Way(4, "outer".to_owned()),
                RelationMember::Way(8, "inner".to_owned()),
            ],
            meta: Meta {
                tags: vec![("type", "multipolygon").into()],
                ..Default::default()
            },
        };

        let mut writer = O5mWriter::new(Vec::new());
        writer.write_relation(&relation).unwrap();
        assert_eq!(writer.inner, expected)
    }

    #[test]
    fn coordinate_delta() {
        let mut encoder = O5mEncoder::new();
        assert_eq!(
            encoder.delta_coordinate(Coordinate { lat: 1, lon: 10 }),
            Coordinate { lat: 1, lon: 10 }
        );
        assert_eq!(
            encoder.delta_coordinate(Coordinate { lat: 2, lon: 11 }),
            Coordinate { lat: 1, lon: 1 }
        );
    }
}