pbfhogg 0.5.0

Fast OpenStreetMap PBF reader and writer for Rust. Read, write, and merge .osm.pbf files with pipelined parallel decoding.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Nodes, ways and relations

use super::block::{get_stringtable_key_value, str_from_stringtable};
use super::dense::DenseNode;
use super::wire::{
    PackedInt32Iter, PackedSint64Iter, PackedUint32Iter, WireBlock, WireInfo, WireNode,
    WireRelation, WireWay,
};
use crate::error::Result;

/// Generates degree-conversion coordinate methods from nanodegree accessors.
///
/// PBF coordinates are stored as nanodegrees (10^-9 degrees) internally. Three types
/// -- `Node`, `DenseNode`, and `WayNodeLocation` -- all need identical conversions from
/// nanodegrees to degrees and decimicrodegrees, but their `nano_lat()`/`nano_lon()`
/// implementations differ (protobuf field access vs struct field). This macro
/// deduplicates the conversion logic while letting each type keep its own nano accessor.
///
/// The macro generates four methods:
///   - `lat()` -> f64: nanodegrees to degrees (multiply by 1e-9)
///   - `lon()` -> f64: nanodegrees to degrees (multiply by 1e-9)
///   - `decimicro_lat()` -> i32: nanodegrees to decimicrodegrees (divide by 100)
///   - `decimicro_lon()` -> i32: nanodegrees to decimicrodegrees (divide by 100)
///
/// Each type must already have `nano_lat(&self) -> i64` and `nano_lon(&self) -> i64`
/// methods defined (they are NOT generated by this macro because the underlying storage
/// differs for each type).
///
/// This macro is an internal implementation detail. It is `#[macro_export]`ed only
/// because `macro_rules!` requires this for cross-module use within the crate
/// (`dense.rs` uses it for `DenseNode`). It is not intended as part of the public API.
#[doc(hidden)]
#[macro_export]
macro_rules! impl_coordinate_conversions {
    () => {
        /// Returns the latitude coordinate in degrees.
        #[inline]
        #[allow(clippy::cast_precision_loss)]
        pub fn lat(&self) -> f64 {
            1e-9 * self.nano_lat() as f64
        }

        /// Returns the longitude coordinate in degrees.
        #[inline]
        #[allow(clippy::cast_precision_loss)]
        pub fn lon(&self) -> f64 {
            1e-9 * self.nano_lon() as f64
        }

        /// Returns the latitude coordinate in decimicrodegrees (10^-7).
        #[inline]
        #[allow(clippy::cast_possible_truncation)]
        pub fn decimicro_lat(&self) -> i32 {
            (self.nano_lat() / 100) as i32
        }

        /// Returns the longitude coordinate in decimicrodegrees (10^-7).
        #[inline]
        #[allow(clippy::cast_possible_truncation)]
        pub fn decimicro_lon(&self) -> i32 {
            (self.nano_lon() / 100) as i32
        }
    };
}

