4 Commits

Autore SHA1 Messaggio Data
  Johannes Hofmann e0699ffd29 Release 0.1.15 5 anni fa
  Johannes Hofmann 7ad09a37ec Regenerate *.rs files in `src/proto/` 5 anni fa
  Johannes Hofmann ae08d8dc81 Require exact version of protobuf (2.10.0) 5 anni fa
  Johannes Hofmann aac8d1dafe Run `cargo fmt` 6 anni fa
14 ha cambiato i file con 264 aggiunte e 280 eliminazioni
  1. 2
    2
      Cargo.toml
  2. 10
    10
      examples/count.rs
  3. 48
    48
      src/blob.rs
  4. 57
    72
      src/block.rs
  5. 28
    25
      src/dense.rs
  6. 25
    31
      src/elements.rs
  7. 32
    30
      src/error.rs
  8. 3
    4
      src/lib.rs
  9. 15
    12
      src/mmap_blob.rs
  10. 3
    3
      src/proto/fileformat.rs
  11. 3
    3
      src/proto/osmformat.rs
  12. 27
    28
      src/reader.rs
  13. 5
    4
      src/util.rs
  14. 6
    8
      tests/read.rs

+ 2
- 2
Cargo.toml Vedi File

1
 [package]
1
 [package]
2
 name = "osmpbf"
2
 name = "osmpbf"
3
-version = "0.1.14"
3
+version = "0.1.15"
4
 authors = ["Johannes Hofmann <mail@b-r-u.org>"]
4
 authors = ["Johannes Hofmann <mail@b-r-u.org>"]
5
 readme = "README.md"
5
 readme = "README.md"
6
 repository = "https://github.com/b-r-u/osmpbf"
6
 repository = "https://github.com/b-r-u/osmpbf"
21
 system-libz = ["flate2"]
21
 system-libz = ["flate2"]
22
 
22
 
23
 [dependencies]
23
 [dependencies]
24
-protobuf = "~2.10"
24
+protobuf = "=2.10.1"
25
 byteorder = "1.1"
25
 byteorder = "1.1"
26
 flate2 = { version = "1.0", optional = true }
26
 flate2 = { version = "1.0", optional = true }
27
 inflate = "0.4"
27
 inflate = "0.4"

+ 10
- 10
examples/count.rs Vedi File

6
 use osmpbf::*;
6
 use osmpbf::*;
7
 
7
 
8
 fn main() {
8
 fn main() {
9
-    let arg = std::env::args_os().nth(1).expect("need a *.osm.pbf file as argument");
9
+    let arg = std::env::args_os()
10
+        .nth(1)
11
+        .expect("need a *.osm.pbf file as argument");
10
     let path = std::path::Path::new(&arg);
12
     let path = std::path::Path::new(&arg);
11
     let reader = ElementReader::from_path(path).unwrap();
13
     let reader = ElementReader::from_path(path).unwrap();
12
 
14
 
13
     println!("Counting...");
15
     println!("Counting...");
14
 
16
 
15
     match reader.par_map_reduce(
17
     match reader.par_map_reduce(
16
-        |element| {
17
-            match element {
18
-                Element::Node(_) | Element::DenseNode(_) => (1, 0, 0),
19
-                Element::Way(_) => (0, 1, 0),
20
-                Element::Relation(_) => (0, 0, 1),
21
-            }
18
+        |element| match element {
19
+            Element::Node(_) | Element::DenseNode(_) => (1, 0, 0),
20
+            Element::Way(_) => (0, 1, 0),
21
+            Element::Relation(_) => (0, 0, 1),
22
         },
22
         },
23
         || (0u64, 0u64, 0u64),
23
         || (0u64, 0u64, 0u64),
24
-        |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2)
24
+        |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2),
25
     ) {
25
     ) {
26
         Ok((nodes, ways, relations)) => {
26
         Ok((nodes, ways, relations)) => {
27
             println!("Nodes: {}", nodes);
27
             println!("Nodes: {}", nodes);
28
             println!("Ways: {}", ways);
28
             println!("Ways: {}", ways);
29
             println!("Relations: {}", relations);
29
             println!("Relations: {}", relations);
30
-        },
30
+        }
31
         Err(e) => {
31
         Err(e) => {
32
             println!("{}", e);
32
             println!("{}", e);
33
-        },
33
+        }
34
     }
34
     }
35
 }
35
 }

+ 48
- 48
src/blob.rs Vedi File

1
 //! Read and decode blobs
1
 //! Read and decode blobs
2
 
2
 
3
-extern crate protobuf;
4
 extern crate byteorder;
3
 extern crate byteorder;
4
+extern crate protobuf;
5
 
5
 
6
 use block::{HeaderBlock, PrimitiveBlock};
6
 use block::{HeaderBlock, PrimitiveBlock};
7
 use byteorder::ReadBytesExt;
7
 use byteorder::ReadBytesExt;
8
-use error::{BlobError, Result, new_blob_error, new_protobuf_error};
8
+use error::{new_blob_error, new_protobuf_error, BlobError, Result};
9
 use proto::fileformat;
9
 use proto::fileformat;
10
 use std::fs::File;
10
 use std::fs::File;
11
 use std::io::{BufReader, Read, Seek, SeekFrom};
11
 use std::io::{BufReader, Read, Seek, SeekFrom};
18
 #[cfg(not(feature = "system-libz"))]
18
 #[cfg(not(feature = "system-libz"))]
19
 use inflate::DeflateDecoder;
19
 use inflate::DeflateDecoder;
20
 
20
 
21
-
22
 /// Maximum allowed `BlobHeader` size in bytes.
21
 /// Maximum allowed `BlobHeader` size in bytes.
23
 pub static MAX_BLOB_HEADER_SIZE: u64 = 64 * 1024;
22
 pub static MAX_BLOB_HEADER_SIZE: u64 = 64 * 1024;
24
 
23
 
25
 /// Maximum allowed uncompressed `Blob` content size in bytes.
24
 /// Maximum allowed uncompressed `Blob` content size in bytes.
26
 pub static MAX_BLOB_MESSAGE_SIZE: u64 = 32 * 1024 * 1024;
25
 pub static MAX_BLOB_MESSAGE_SIZE: u64 = 32 * 1024 * 1024;
27
 
26
 
28
-
29
 /// The content type of a blob.
27
 /// The content type of a blob.
30
 #[derive(Clone, Debug, Eq, PartialEq)]
28
 #[derive(Clone, Debug, Eq, PartialEq)]
31
 pub enum BlobType<'a> {
29
 pub enum BlobType<'a> {
86
             BlobType::OsmHeader => {
84
             BlobType::OsmHeader => {
87
                 let block = Box::new(self.to_headerblock()?);
85
                 let block = Box::new(self.to_headerblock()?);
88
                 Ok(BlobDecode::OsmHeader(block))
86
                 Ok(BlobDecode::OsmHeader(block))
89
-
90
-            },
87
+            }
91
             BlobType::OsmData => {
88
             BlobType::OsmData => {
92
                 let block = self.to_primitiveblock()?;
89
                 let block = self.to_primitiveblock()?;
93
                 Ok(BlobDecode::OsmData(block))
90
                 Ok(BlobDecode::OsmData(block))
94
-            },
91
+            }
95
             BlobType::Unknown(x) => Ok(BlobDecode::Unknown(x)),
92
             BlobType::Unknown(x) => Ok(BlobDecode::Unknown(x)),
96
         }
93
         }
97
     }
94
     }
114
     /// Tries to decode the blob to a `HeaderBlock`. This operation might involve an expensive
111
     /// Tries to decode the blob to a `HeaderBlock`. This operation might involve an expensive
115
     /// decompression step.
112
     /// decompression step.
116
     pub fn to_headerblock(&self) -> Result<HeaderBlock> {
113
     pub fn to_headerblock(&self) -> Result<HeaderBlock> {
117
-        decode_blob(&self.blob)
118
-            .map(HeaderBlock::new)
114
+        decode_blob(&self.blob).map(HeaderBlock::new)
119
     }
115
     }
120
 
116
 
121
     /// Tries to decode the blob to a `PrimitiveBlock`. This operation might involve an expensive
117
     /// Tries to decode the blob to a `PrimitiveBlock`. This operation might involve an expensive
122
     /// decompression step.
118
     /// decompression step.
123
     pub fn to_primitiveblock(&self) -> Result<PrimitiveBlock> {
119
     pub fn to_primitiveblock(&self) -> Result<PrimitiveBlock> {
124
-        decode_blob(&self.blob)
125
-            .map(PrimitiveBlock::new)
120
+        decode_blob(&self.blob).map(PrimitiveBlock::new)
126
     }
121
     }
127
 }
122
 }
128
 
123
 
177
     /// # }
172
     /// # }
178
     /// # foo().unwrap();
173
     /// # foo().unwrap();
179
     /// ```
174
     /// ```
180
-    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self>
181
-    {
175
+    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
182
         let f = File::open(path)?;
176
         let f = File::open(path)?;
183
         let reader = BufReader::new(f);
177
         let reader = BufReader::new(f);
184
 
178
 
205
             Ok(n) => {
199
             Ok(n) => {
206
                 self.offset = self.offset.map(|x| ByteOffset(x.0 + 4));
200
                 self.offset = self.offset.map(|x| ByteOffset(x.0 + 4));
207
                 u64::from(n)
201
                 u64::from(n)
208
-            },
202
+            }
209
             Err(e) => {
203
             Err(e) => {
210
                 self.offset = None;
204
                 self.offset = None;
211
                 match e.kind() {
205
                 match e.kind() {
212
                     ::std::io::ErrorKind::UnexpectedEof => {
206
                     ::std::io::ErrorKind::UnexpectedEof => {
213
                         //TODO This also accepts corrupted files in the case of 1-3 available bytes
207
                         //TODO This also accepts corrupted files in the case of 1-3 available bytes
214
-                        return None
215
-                    },
208
+                        return None;
209
+                    }
216
                     _ => {
210
                     _ => {
217
                         self.last_blob_ok = false;
211
                         self.last_blob_ok = false;
218
                         return Some(Err(new_blob_error(BlobError::InvalidHeaderSize)));
212
                         return Some(Err(new_blob_error(BlobError::InvalidHeaderSize)));
219
-                    },
213
+                    }
220
                 }
214
                 }
221
-            },
215
+            }
222
         };
216
         };
223
 
217
 
224
         if header_size >= MAX_BLOB_HEADER_SIZE {
218
         if header_size >= MAX_BLOB_HEADER_SIZE {
225
             self.last_blob_ok = false;
219
             self.last_blob_ok = false;
226
-            return Some(Err(new_blob_error(BlobError::HeaderTooBig{size: header_size})));
220
+            return Some(Err(new_blob_error(BlobError::HeaderTooBig {
221
+                size: header_size,
222
+            })));
227
         }
223
         }
228
 
224
 
229
-        let header: fileformat::BlobHeader = match parse_message_from_reader(&mut self.reader.by_ref().take(header_size)) {
230
-            Ok(header) => header,
231
-            Err(e) => {
232
-                self.offset = None;
233
-                self.last_blob_ok = false;
234
-                return Some(Err(new_protobuf_error(e, "blob header")));
235
-            },
236
-        };
225
+        let header: fileformat::BlobHeader =
226
+            match parse_message_from_reader(&mut self.reader.by_ref().take(header_size)) {
227
+                Ok(header) => header,
228
+                Err(e) => {
229
+                    self.offset = None;
230
+                    self.last_blob_ok = false;
231
+                    return Some(Err(new_protobuf_error(e, "blob header")));
232
+                }
233
+            };
237
 
234
 
238
-        let blob: fileformat::Blob = match parse_message_from_reader(&mut self.reader.by_ref().take(header.get_datasize() as u64)) {
235
+        let blob: fileformat::Blob = match parse_message_from_reader(
236
+            &mut self.reader.by_ref().take(header.get_datasize() as u64),
237
+        ) {
239
             Ok(blob) => blob,
238
             Ok(blob) => blob,
240
             Err(e) => {
239
             Err(e) => {
241
                 self.offset = None;
240
                 self.offset = None;
242
                 self.last_blob_ok = false;
241
                 self.last_blob_ok = false;
243
                 return Some(Err(new_protobuf_error(e, "blob content")));
242
                 return Some(Err(new_protobuf_error(e, "blob content")));
244
-            },
243
+            }
245
         };
244
         };
246
 
245
 
247
-        self.offset = self.offset.map(|x| ByteOffset(
248
-            x.0 + header_size + header.get_datasize() as u64
249
-        ));
246
+        self.offset = self
247
+            .offset
248
+            .map(|x| ByteOffset(x.0 + header_size + header.get_datasize() as u64));
250
 
249
 
251
         Some(Ok(Blob::new(header, blob, prev_offset)))
250
         Some(Ok(Blob::new(header, blob, prev_offset)))
252
     }
251
     }
306
             Ok(offset) => {
305
             Ok(offset) => {
307
                 self.offset = Some(ByteOffset(offset));
306
                 self.offset = Some(ByteOffset(offset));
308
                 Ok(())
307
                 Ok(())
309
-            },
308
+            }
310
             Err(e) => {
309
             Err(e) => {
311
                 self.offset = None;
310
                 self.offset = None;
312
                 Err(e.into())
311
                 Err(e.into())
313
-            },
312
+            }
314
         }
313
         }
315
     }
314
     }
316
 
315
 
320
             Ok(offset) => {
319
             Ok(offset) => {
321
                 self.offset = Some(ByteOffset(offset));
320
                 self.offset = Some(ByteOffset(offset));
322
                 Ok(offset)
321
                 Ok(offset)
323
-            },
322
+            }
324
             Err(e) => {
323
             Err(e) => {
325
                 self.offset = None;
324
                 self.offset = None;
326
                 Err(e.into())
325
                 Err(e.into())
327
-            },
326
+            }
328
         }
327
         }
329
     }
328
     }
330
 }
329
 }
355
 
354
 
356
 #[cfg(feature = "system-libz")]
355
 #[cfg(feature = "system-libz")]
357
 pub(crate) fn decode_blob<T>(blob: &fileformat::Blob) -> Result<T>
356
 pub(crate) fn decode_blob<T>(blob: &fileformat::Blob) -> Result<T>