/// An enum with the OSM core elements: nodes, ways and relations.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Element<'a> {
    /// A node. Also, see [`DenseNode`](Self::DenseNode).
    Node(Node<'a>),

    /// Just like [`Node`](Self::Node), but with a different representation in memory. This distinction is
    /// usually not important but is not abstracted away to avoid copying. So, if you want to match
    /// `Node`, you also likely want to match [`DenseNode`].
    DenseNode(DenseNode<'a>),

    /// A way.
    Way(Way<'a>),

    /// A relation.
    Relation(Relation<'a>),
}

/// An OpenStreetMap node element (See [OSM wiki](http://wiki.openstreetmap.org/wiki/Node)).
#[derive(Clone, Debug)]
pub struct Node<'a> {
    block: &'a WireBlock<'static>,
    node: WireNode<'a>,
    granularity: i64,
    lat_offset: i64,
    lon_offset: i64,
}

impl<'a> Node<'a> {
    pub(crate) fn new(block: &'a WireBlock<'static>, node: WireNode<'a>) -> Node<'a> {
        Node {
            block,
            node,
            granularity: i64::from(block.granularity),
            lat_offset: block.lat_offset,
            lon_offset: block.lon_offset,
        }
    }

    /// Returns the node id.
    #[inline]
    pub fn id(&self) -> i64 {
        self.node.id
    }

    /// Returns an iterator over the tags of this node.
    pub fn tags(&self) -> TagIter<'a> {
        TagIter {
            block: self.block,
            key_indices: PackedUint32Iter::new(self.node.keys_data),
            val_indices: PackedUint32Iter::new(self.node.vals_data),
        }
    }

    /// Returns additional metadata for this element.
    pub fn info(&self) -> Info<'a> {
        let wire_info = self
            .node
            .info_data
            .and_then(|data| WireInfo::parse(data).ok())
            .unwrap_or_default();
        Info::new(self.block, wire_info)
    }

    /// Returns the latitude coordinate in nanodegrees (10^-9).
    #[inline]
    pub fn nano_lat(&self) -> i64 {
        self.lat_offset + self.granularity * self.node.lat
    }

    /// Returns the longitude in nanodegrees (10^-9).
    #[inline]
    pub fn nano_lon(&self) -> i64 {
        self.lon_offset + self.granularity * self.node.lon
    }

    impl_coordinate_conversions!();

    /// Returns an iterator over the tags of this node as raw index pairs.
    pub fn raw_tags(&self) -> RawTagIter<'a> {
        RawTagIter {
            key_indices: PackedUint32Iter::new(self.node.keys_data),
            val_indices: PackedUint32Iter::new(self.node.vals_data),
        }
    }
}

/// An OpenStreetMap way element (See [OSM wiki](http://wiki.openstreetmap.org/wiki/Way)).
///
/// A way contains an ordered list of node references that can be accessed with the `refs`
/// method.
#[derive(Clone, Debug)]
pub struct Way<'a> {
    block: &'a WireBlock<'static>,
    way: WireWay<'a>,
    granularity: i64,
    lat_offset: i64,
    lon_offset: i64,
}

impl<'a> Way<'a> {
    pub(crate) fn new(block: &'a WireBlock<'static>, way: WireWay<'a>) -> Way<'a> {
        Way {
            block,
            way,
            granularity: i64::from(block.granularity),
            lat_offset: block.lat_offset,
            lon_offset: block.lon_offset,
        }
    }

    /// Returns the way id.
    #[inline]
    pub fn id(&self) -> i64 {
        self.way.id
    }

    /// Returns an iterator over the tags of this way.
    pub fn tags(&self) -> TagIter<'a> {
        TagIter {
            block: self.block,
            key_indices: PackedUint32Iter::new(self.way.keys_data),
            val_indices: PackedUint32Iter::new(self.way.vals_data),
        }
    }

    /// Returns additional metadata for this element.
    pub fn info(&self) -> Info<'a> {
        let wire_info = self
            .way
            .info_data
            .and_then(|data| WireInfo::parse(data).ok())
            .unwrap_or_default();
        Info::new(self.block, wire_info)
    }

    /// Returns an iterator over the references of this way. Each reference should correspond to a
    /// node id.
    pub fn refs(&self) -> WayRefIter<'a> {
        WayRefIter {
            deltas: PackedSint64Iter::new(self.way.refs_data),
            current: 0,
        }
    }

    /// Returns an iterator over the way's node locations (latitude, longitude).
    /// Only available if the optional `LocationsOnWays` feature is included in the
    /// [`HeaderBlock`](crate::block::HeaderBlock) and should return an empty iterator otherwise.
    pub fn node_locations(&self) -> WayNodeLocationsIter<'a> {
        WayNodeLocationsIter {
            dlats: PackedSint64Iter::new(self.way.lat_data),
            dlons: PackedSint64Iter::new(self.way.lon_data),
            clat: 0,
            clon: 0,
            granularity: self.granularity,
            lat_offset: self.lat_offset,
            lon_offset: self.lon_offset,
        }
    }

    /// Raw field-20 shared-node pin bitmap, if present.
    pub fn shared_node_pins(&self) -> Option<&'a [u8]> {
        self.way.pins_data
    }

    /// Returns an iterator over the tags of this way as raw index pairs.
    pub fn raw_tags(&self) -> RawTagIter<'a> {
        RawTagIter {
            key_indices: PackedUint32Iter::new(self.way.keys_data),
            val_indices: PackedUint32Iter::new(self.way.vals_data),
        }
    }

    /// Raw packed uint32 bytes for tag key string table indices.
    pub(crate) fn keys_data(&self) -> &[u8] {
        self.way.keys_data
    }

    /// Raw packed uint32 bytes for tag value string table indices.
    pub(crate) fn vals_data(&self) -> &[u8] {
        self.way.vals_data
    }

    /// Raw packed sint64 delta-encoded bytes for node refs.
    pub(crate) fn refs_data(&self) -> &[u8] {
        self.way.refs_data
    }

    /// Raw Info submessage bytes (if present).
    pub(crate) fn info_data(&self) -> Option<&[u8]> {
        self.way.info_data
    }

    /// Raw packed sint64 delta-encoded bytes for node latitudes (LocationsOnWays).
    pub(crate) fn lat_data(&self) -> &[u8] {
        self.way.lat_data
    }

    /// Raw packed sint64 delta-encoded bytes for node longitudes (LocationsOnWays).
    pub(crate) fn lon_data(&self) -> &[u8] {
        self.way.lon_data
    }
}