358
-    where T: protobuf::Message {
357
+where
358
+    T: protobuf::Message,
359
+{
359
     if blob.has_raw() {
360
     if blob.has_raw() {
360
         let size = blob.get_raw().len() as u64;
361
         let size = blob.get_raw().len() as u64;
361
         if size < MAX_BLOB_MESSAGE_SIZE {
362
         if size < MAX_BLOB_MESSAGE_SIZE {
362
             parse_message_from_bytes(blob.get_raw())
363
             parse_message_from_bytes(blob.get_raw())
363
                 .map_err(|e| new_protobuf_error(e, "raw blob data"))
364
                 .map_err(|e| new_protobuf_error(e, "raw blob data"))
364
         } else {
365
         } else {
365
-            Err(new_blob_error(BlobError::MessageTooBig{size}))
366
+            Err(new_blob_error(BlobError::MessageTooBig { size }))
366
         }
367
         }
367
     } else if blob.has_zlib_data() {
368
     } else if blob.has_zlib_data() {
368
-        let mut decoder = ZlibDecoder::new(blob.get_zlib_data())
369
-            .take(MAX_BLOB_MESSAGE_SIZE);
370
-        parse_message_from_reader(&mut decoder)
371
-            .map_err(|e| new_protobuf_error(e, "blob zlib data"))
369
+        let mut decoder = ZlibDecoder::new(blob.get_zlib_data()).take(MAX_BLOB_MESSAGE_SIZE);
370
+        parse_message_from_reader(&mut decoder).map_err(|e| new_protobuf_error(e, "blob zlib data"))
372
     } else {
371
     } else {
373
         Err(new_blob_error(BlobError::Empty))
372
         Err(new_blob_error(BlobError::Empty))
374
     }
373
     }
376
 
375
 
377
 #[cfg(not(feature = "system-libz"))]
376
 #[cfg(not(feature = "system-libz"))]
378
 pub(crate) fn decode_blob<T>(blob: &fileformat::Blob) -> Result<T>
377
 pub(crate) fn decode_blob<T>(blob: &fileformat::Blob) -> Result<T>
379
-    where T: protobuf::Message {
378
+where
379
+    T: protobuf::Message,
380
+{
380
     if blob.has_raw() {
381
     if blob.has_raw() {
381
         let size = blob.get_raw().len() as u64;
382
         let size = blob.get_raw().len() as u64;
382
         if size < MAX_BLOB_MESSAGE_SIZE {
383
         if size < MAX_BLOB_MESSAGE_SIZE {
383
             parse_message_from_bytes(blob.get_raw())
384
             parse_message_from_bytes(blob.get_raw())
384
                 .map_err(|e| new_protobuf_error(e, "raw blob data"))
385
                 .map_err(|e| new_protobuf_error(e, "raw blob data"))
385
         } else {
386
         } else {
386
-            Err(new_blob_error(BlobError::MessageTooBig{size}))
387
+            Err(new_blob_error(BlobError::MessageTooBig { size }))
387
         }
388
         }
388
     } else if blob.has_zlib_data() {
389
     } else if blob.has_zlib_data() {
389
-        let mut decoder = DeflateDecoder::from_zlib(blob.get_zlib_data())
390
-            .take(MAX_BLOB_MESSAGE_SIZE);
391
-        parse_message_from_reader(&mut decoder)
392
-            .map_err(|e| new_protobuf_error(e, "blob zlib data"))
390
+        let mut decoder =
391
+            DeflateDecoder::from_zlib(blob.get_zlib_data()).take(MAX_BLOB_MESSAGE_SIZE);
392
+        parse_message_from_reader(&mut decoder).map_err(|e| new_protobuf_error(e, "blob zlib data"))
393
     } else {
393
     } else {
394
         Err(new_blob_error(BlobError::Empty))
394
         Err(new_blob_error(BlobError::Empty))
395
     }
395
     }

+ 57
- 72
src/block.rs Vedi File

1
 //! `HeaderBlock`, `PrimitiveBlock` and `PrimitiveGroup`s
1
 //! `HeaderBlock`, `PrimitiveBlock` and `PrimitiveGroup`s
2
 
2
 
3
 use dense::DenseNodeIter;
3
 use dense::DenseNodeIter;
4
-use elements::{Element, Node, Way, Relation};
5
-use error::{ErrorKind, Result, new_error};
4
+use elements::{Element, Node, Relation, Way};
5
+use error::{new_error, ErrorKind, Result};
6
 use proto::osmformat;
6
 use proto::osmformat;
7
 use std;
7
 use std;
8
 
8
 
9
-
10
 /// A `HeaderBlock`. It contains metadata about following `PrimitiveBlock`s.
9
 /// A `HeaderBlock`. It contains metadata about following `PrimitiveBlock`s.
11
 #[derive(Clone, Debug)]
10
 #[derive(Clone, Debug)]
12
 pub struct HeaderBlock {
11
 pub struct HeaderBlock {
53
 
52
 
54
     /// Calls the given closure on each element.
53
     /// Calls the given closure on each element.
55
     pub fn for_each_element<F>(&self, mut f: F)
54
     pub fn for_each_element<F>(&self, mut f: F)
56
-        where F: for<'a> FnMut(Element<'a>)
55
+    where
56
+        F: for<'a> FnMut(Element<'a>),
57
     {
57
     {
58
         for group in self.groups() {
58
         for group in self.groups() {
59
             for node in group.nodes() {
59
             for node in group.nodes() {
88
 }
88
 }
89
 
89
 
90
 impl<'a> PrimitiveGroup<'a> {
90
 impl<'a> PrimitiveGroup<'a> {
91
-    fn new(block: &'a osmformat::PrimitiveBlock,
92
-           group: &'a osmformat::PrimitiveGroup)
93
-          -> PrimitiveGroup<'a> {
94
-        PrimitiveGroup {
95
-            block,
96
-            group,
97
-        }
91
+    fn new(
92
+        block: &'a osmformat::PrimitiveBlock,
93
+        group: &'a osmformat::PrimitiveGroup,
94
+    ) -> PrimitiveGroup<'a> {
95
+        PrimitiveGroup { block, group }
98
     }
96
     }
99
 
97
 
100
     /// Returns an iterator over the nodes in this group.
98
     /// Returns an iterator over the nodes in this group.
136
     DenseNode,
134
     DenseNode,
137
     Node,
135
     Node,
138
     Way,
136
     Way,
139
-    Relation
137
+    Relation,
140
 }
138
 }
141
 
139
 
142
 impl<'a> BlockElementsIter<'a> {
140
 impl<'a> BlockElementsIter<'a> {
158
     #[allow(clippy::option_option)]
156
     #[allow(clippy::option_option)]
159
     fn step(&mut self) -> Option<Option<Element<'a>>> {
157
     fn step(&mut self) -> Option<Option<Element<'a>>> {
160
         match self.state {
158
         match self.state {
161
-            ElementsIterState::Group => {
162
-                match self.groups.next() {
163
-                    Some(group) => {
164
-                        self.state = ElementsIterState::DenseNode;
165
-                        self.dense_nodes = DenseNodeIter::new(self.block, group.get_dense());
166
-                        self.nodes = group.get_nodes().iter();
167
-                        self.ways = group.get_ways().iter();
168
-                        self.relations = group.get_relations().iter();
169
-                        None
170
-                    },
171
-                    None => Some(None),
159
+            ElementsIterState::Group => match self.groups.next() {
160
+                Some(group) => {
161
+                    self.state = ElementsIterState::DenseNode;
162
+                    self.dense_nodes = DenseNodeIter::new(self.block, group.get_dense());
163
+                    self.nodes = group.get_nodes().iter();
164
+                    self.ways = group.get_ways().iter();
165
+                    self.relations = group.get_relations().iter();
166
+                    None
172
                 }
167
                 }
168
+                None => Some(None),
173
             },
169
             },
174
-            ElementsIterState::DenseNode => {
175
-                match self.dense_nodes.next() {
176
-                    Some(dense_node) => {
177
-                        Some(Some(Element::DenseNode(dense_node)))
178
-                    },
179
-                    None => {
180
-                        self.state = ElementsIterState::Node;
181
-                        None
182
-                    },
170
+            ElementsIterState::DenseNode => match self.dense_nodes.next() {
171
+                Some(dense_node) => Some(Some(Element::DenseNode(dense_node))),
172
+                None => {
173
+                    self.state = ElementsIterState::Node;
174
+                    None
183
                 }
175
                 }
184
             },
176
             },
185
-            ElementsIterState::Node => {
186
-                match self.nodes.next() {
187
-                    Some(node) => {
188
-                        Some(Some(Element::Node(Node::new(self.block, node))))
189
-                    },
190
-                    None => {
191
-                        self.state = ElementsIterState::Way;
192
-                        None
193
-                    },
177
+            ElementsIterState::Node => match self.nodes.next() {
178
+                Some(node) => Some(Some(Element::Node(Node::new(self.block, node)))),
179
+                None => {
180
+                    self.state = ElementsIterState::Way;
181
+                    None
194
                 }
182
                 }
195
             },
183
             },
196
-            ElementsIterState::Way => {
197
-                match self.ways.next() {
198
-                    Some(way) => {
199
-                        Some(Some(Element::Way(Way::new(self.block, way))))
200
-                    },
201
-                    None => {
202
-                        self.state = ElementsIterState::Relation;
203
-                        None
204
-                    },
184
+            ElementsIterState::Way => match self.ways.next() {
185
+                Some(way) => Some(Some(Element::Way(Way::new(self.block, way)))),
186
+                None => {
187
+                    self.state = ElementsIterState::Relation;
188
+                    None
205
                 }
189
                 }
206
             },
190
             },
207
-            ElementsIterState::Relation => {
208
-                match self.relations.next() {
209
-                    Some(rel) => {
210
-                        Some(Some(Element::Relation(Relation::new(self.block, rel))))
211
-                    },
212
-                    None => {
213
-                        self.state = ElementsIterState::Group;
214
-                        None
215
-                    },
191
+            ElementsIterState::Relation => match self.relations.next() {
192
+                Some(rel) => Some(Some(Element::Relation(Relation::new(self.block, rel)))),
193
+                None => {
194
+                    self.state = ElementsIterState::Group;
195
+                    None
216
                 }
196
                 }
217
             },
197
             },
218
         }
198
         }
232
     }
212
     }
233
 }
213
 }
234
 
214
 
235
-
236
 /// An iterator over the groups in a `PrimitiveBlock`.
215
 /// An iterator over the groups in a `PrimitiveBlock`.
237
 #[derive(Clone, Debug)]
216
 #[derive(Clone, Debug)]
238
 pub struct GroupIter<'a> {
217
 pub struct GroupIter<'a> {
274
 }
253
 }
275
 
254
 
276
 impl<'a> GroupNodeIter<'a> {
255
 impl<'a> GroupNodeIter<'a> {
277
-    fn new(block: &'a osmformat::PrimitiveBlock,
278
-           group: &'a osmformat::PrimitiveGroup)
279
-          -> GroupNodeIter<'a> {
256
+    fn new(
257
+        block: &'a osmformat::PrimitiveBlock,
258
+        group: &'a osmformat::PrimitiveGroup,
259
+    ) -> GroupNodeIter<'a> {
280
         GroupNodeIter {
260
         GroupNodeIter {
281
             block,
261
             block,
282
             nodes: group.get_nodes().iter(),
262
             nodes: group.get_nodes().iter(),
309
 }
289
 }
310
 
290
 
311
 impl<'a> GroupWayIter<'a> {
291
 impl<'a> GroupWayIter<'a> {
312
-    fn new(block: &'a osmformat::PrimitiveBlock,
313
-           group: &'a osmformat::PrimitiveGroup)
314
-          -> GroupWayIter<'a> {
292
+    fn new(
293
+        block: &'a osmformat::PrimitiveBlock,
294
+        group: &'a osmformat::PrimitiveGroup,
295
+    ) -> GroupWayIter<'a> {
315
         GroupWayIter {
296
         GroupWayIter {
316
             block,
297
             block,
317
             ways: group.get_ways().iter(),
298
             ways: group.get_ways().iter(),
344
 }
325
 }
345
 
326
 
346
 impl<'a> GroupRelationIter<'a> {
327
 impl<'a> GroupRelationIter<'a> {
347
-    fn new(block: &'a osmformat::PrimitiveBlock,
348
-           group: &'a osmformat::PrimitiveGroup)
349
-          -> GroupRelationIter<'a> {
328
+    fn new(
329
+        block: &'a osmformat::PrimitiveBlock,
330
+        group: &'a osmformat::PrimitiveGroup,
331
+    ) -> GroupRelationIter<'a> {
350
         GroupRelationIter {
332
         GroupRelationIter {
351
             block,
333
             block,
352
             rels: group.get_relations().iter(),
334
             rels: group.get_relations().iter(),
371
 
353
 
372
 impl<'a> ExactSizeIterator for GroupRelationIter<'a> {}
354
 impl<'a> ExactSizeIterator for GroupRelationIter<'a> {}
373
 
355
 
374
-pub(crate) fn str_from_stringtable(block: &osmformat::PrimitiveBlock, index: usize) -> Result<&str> {
356
+pub(crate) fn str_from_stringtable(
357
+    block: &osmformat::PrimitiveBlock,
358
+    index: usize,
359
+) -> Result<&str> {
375
     if let Some(vec) = block.get_stringtable().get_s().get(index) {
360
     if let Some(vec) = block.get_stringtable().get_s().get(index) {
376
         std::str::from_utf8(vec)
361
         std::str::from_utf8(vec)
377
-            .map_err(|e| new_error(ErrorKind::StringtableUtf8{err: e, index}))
362
+            .map_err(|e| new_error(ErrorKind::StringtableUtf8 { err: e, index }))
378
     } else {
363
     } else {
379
-        Err(new_error(ErrorKind::StringtableIndexOutOfBounds{index}))
364
+        Err(new_error(ErrorKind::StringtableIndexOutOfBounds { index }))
380
     }
365
     }
381
 }
366
 }

+ 28
- 25
src/dense.rs Vedi File

1
 //! Iterate over the dense nodes in a `PrimitiveGroup`
1
 //! Iterate over the dense nodes in a `PrimitiveGroup`
2
 
2
 
3
+use block::str_from_stringtable;
3
 use error::Result;
4
 use error::Result;
4
 use proto::osmformat;
5
 use proto::osmformat;
5
-use block::str_from_stringtable;
6
 use std;
6
 use std;
7
 
7
 
8
-
9
 //TODO Add getter functions for id, version, uid, ...
8
 //TODO Add getter functions for id, version, uid, ...
10
 /// An OpenStreetMap node element from a compressed array of dense nodes (See [OSM wiki](http://wiki.openstreetmap.org/wiki/Node)).
9
 /// An OpenStreetMap node element from a compressed array of dense nodes (See [OSM wiki](http://wiki.openstreetmap.org/wiki/Node)).
11
 #[derive(Clone, Debug)]
10
 #[derive(Clone, Debug)]
93
 pub struct DenseNodeIter<'a> {
92
 pub struct DenseNodeIter<'a> {
94
     block: &'a osmformat::PrimitiveBlock,
93
     block: &'a osmformat::PrimitiveBlock,
95
     dids: std::slice::Iter<'a, i64>, // deltas
94
     dids: std::slice::Iter<'a, i64>, // deltas
96
-    cid: i64, // current id
95
+    cid: i64,                        // current id
97
     versions: std::slice::Iter<'a, i32>,
96
     versions: std::slice::Iter<'a, i32>,
98
     dtimestamps: std::slice::Iter<'a, i64>, // deltas
97
     dtimestamps: std::slice::Iter<'a, i64>, // deltas
99
     ctimestamp: i64,
98
     ctimestamp: i64,
112
 }
111
 }
113
 
112
 
114
 impl<'a> DenseNodeIter<'a> {
113
 impl<'a> DenseNodeIter<'a> {
115
-    pub(crate) fn new(block: &'a osmformat::PrimitiveBlock,
116
-           osmdense: &'a osmformat::DenseNodes) -> DenseNodeIter<'a> {
114
+    pub(crate) fn new(
115
+        block: &'a osmformat::PrimitiveBlock,
116
+        osmdense: &'a osmformat::DenseNodes,
117
+    ) -> DenseNodeIter<'a> {
117
         let info = osmdense.get_denseinfo();
118
         let info = osmdense.get_denseinfo();
118
         DenseNodeIter {
119
         DenseNodeIter {
119
             block,
120
             block,
161
     }
162
     }
162
 }
163
 }
163
 
164
 
164
-
165
 impl<'a> Iterator for DenseNodeIter<'a> {
165
 impl<'a> Iterator for DenseNodeIter<'a> {
166
     type Item = DenseNode<'a>;
166
     type Item = DenseNode<'a>;
167
 
167
 
168
     fn next(&mut self) -> Option<Self::Item> {
168
     fn next(&mut self) -> Option<Self::Item> {
169
-        match (self.dids.next(),
170
-               self.versions.next(),
171
-               self.dtimestamps.next(),
172
-               self.dchangesets.next(),
173
-               self.duids.next(),
174
-               self.duser_sids.next(),
175
-               self.dlats.next(),
176
-               self.dlons.next()) {
177
-            (Some(did),
178
-             Some(version),
179
-             Some(dtimestamp),
180
-             Some(dchangeset),
181
-             Some(duid),
182
-             Some(duser_sid),
183
-             Some(dlat),
184
-             Some(dlon)) => {
169
+        match (
170
+            self.dids.next(),
171
+            self.versions.next(),
172
+            self.dtimestamps.next(),
173
+            self.dchangesets.next(),
174
+            self.duids.next(),
175
+            self.duser_sids.next(),
176
+            self.dlats.next(),
177
+            self.dlons.next(),
178
+        ) {
179
+            (
180
+                Some(did),
181
+                Some(version),
182
+                Some(dtimestamp),
183
+                Some(dchangeset),
184
+                Some(duid),
185
+                Some(duser_sid),
186
+                Some(dlat),
187
+                Some(dlon),
188
+            ) => {
185
                 self.cid += *did;
189
                 self.cid += *did;
186
                 self.ctimestamp += *dtimestamp;
190
                 self.ctimestamp += *dtimestamp;
187
                 self.cchangeset += *dchangeset;
191
                 self.cchangeset += *dchangeset;
214
                     lon: self.clon,
218
                     lon: self.clon,
215
                     keys_vals_indices: &self.keys_vals_slice[start_index..end_index],
219
                     keys_vals_indices: &self.keys_vals_slice[start_index..end_index],
216
                 })
220
                 })
217
-
218
-            },
221
+            }
219
             _ => None,
222
             _ => None,
220
         }
223
         }
221
     }
224
     }
248
                 } else {
251
                 } else {
249
                     None
252
                     None
250
                 }
253
                 }
251
-            },
254
+            }
252
             _ => None,
255
             _ => None,
253
         }
256
         }
254
     }
257
     }

+ 25
- 31
src/elements.rs Vedi File

1
 //! Nodes, ways and relations
1
 //! Nodes, ways and relations
2
 
2
 
3
-use error::Result;
4
 use block::str_from_stringtable;
3
 use block::str_from_stringtable;
5
 use dense::DenseNode;
4
 use dense::DenseNode;
6
-use proto::osmformat::PrimitiveBlock;
5
+use error::Result;
7
 use proto::osmformat;
6
 use proto::osmformat;
7
+use proto::osmformat::PrimitiveBlock;
8
 use std;
8
 use std;
9
 
9
 
10
-
11
 /// An enum with the OSM core elements: nodes, ways and relations.
10
 /// An enum with the OSM core elements: nodes, ways and relations.
12
 #[derive(Clone, Debug)]
11
 #[derive(Clone, Debug)]
13
 pub enum Element<'a> {
12
 pub enum Element<'a> {
35
 
34
 
36
 impl<'a> Node<'a> {
35
 impl<'a> Node<'a> {
37
     pub(crate) fn new(block: &'a PrimitiveBlock, osmnode: &'a osmformat::Node) -> Node<'a> {
36
     pub(crate) fn new(block: &'a PrimitiveBlock, osmnode: &'a osmformat::Node) -> Node<'a> {
38
-        Node {
39
-            block,
40
-            osmnode,
41
-        }
37
+        Node { block, osmnode }
42
     }
38
     }
43
 
39
 
44
     /// Returns the node id. It should be unique between nodes and might be negative to indicate
40
     /// Returns the node id. It should be unique between nodes and might be negative to indicate
90
 
86
 
91
     /// Returns the latitude coordinate in nanodegrees (10⁻⁹).
87
     /// Returns the latitude coordinate in nanodegrees (10⁻⁹).
92
     pub fn nano_lat(&self) -> i64 {
88
     pub fn nano_lat(&self) -> i64 {
93
-        self.block.get_lat_offset() + i64::from(self.block.get_granularity()) * self.osmnode.get_lat()
89
+        self.block.get_lat_offset()
90
+            + i64::from(self.block.get_granularity()) * self.osmnode.get_lat()
94
     }
91
     }
95
 
92
 
96
     /// Returns the latitude coordinate in decimicrodegrees (10⁻⁷).
93
     /// Returns the latitude coordinate in decimicrodegrees (10⁻⁷).
105
 
102
 
106
     /// Returns the longitude in nanodegrees (10⁻⁹).
103
     /// Returns the longitude in nanodegrees (10⁻⁹).
107
     pub fn nano_lon(&self) -> i64 {
104
     pub fn nano_lon(&self) -> i64 {
108
-        self.block.get_lon_offset() + i64::from(self.block.get_granularity()) * self.osmnode.get_lon()
105
+        self.block.get_lon_offset()
106
+            + i64::from(self.block.get_granularity()) * self.osmnode.get_lon()
109
     }
107
     }
110
 
108
 
111
     /// Returns the longitude coordinate in decimicrodegrees (10⁻⁷).
109
     /// Returns the longitude coordinate in decimicrodegrees (10⁻⁷).
146
 
144
 
147
 impl<'a> Way<'a> {
145
 impl<'a> Way<'a> {
148
     pub(crate) fn new(block: &'a PrimitiveBlock, osmway: &'a osmformat::Way) -> Way<'a> {
146
     pub(crate) fn new(block: &'a PrimitiveBlock, osmway: &'a osmformat::Way) -> Way<'a> {
149
-        Way {
150
-            block,
151
-            osmway,
152
-        }
147
+        Way { block, osmway }
153
     }
148
     }
154
 
149
 
155
     /// Returns the way id.
150
     /// Returns the way id.
197
     /// node id.
192
     /// node id.
198
     pub fn refs(&self) -> WayRefIter<'a> {
193
     pub fn refs(&self) -> WayRefIter<'a> {
199
         WayRefIter {
194
         WayRefIter {
200
-           deltas: self.osmway.get_refs().iter(),
201
-           current: 0,
195
+            deltas: self.osmway.get_refs().iter(),
196
+            current: 0,
202
         }
197
         }
203
     }
198
     }
204
 
199
 
239
 
234
 
240
 impl<'a> Relation<'a> {
235
 impl<'a> Relation<'a> {
241
     pub(crate) fn new(block: &'a PrimitiveBlock, osmrel: &'a osmformat::Relation) -> Relation<'a> {
236
     pub(crate) fn new(block: &'a PrimitiveBlock, osmrel: &'a osmformat::Relation) -> Relation<'a> {
242
-        Relation {
243
-            block,
244
-            osmrel,
245
-        }
237
+        Relation { block, osmrel }
246
     }
238
     }
247
 
239
 
248
     /// Returns the relation id.
240
     /// Returns the relation id.
329
             Some(&d) => {
321
             Some(&d) => {
330
                 self.current += d;
322
                 self.current += d;
331
                 Some(self.current)
323
                 Some(self.current)
332
-            },
324
+            }
333
             None => None,
325
             None => None,
334
         }
326
         }
335
     }
327
     }
346
 pub enum RelMemberType {
338
 pub enum RelMemberType {
347
     Node,
339
     Node,
348
     Way,
340
     Way,
349
-    Relation
341
+    Relation,
350
 }
342
 }
351
 
343
 
352
 impl From<osmformat::Relation_MemberType> for RelMemberType {
344
 impl From<osmformat::Relation_MemberType> for RelMemberType {
404
     type Item = RelMember<'a>;
396
     type Item = RelMember<'a>;
405
 
397
 
406
     fn next(&mut self) -> Option<Self::Item> {
398
     fn next(&mut self) -> Option<Self::Item> {
407
-        match (self.role_sids.next(),
408
-               self.member_id_deltas.next(),
409
-               self.member_types.next()) {
399
+        match (
400
+            self.role_sids.next(),
401
+            self.member_id_deltas.next(),
402
+            self.member_types.next(),
403
+        ) {
410
             (Some(role_sid), Some(mem_id_delta), Some(member_type)) => {
404
             (Some(role_sid), Some(mem_id_delta), Some(member_type)) => {
411
                 self.current_member_id += *mem_id_delta;
405
                 self.current_member_id += *mem_id_delta;
412
                 Some(RelMember {
406
                 Some(RelMember {
415
                     member_id: self.current_member_id,
409
                     member_id: self.current_member_id,
416
                     member_type: RelMemberType::from(*member_type),
410
                     member_type: RelMemberType::from(*member_type),
417
                 })
411
                 })
418
-            },
412
+            }
419
             _ => None,
413
             _ => None,
420
         }
414
         }
421
     }
415
     }
449
                 } else {
443
                 } else {
450
                     None
444
                     None
451
                 }
445
                 }