/// An OpenStreetMap relation element (See [OSM wiki](http://wiki.openstreetmap.org/wiki/Relation)).
///
/// A relation contains an ordered list of members that can be of any element type.
#[derive(Clone, Debug)]
pub struct Relation<'a> {
    block: &'a WireBlock<'static>,
    rel: WireRelation<'a>,
}

impl<'a> Relation<'a> {
    pub(crate) fn new(block: &'a WireBlock<'static>, rel: WireRelation<'a>) -> Relation<'a> {
        Relation { block, rel }
    }

    /// Returns the relation id.
    #[inline]
    pub fn id(&self) -> i64 {
        self.rel.id
    }

    /// Returns an iterator over the tags of this relation.
    pub fn tags(&self) -> TagIter<'a> {
        TagIter {
            block: self.block,
            key_indices: PackedUint32Iter::new(self.rel.keys_data),
            val_indices: PackedUint32Iter::new(self.rel.vals_data),
        }
    }

    /// Returns additional metadata for this element.
    pub fn info(&self) -> Info<'a> {
        let wire_info = self
            .rel
            .info_data
            .and_then(|data| WireInfo::parse(data).ok())
            .unwrap_or_default();
        Info::new(self.block, wire_info)
    }

    /// Returns an iterator over the members of this relation.
    pub fn members(&self) -> RelMemberIter<'a> {
        RelMemberIter::new(self.block, &self.rel)
    }

    /// Returns an iterator over the tags of this relation as raw index pairs.
    pub fn raw_tags(&self) -> RawTagIter<'a> {
        RawTagIter {
            key_indices: PackedUint32Iter::new(self.rel.keys_data),
            val_indices: PackedUint32Iter::new(self.rel.vals_data),
        }
    }

    /// Raw packed uint32 bytes for tag key string table indices.
    pub(crate) fn keys_data(&self) -> &[u8] {
        self.rel.keys_data
    }

    /// Raw packed uint32 bytes for tag value string table indices.
    pub(crate) fn vals_data(&self) -> &[u8] {
        self.rel.vals_data
    }

    /// Raw packed int32 bytes for member role string table indices.
    pub(crate) fn roles_sid_data(&self) -> &[u8] {
        self.rel.roles_sid_data
    }

    /// Raw packed sint64 delta-encoded bytes for member IDs.
    pub(crate) fn memids_data(&self) -> &[u8] {
        self.rel.memids_data
    }

    /// Raw packed int32 bytes for member types.
    pub(crate) fn types_data(&self) -> &[u8] {
        self.rel.types_data
    }

    /// Raw Info submessage bytes (if present).
    pub(crate) fn info_data(&self) -> Option<&[u8]> {
        self.rel.info_data
    }
}

/// An iterator over the references of a way.
///
/// Each reference corresponds to a node id.
#[derive(Clone)]
pub struct WayRefIter<'a> {
    deltas: PackedSint64Iter<'a>,
    current: i64,
}