452
-            },
446
+            }
453
             _ => None,
447
             _ => None,
454
         }
448
         }
455
     }
449
     }
497
 
491
 
498
 impl<'a> Info<'a> {
492
 impl<'a> Info<'a> {
499
     fn new(block: &'a PrimitiveBlock, info: &'a osmformat::Info) -> Info<'a> {
493
     fn new(block: &'a PrimitiveBlock, info: &'a osmformat::Info) -> Info<'a> {
500
-        Info {
501
-            block,
502
-            info,
503
-        }
494
+        Info { block, info }
504
     }
495
     }
505
 
496
 
506
     /// Returns the version of this element.
497
     /// Returns the version of this element.
542
     /// Returns the user name.
533
     /// Returns the user name.
543
     pub fn user(&self) -> Option<Result<&'a str>> {
534
     pub fn user(&self) -> Option<Result<&'a str>> {
544
         if self.info.has_user_sid() {
535
         if self.info.has_user_sid() {
545
-            Some(str_from_stringtable(self.block, self.info.get_user_sid() as usize))
536
+            Some(str_from_stringtable(
537
+                self.block,
538
+                self.info.get_user_sid() as usize,
539
+            ))
546
         } else {
540
         } else {
547
             None
541
             None
548
         }
542
         }

+ 32
- 30
src/error.rs Vedi File

18
 }
18
 }
19
 
19
 
20
 pub(crate) fn new_protobuf_error(err: ProtobufError, location: &'static str) -> Error {
20
 pub(crate) fn new_protobuf_error(err: ProtobufError, location: &'static str) -> Error {
21
-    Error(Box::new(ErrorKind::Protobuf{ err, location }))
21
+    Error(Box::new(ErrorKind::Protobuf { err, location }))
22
 }
22
 }
23
 
23
 
24
 /// A type alias for `Result<T, osmpbf::Error>`.
24
 /// A type alias for `Result<T, osmpbf::Error>`.
46
     /// An error for I/O operations.
46
     /// An error for I/O operations.