impl Iterator for WayRefIter<'_> {
    type Item = i64;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.deltas.next().map(|d| {
            self.current += d;
            self.current
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.deltas.size_hint()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WayNodeLocation {
    lat: i64,
    lon: i64,
}

/// A node location that contains latitude and longitude coordinates.
impl WayNodeLocation {
    #[inline]
    pub fn nano_lat(&self) -> i64 {
        self.lat
    }

    #[inline]
    pub fn nano_lon(&self) -> i64 {
        self.lon
    }

    impl_coordinate_conversions!();
}

/// An iterator over the node locations of a way.
#[derive(Clone)]
pub struct WayNodeLocationsIter<'a> {
    dlats: PackedSint64Iter<'a>,
    dlons: PackedSint64Iter<'a>,
    clat: i64,
    clon: i64,
    granularity: i64,
    lat_offset: i64,
    lon_offset: i64,
}

impl Iterator for WayNodeLocationsIter<'_> {
    type Item = WayNodeLocation;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match (self.dlats.next(), self.dlons.next()) {
            (Some(dlat), Some(dlon)) => {
                self.clat += dlat;
                self.clon += dlon;
                Some(WayNodeLocation {
                    lat: self.lat_offset + self.granularity * self.clat,
                    lon: self.lon_offset + self.granularity * self.clon,
                })
            }
            _ => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.dlats.size_hint()
    }
}

/// The element type of a relation member.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum MemberType {
    Node,
    Way,
    Relation,
    /// A member type value not recognized by this version of the library.
    Unknown(i32),
}

impl From<i32> for MemberType {
    #[inline]
    fn from(v: i32) -> MemberType {
        match v {
            0 => MemberType::Node,
            1 => MemberType::Way,
            2 => MemberType::Relation,
            other => MemberType::Unknown(other),
        }
    }
}

/// A typed relation member reference combining element type and ID.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MemberId {
    Node(i64),
    Way(i64),
    Relation(i64),
    Unknown(i32, i64),
}

impl MemberId {
    /// Returns the raw element ID regardless of type.
    #[inline]
    pub fn id(self) -> i64 {
        match self {
            MemberId::Node(id)
            | MemberId::Way(id)
            | MemberId::Relation(id)
            | MemberId::Unknown(_, id) => id,
        }
    }

    /// Returns the element type of this member reference.
    #[inline]
    pub fn member_type(self) -> MemberType {
        match self {
            MemberId::Node(_) => MemberType::Node,
            MemberId::Way(_) => MemberType::Way,
            MemberId::Relation(_) => MemberType::Relation,
            MemberId::Unknown(raw, _) => MemberType::Unknown(raw),
        }
    }

    /// Construct a MemberId from a raw id and type.
    #[inline]
    pub fn from_id_and_type(id: i64, member_type: MemberType) -> Self {
        match member_type {
            MemberType::Node => MemberId::Node(id),
            MemberType::Way => MemberId::Way(id),
            MemberType::Relation => MemberId::Relation(id),
            MemberType::Unknown(raw) => MemberId::Unknown(raw, id),
        }
    }
}

/// A member of a relation.
#[derive(Clone, Debug)]
pub struct RelMember<'a> {
    block: &'a WireBlock<'static>,
    pub role_sid: i32,
    pub id: MemberId,
}

impl<'a> RelMember<'a> {
    /// Returns the role of a relation member.
    #[allow(clippy::cast_sign_loss)]
    pub fn role(&self) -> Result<&'a str> {
        if self.role_sid < 0 {
            return Err(crate::error::new_error(
                crate::error::ErrorKind::WireFormat {
                    msg: "relation member has negative role string index",
                },
            ));
        }
        str_from_stringtable(self.block, self.role_sid as usize)
    }
}

/// An iterator over the members of a relation.
#[derive(Clone)]
pub struct RelMemberIter<'a> {
    block: &'a WireBlock<'static>,
    role_sids: PackedInt32Iter<'a>,
    member_id_deltas: PackedSint64Iter<'a>,
    member_types: PackedInt32Iter<'a>,
    current_member_id: i64,
}

impl<'a> RelMemberIter<'a> {
    fn new(block: &'a WireBlock<'static>, rel: &WireRelation<'a>) -> RelMemberIter<'a> {
        RelMemberIter {
            block,
            role_sids: PackedInt32Iter::new(rel.roles_sid_data),
            member_id_deltas: PackedSint64Iter::new(rel.memids_data),
            member_types: PackedInt32Iter::new(rel.types_data),
            current_member_id: 0,
        }
    }
}

impl<'a> Iterator for RelMemberIter<'a> {
    type Item = RelMember<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match (
            self.role_sids.next(),
            self.member_id_deltas.next(),
            self.member_types.next(),
        ) {
            (Some(role_sid), Some(mem_id_delta), Some(member_type)) => {
                self.current_member_id += mem_id_delta;
                let mt = MemberType::from(member_type);
                Some(RelMember {
                    block: self.block,
                    role_sid,
                    id: MemberId::from_id_and_type(self.current_member_id, mt),
                })
            }
            _ => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.role_sids.size_hint()
    }
}

/// An iterator over the tags of an element. It returns a pair of strings (key and value).
#[derive(Clone)]
pub struct TagIter<'a> {
    block: &'a WireBlock<'static>,
    key_indices: PackedUint32Iter<'a>,
    val_indices: PackedUint32Iter<'a>,
}

impl<'a> Iterator for TagIter<'a> {
    type Item = (&'a str, &'a str);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        get_stringtable_key_value(
            self.block,
            self.key_indices.next().map(|v| v as usize),
            self.val_indices.next().map(|v| v as usize),
        )
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.key_indices.size_hint()
    }
}

/// An iterator over the tags of an element as raw index pairs.
#[derive(Clone)]
pub struct RawTagIter<'a> {
    key_indices: PackedUint32Iter<'a>,
    val_indices: PackedUint32Iter<'a>,
}

impl Iterator for RawTagIter<'_> {
    type Item = (u32, u32);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match (self.key_indices.next(), self.val_indices.next()) {
            (Some(key_index), Some(val_index)) => Some((key_index, val_index)),
            _ => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.key_indices.size_hint()
    }
}

/// Additional metadata that might be included in each element.
#[derive(Clone, Debug)]
pub struct Info<'a> {
    block: &'a WireBlock<'static>,
    info: WireInfo,
}

impl<'a> Info<'a> {
    fn new(block: &'a WireBlock<'static>, info: WireInfo) -> Info<'a> {
        Info { block, info }
    }

    /// Returns the version of this element.
    #[inline]
    pub fn version(&self) -> Option<i32> {
        self.info.version
    }

    /// Returns the time stamp in milliseconds since the epoch.
    #[inline]
    pub fn milli_timestamp(&self) -> Option<i64> {
        self.info
            .timestamp
            .map(|ts| ts * i64::from(self.block.date_granularity))
    }

    /// Returns the changeset id.
    #[inline]
    pub fn changeset(&self) -> Option<i64> {
        self.info.changeset
    }

    /// Returns the user id.
    #[inline]
    pub fn uid(&self) -> Option<i32> {
        self.info.uid
    }

    /// Returns the raw string table index for the user name, if present.
    #[inline]
    pub fn raw_user_sid(&self) -> Option<i32> {
        self.info.user_sid
    }

    /// Returns the user name.
    #[allow(clippy::cast_sign_loss)]
    pub fn user(&self) -> Option<Result<&'a str>> {
        self.info.user_sid.map(|sid| {
            if sid < 0 {
                return Err(crate::error::new_error(
                    crate::error::ErrorKind::StringtableIndexOutOfBounds { index: 0 },
                ));
            }
            str_from_stringtable(self.block, sid as usize)
        })
    }

    /// Returns the visibility status of an element.
    // wontfix(name-is-has-bool): inherited from osmpbf public API
    #[inline]
    pub fn visible(&self) -> bool {
        self.info.visible.unwrap_or(true)
    }

    /// Return visibility only when the source info message carries the field.
    pub(crate) fn visible_opt(&self) -> Option<bool> {
        self.info.visible
    }

    /// Returns true if the element was deleted.
    // wontfix(name-is-has-bool): inherited from osmpbf public API
    #[inline]
    pub fn deleted(&self) -> bool {
        !self.visible()
    }
}