47
     Io(io::Error),
47
     Io(io::Error),
48
     /// An error that occurs when decoding a protobuf message.
48
     /// An error that occurs when decoding a protobuf message.
49
-    Protobuf{err: ProtobufError, location: &'static str},
49
+    Protobuf {
50
+        err: ProtobufError,
51
+        location: &'static str,
52
+    },
50
     /// The stringtable contains an entry at `index` that could not be decoded to a valid UTF-8
53
     /// The stringtable contains an entry at `index` that could not be decoded to a valid UTF-8
51
     /// string.
54
     /// string.
52
-    StringtableUtf8{err: Utf8Error, index: usize},
55
+    StringtableUtf8 { err: Utf8Error, index: usize },
53
     /// An element contains an out-of-bounds index to the stringtable.
56
     /// An element contains an out-of-bounds index to the stringtable.
54
-    StringtableIndexOutOfBounds{index: usize},
57
+    StringtableIndexOutOfBounds { index: usize },
55
     /// An error that occurs when decoding `Blob`s.
58
     /// An error that occurs when decoding `Blob`s.
56
     Blob(BlobError),
59
     Blob(BlobError),
57
 
60
 
58
     //TODO add UnexpectedPrimitiveBlock
61
     //TODO add UnexpectedPrimitiveBlock
59
-
60
     /// Hints that destructuring should not be exhaustive.
62
     /// Hints that destructuring should not be exhaustive.
61
     ///
63
     ///
62
     /// This enum may grow additional variants, so this makes sure clients
64
     /// This enum may grow additional variants, so this makes sure clients
72
     /// Header size could not be decoded to a u32.
74
     /// Header size could not be decoded to a u32.
73
     InvalidHeaderSize,
75
     InvalidHeaderSize,
74
     /// Blob header is bigger than [`MAX_BLOB_HEADER_SIZE`](blob/MAX_BLOB_HEADER_SIZE.v.html).
76
     /// Blob header is bigger than [`MAX_BLOB_HEADER_SIZE`](blob/MAX_BLOB_HEADER_SIZE.v.html).
75
-    HeaderTooBig{
77
+    HeaderTooBig {
76
         /// Blob header size in bytes.
78
         /// Blob header size in bytes.
77
-        size: u64
79
+        size: u64,
78
     },
80
     },
79
     /// Blob content is bigger than [`MAX_BLOB_MESSAGE_SIZE`](blob/MAX_BLOB_MESSAGE_SIZE.v.html).
81
     /// Blob content is bigger than [`MAX_BLOB_MESSAGE_SIZE`](blob/MAX_BLOB_MESSAGE_SIZE.v.html).
80
-    MessageTooBig{
82
+    MessageTooBig {
81
         /// Blob content size in bytes.
83
         /// Blob content size in bytes.
82
-        size: u64
84
+        size: u64,
83
     },
85
     },
84
     /// The blob is empty because the `raw` and `zlib-data` fields are missing.
86
     /// The blob is empty because the `raw` and `zlib-data` fields are missing.
85
     Empty,
87
     Empty,
88
     __Nonexhaustive,
90
     __Nonexhaustive,
89
 }
91
 }
90
 
92
 
91
-
92
 impl From<io::Error> for Error {
93
 impl From<io::Error> for Error {
93
     fn from(err: io::Error) -> Error {
94
     fn from(err: io::Error) -> Error {
94
         new_error(ErrorKind::Io(err))
95
         new_error(ErrorKind::Io(err))
105
     fn description(&self) -> &str {
106
     fn description(&self) -> &str {
106
         match *self.0 {
107
         match *self.0 {
107
             ErrorKind::Io(ref err) => err.description(),
108
             ErrorKind::Io(ref err) => err.description(),
108
-            ErrorKind::Protobuf{ref err, ..} => err.description(),
109
-            ErrorKind::StringtableUtf8{ref err, ..} => err.description(),
110
-            ErrorKind::StringtableIndexOutOfBounds{..} => "stringtable index out of bounds",
111
-            ErrorKind::Blob(BlobError::InvalidHeaderSize) => "blob header size could not be decoded",
112
-            ErrorKind::Blob(BlobError::HeaderTooBig{..}) => "blob header is too big",
113
-            ErrorKind::Blob(BlobError::MessageTooBig{..}) => "blob message is too big",
109
+            ErrorKind::Protobuf { ref err, .. } => err.description(),
110
+            ErrorKind::StringtableUtf8 { ref err, .. } => err.description(),
111
+            ErrorKind::StringtableIndexOutOfBounds { .. } => "stringtable index out of bounds",
112
+            ErrorKind::Blob(BlobError::InvalidHeaderSize) => {
113
+                "blob header size could not be decoded"
114
+            }
115
+            ErrorKind::Blob(BlobError::HeaderTooBig { .. }) => "blob header is too big",
116
+            ErrorKind::Blob(BlobError::MessageTooBig { .. }) => "blob message is too big",
114
             ErrorKind::Blob(BlobError::Empty) => "blob is missing fields 'raw' and 'zlib_data",
117
             ErrorKind::Blob(BlobError::Empty) => "blob is missing fields 'raw' and 'zlib_data",
115
             _ => unreachable!(),
118
             _ => unreachable!(),
116
         }
119
         }
119
     fn cause(&self) -> Option<&dyn StdError> {
122
     fn cause(&self) -> Option<&dyn StdError> {
120
         match *self.0 {
123
         match *self.0 {
121
             ErrorKind::Io(ref err) => Some(err),
124
             ErrorKind::Io(ref err) => Some(err),
122
-            ErrorKind::Protobuf{ref err, ..} => Some(err),
123
-            ErrorKind::StringtableUtf8{ref err, ..} => Some(err),
124
-            ErrorKind::StringtableIndexOutOfBounds{..} => None,
125
+            ErrorKind::Protobuf { ref err, .. } => Some(err),
126
+            ErrorKind::StringtableUtf8 { ref err, .. } => Some(err),
127
+            ErrorKind::StringtableIndexOutOfBounds { .. } => None,
125
             ErrorKind::Blob(BlobError::InvalidHeaderSize) => None,
128
             ErrorKind::Blob(BlobError::InvalidHeaderSize) => None,
126
-            ErrorKind::Blob(BlobError::HeaderTooBig{..}) => None,
127
-            ErrorKind::Blob(BlobError::MessageTooBig{..}) => None,
129
+            ErrorKind::Blob(BlobError::HeaderTooBig { .. }) => None,
130
+            ErrorKind::Blob(BlobError::MessageTooBig { .. }) => None,
128
             ErrorKind::Blob(BlobError::Empty) => None,
131
             ErrorKind::Blob(BlobError::Empty) => None,
129
             _ => unreachable!(),
132
             _ => unreachable!(),
130
         }
133
         }
135
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136
         match *self.0 {
139
         match *self.0 {
137
             ErrorKind::Io(ref err) => err.fmt(f),
140
             ErrorKind::Io(ref err) => err.fmt(f),
138
-            ErrorKind::Protobuf{ref err, location} => {
141
+            ErrorKind::Protobuf { ref err, location } => {
139
                 write!(f, "protobuf error at '{}': {}", location, err)
142
                 write!(f, "protobuf error at '{}': {}", location, err)
140
-            },
141
-            ErrorKind::StringtableUtf8{ref err, index} => {
143
+            }
144
+            ErrorKind::StringtableUtf8 { ref err, index } => {
142
                 write!(f, "invalid UTF-8 at string table index {}: {}", index, err)
145
                 write!(f, "invalid UTF-8 at string table index {}: {}", index, err)
143
             }
146
             }
144
             ErrorKind::StringtableIndexOutOfBounds { index } => {
147
             ErrorKind::StringtableIndexOutOfBounds { index } => {
145
                 write!(f, "stringtable index out of bounds: {}", index)
148
                 write!(f, "stringtable index out of bounds: {}", index)
146
-            },
149
+            }
147
             ErrorKind::Blob(BlobError::InvalidHeaderSize) => {
150
             ErrorKind::Blob(BlobError::InvalidHeaderSize) => {
148
                 write!(f, "blob header size could not be decoded")
151
                 write!(f, "blob header size could not be decoded")
149
-            },
152
+            }
150
             ErrorKind::Blob(BlobError::HeaderTooBig { size }) => {
153
             ErrorKind::Blob(BlobError::HeaderTooBig { size }) => {
151
                 write!(f, "blob header is too big: {} bytes", size)
154
                 write!(f, "blob header is too big: {} bytes", size)
152
-            },
155
+            }
153
             ErrorKind::Blob(BlobError::MessageTooBig { size }) => {
156
             ErrorKind::Blob(BlobError::MessageTooBig { size }) => {
154
                 write!(f, "blob message is too big: {} bytes", size)
157
                 write!(f, "blob message is too big: {} bytes", size)
155
-            },
158
+            }
156
             ErrorKind::Blob(BlobError::Empty) => {
159
             ErrorKind::Blob(BlobError::Empty) => {
157
                 write!(f, "blob is missing fields 'raw' and 'zlib_data'")
160
                 write!(f, "blob is missing fields 'raw' and 'zlib_data'")
158
-            },
161
+            }
159
             _ => unreachable!(),
162
             _ => unreachable!(),
160
         }
163
         }
161
     }
164
     }
162
 }
165
 }
163
-

+ 3
- 4
src/lib.rs Vedi File

76
 #[cfg(not(feature = "system-libz"))]
76
 #[cfg(not(feature = "system-libz"))]
77
 extern crate inflate;
77
 extern crate inflate;
78
 
78
 
79
-
80
 pub use blob::*;
79
 pub use blob::*;
81
 pub use block::*;
80
 pub use block::*;
82
 pub use dense::*;
81
 pub use dense::*;
85
 pub use mmap_blob::*;
84
 pub use mmap_blob::*;
86
 pub use reader::*;
85
 pub use reader::*;
87
 
86
 
88
-mod error;
89
-mod proto;
90
-pub mod reader;
91
 pub mod blob;
87
 pub mod blob;
92
 pub mod block;
88
 pub mod block;
93
 pub mod dense;
89
 pub mod dense;
94
 pub mod elements;
90
 pub mod elements;
91
+mod error;
95
 pub mod mmap_blob;
92
 pub mod mmap_blob;
93
+mod proto;
94
+pub mod reader;
96
 mod util;
95
 mod util;

+ 15
- 12
src/mmap_blob.rs Vedi File

1
 //! Iterate over blobs from a memory map
1
 //! Iterate over blobs from a memory map
2
 
2
 
3
-extern crate protobuf;
4
 extern crate byteorder;
3
 extern crate byteorder;
5
 extern crate memmap;
4
 extern crate memmap;
5
+extern crate protobuf;
6
 
6
 
7
-use blob::{BlobDecode, ByteOffset, BlobType, decode_blob};
7
+use self::fileformat::BlobHeader;
8
+use blob::{decode_blob, BlobDecode, BlobType, ByteOffset};
8
 use block::{HeaderBlock, PrimitiveBlock};
9
 use block::{HeaderBlock, PrimitiveBlock};
9
 use byteorder::ByteOrder;
10
 use byteorder::ByteOrder;
10
-use error::{BlobError, Result, new_blob_error, new_protobuf_error};
11
+use error::{new_blob_error, new_protobuf_error, BlobError, Result};
11
 use proto::{fileformat, osmformat};
12
 use proto::{fileformat, osmformat};
12
-use self::fileformat::BlobHeader;
13
 use std::fs::File;
13
 use std::fs::File;
14
 use std::path::Path;
14
 use std::path::Path;
15
 use util::parse_message_from_bytes;
15
 use util::parse_message_from_bytes;
16
 
16
 
17
-
18
 /// A read-only memory map.
17
 /// A read-only memory map.
19
 #[derive(Debug)]
18
 #[derive(Debug)]
20
 pub struct Mmap {
19
 pub struct Mmap {
190
 
189
 
191
         match slice.len() {
190
         match slice.len() {
192
             0 => return None,
191
             0 => return None,
193
-            1 ..= 3 => {
192
+            1..=3 => {
194
                 self.last_blob_ok = false;
193
                 self.last_blob_ok = false;
195
                 return Some(Err(new_blob_error(BlobError::InvalidHeaderSize)));
194
                 return Some(Err(new_blob_error(BlobError::InvalidHeaderSize)));
196
-            },
197
-            _ => {},
195
+            }
196
+            _ => {}
198
         }
197
         }
199
 
198
 
200
         let header_size = byteorder::BigEndian::read_u32(slice) as usize;
199
         let header_size = byteorder::BigEndian::read_u32(slice) as usize;
201
 
200
 
202
         if header_size as u64 >= ::blob::MAX_BLOB_HEADER_SIZE {
201
         if header_size as u64 >= ::blob::MAX_BLOB_HEADER_SIZE {
203
             self.last_blob_ok = false;
202
             self.last_blob_ok = false;
204
-            return Some(Err(new_blob_error(BlobError::HeaderTooBig{size: header_size as u64})));
203
+            return Some(Err(new_blob_error(BlobError::HeaderTooBig {
204
+                size: header_size as u64,
205
+            })));
205
         }
206
         }
206
 
207
 
207
         if slice.len() < 4 + header_size {
208
         if slice.len() < 4 + header_size {
208
             self.last_blob_ok = false;
209
             self.last_blob_ok = false;
209
             let io_error = ::std::io::Error::new(
210
             let io_error = ::std::io::Error::new(
210
-                ::std::io::ErrorKind::UnexpectedEof, "content too short for header"
211
+                ::std::io::ErrorKind::UnexpectedEof,
212
+                "content too short for header",
211
             );
213
             );
212
             return Some(Err(io_error.into()));
214
             return Some(Err(io_error.into()));
213
         }
215
         }
217
             Err(e) => {
219
             Err(e) => {
218
                 self.last_blob_ok = false;
220
                 self.last_blob_ok = false;
219
                 return Some(Err(new_protobuf_error(e, "blob header")));
221
                 return Some(Err(new_protobuf_error(e, "blob header")));
220
-            },
222
+            }
221
         };
223
         };
222
 
224
 
223
         let data_size = header.get_datasize() as usize;
225
         let data_size = header.get_datasize() as usize;
226
         if slice.len() < chunk_size {
228
         if slice.len() < chunk_size {
227
             self.last_blob_ok = false;
229
             self.last_blob_ok = false;
228
             let io_error = ::std::io::Error::new(
230
             let io_error = ::std::io::Error::new(
229
-                ::std::io::ErrorKind::UnexpectedEof, "content too short for block data"
231
+                ::std::io::ErrorKind::UnexpectedEof,
232
+                "content too short for block data",
230
             );
233
             );
231
             return Some(Err(io_error.into()));
234
             return Some(Err(io_error.into()));
232
         }
235
         }

+ 3
- 3
src/proto/fileformat.rs Vedi File

1
-// This file is generated by rust-protobuf 2.10.0. Do not edit
1
+// This file is generated by rust-protobuf 2.10.1. Do not edit
2
 // @generated
2
 // @generated
3
 
3
 
4
-// https://github.com/Manishearth/rust-clippy/issues/702
4
+// https://github.com/rust-lang/rust-clippy/issues/702
5
 #![allow(unknown_lints)]
5
 #![allow(unknown_lints)]
6
 #![allow(clippy::all)]
6
 #![allow(clippy::all)]
7
 
7
 
24
 
24
 
25
 /// Generated files are compatible only with the same version
25
 /// Generated files are compatible only with the same version
26
 /// of protobuf runtime.
26
 /// of protobuf runtime.
27
-const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_10_0;
27
+// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_10_1;
28
 
28
 
29
 #[derive(PartialEq,Clone,Default,Debug)]
29
 #[derive(PartialEq,Clone,Default,Debug)]
30
 pub struct Blob {
30
 pub struct Blob {

+ 3
- 3
src/proto/osmformat.rs Vedi File

1
-// This file is generated by rust-protobuf 2.10.0. Do not edit
1
+// This file is generated by rust-protobuf 2.10.1. Do not edit
2
 // @generated
2
 // @generated
3
 
3
 
4
-// https://github.com/Manishearth/rust-clippy/issues/702
4
+// https://github.com/rust-lang/rust-clippy/issues/702
5
 #![allow(unknown_lints)]
5
 #![allow(unknown_lints)]
6
 #![allow(clippy::all)]
6
 #![allow(clippy::all)]
7
 
7
 
24
 
24
 
25
 /// Generated files are compatible only with the same version
25
 /// Generated files are compatible only with the same version
26
 /// of protobuf runtime.
26
 /// of protobuf runtime.
27
-const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_10_0;
27
+// const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_10_1;
28
 
28
 
29
 #[derive(PartialEq,Clone,Default,Debug)]
29
 #[derive(PartialEq,Clone,Default,Debug)]
30
 pub struct HeaderBlock {
30
 pub struct HeaderBlock {

+ 27
- 28
src/reader.rs Vedi File

8
 use std::io::{BufReader, Read};
8
 use std::io::{BufReader, Read};
9
 use std::path::Path;
9
 use std::path::Path;
10
 
10
 
11
-
12
 /// A reader for PBF files that gives access to the stored elements: nodes, ways and relations.
11
 /// A reader for PBF files that gives access to the stored elements: nodes, ways and relations.
13
 #[derive(Clone, Debug)]
12
 #[derive(Clone, Debug)]
14
 pub struct ElementReader<R: Read> {
13
 pub struct ElementReader<R: Read> {
66
     /// # foo().unwrap();
65
     /// # foo().unwrap();
67
     /// ```
66
     /// ```
68
     pub fn for_each<F>(self, mut f: F) -> Result<()>
67
     pub fn for_each<F>(self, mut f: F) -> Result<()>
69
-        where F: for<'a> FnMut(Element<'a>) {
70
-
68
+    where
69
+        F: for<'a> FnMut(Element<'a>),
70
+    {
71
         let blobs = self.blob_iter.collect::<Result<Vec<_>>>()?;
71
         let blobs = self.blob_iter.collect::<Result<Vec<_>>>()?;
72
 
72
 
73
         //TODO do something useful with header blocks
73
         //TODO do something useful with header blocks
74
         for blob in &blobs {
74
         for blob in &blobs {
75
             match blob.decode() {
75
             match blob.decode() {
76
-                Ok(BlobDecode::OsmHeader(_)) | Ok(BlobDecode::Unknown(_)) => {},
76
+                Ok(BlobDecode::OsmHeader(_)) | Ok(BlobDecode::Unknown(_)) => {}
77
                 Ok(BlobDecode::OsmData(block)) => {
77
                 Ok(BlobDecode::OsmData(block)) => {
78
                     block.for_each_element(&mut f);
78
                     block.for_each_element(&mut f);
79
-                },
79
+                }
80
                 Err(e) => return Err(e),
80
                 Err(e) => return Err(e),
81
             }
81
             }
82
         }
82
         }
119
     /// # foo().unwrap();
119
     /// # foo().unwrap();
120
     /// ```
120
     /// ```
121
     pub fn par_map_reduce<MP, RD, ID, T>(self, map_op: MP, identity: ID, reduce_op: RD) -> Result<T>
121
     pub fn par_map_reduce<MP, RD, ID, T>(self, map_op: MP, identity: ID, reduce_op: RD) -> Result<T>
122
-        where MP: for<'a> Fn(Element<'a>) -> T + Sync + Send,
123
-              RD: Fn(T, T) -> T + Sync + Send,
124
-              ID: Fn() -> T + Sync + Send,
125
-              T: Send,
122
+    where
123
+        MP: for<'a> Fn(Element<'a>) -> T + Sync + Send,
124
+        RD: Fn(T, T) -> T + Sync + Send,
125
+        ID: Fn() -> T + Sync + Send,
126
+        T: Send,
126
     {
127
     {
127
         let blobs = self.blob_iter.collect::<Result<Vec<_>>>()?;
128
         let blobs = self.blob_iter.collect::<Result<Vec<_>>>()?;
128
 
129
 
129
-        blobs.into_par_iter().map(|blob| {
130
-            match blob.decode() {
131
-                Ok(BlobDecode::OsmHeader(_)) | Ok(BlobDecode::Unknown(_)) => {
132
-                    Ok(identity())
133
-                },
134
-                Ok(BlobDecode::OsmData(block)) => {
135
-                    Ok(block.elements()
136
-                            .map(|e| map_op(e))
137
-                            .fold(identity(), |a, b| reduce_op(a, b)))
138
-                },
130
+        blobs
131
+            .into_par_iter()
132
+            .map(|blob| match blob.decode() {
133
+                Ok(BlobDecode::OsmHeader(_)) | Ok(BlobDecode::Unknown(_)) => Ok(identity()),
134
+                Ok(BlobDecode::OsmData(block)) => Ok(block
135
+                    .elements()
136
+                    .map(|e| map_op(e))
137
+                    .fold(identity(), |a, b| reduce_op(a, b))),
139
                 Err(e) => Err(e),
138
                 Err(e) => Err(e),
140
-            }
141
-        }).reduce(|| Ok(identity()), |a, b| {
142
-            match (a, b) {
143
-                (Ok(x), Ok(y)) => Ok(reduce_op(x, y)),
144
-                (x, y) => x.and(y),
145
-            }
146
-        })
139
+            })
140
+            .reduce(
141
+                || Ok(identity()),
142
+                |a, b| match (a, b) {
143
+                    (Ok(x), Ok(y)) => Ok(reduce_op(x, y)),
144
+                    (x, y) => x.and(y),
145
+                },
146
+            )
147
     }
147
     }
148
 }
148
 }
149
 
149
 
163
     /// # }
163
     /// # }
164
     /// # foo().unwrap();
164
     /// # foo().unwrap();
165
     /// ```
165
     /// ```
166
-    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self>
167
-    {
166
+    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
168
         Ok(ElementReader {
167
         Ok(ElementReader {
169
             blob_iter: BlobReader::from_path(path)?,
168
             blob_iter: BlobReader::from_path(path)?,
170
         })
169
         })

+ 5
- 4
src/util.rs Vedi File

1
 use protobuf::ProtobufError;
1
 use protobuf::ProtobufError;
2
 use std::io::Read;
2
 use std::io::Read;
3
 
3
 
4
-
5
 pub(crate) fn parse_message_from_bytes<M>(bytes: &[u8]) -> Result<M, ProtobufError>
4
 pub(crate) fn parse_message_from_bytes<M>(bytes: &[u8]) -> Result<M, ProtobufError>
6
-    where M: ::protobuf::Message
5
+where
6
+    M: ::protobuf::Message,
7
 {
7
 {
8
     let mut stream = ::protobuf::CodedInputStream::from_bytes(bytes);
8
     let mut stream = ::protobuf::CodedInputStream::from_bytes(bytes);
9
     let mut message: M = ::protobuf::Message::new();
9
     let mut message: M = ::protobuf::Message::new();
17
 }
17
 }
18
 
18
 
19
 pub(crate) fn parse_message_from_reader<R, M>(reader: &mut R) -> Result<M, ProtobufError>
19
 pub(crate) fn parse_message_from_reader<R, M>(reader: &mut R) -> Result<M, ProtobufError>
20
-    where R: Read,
21
-          M: ::protobuf::Message,
20
+where
21
+    R: Read,
22
+    M: ::protobuf::Message,
22
 {
23
 {
23
     let mut stream = ::protobuf::CodedInputStream::new(reader);
24
     let mut stream = ::protobuf::CodedInputStream::new(reader);
24
     let mut message: M = ::protobuf::Message::new();
25
     let mut message: M = ::protobuf::Message::new();

+ 6
- 8
tests/read.rs Vedi File

3
 use osmpbf::*;
3
 use osmpbf::*;
4
 
4
 
5
 static TEST_FILE_PATHS: [&str; 3] = [
5
 static TEST_FILE_PATHS: [&str; 3] = [
6
-"tests/test.osm.pbf",
7
-"tests/test_nozlib.osm.pbf",
8
-"tests/test_nozlib_nodense.osm.pbf",
6
+    "tests/test.osm.pbf",
7
+    "tests/test_nozlib.osm.pbf",
8
+    "tests/test_nozlib_nodense.osm.pbf",
9
 ];
9
 ];
10
 
10
 
11
 fn approx_eq(a: f64, b: f64) -> bool {
11
 fn approx_eq(a: f64, b: f64) -> bool {
191
     for path in &TEST_FILE_PATHS {
191
     for path in &TEST_FILE_PATHS {
192
         let reader = ElementReader::from_path(path).unwrap();
192
         let reader = ElementReader::from_path(path).unwrap();
193
 
193
 
194
-        let elements = reader.par_map_reduce(
195
-            |_element| 1,
196
-            || 0_usize,
197
-            |a, b| a + b,
198
-        ).unwrap();
194
+        let elements = reader
195
+            .par_map_reduce(|_element| 1, || 0_usize, |a, b| a + b)
196
+            .unwrap();
199
 
197
 
200
         assert_eq!(elements, 5);
198
         assert_eq!(elements, 5);
201
     }
199
     }