Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / proto.rs

proto.rs300 lines · 8.8 KiBRaw
1//! Protobuf wire-format decoder — just enough of it to read an `.osm.pbf`.
2//!
3//! The mirror image of `maps/src/main/rust/src/mvt.rs`, which hand-rolls a
4//! protobuf *encoder* for vector tiles. The `.osm.pbf` schema subset we need is
5//! small and fixed (see `pbf.rs`), so a generated-code dependency would buy
6//! nothing and would cost the offline build.
7
8use std::fmt;
9
10pub type Result<T> = std::result::Result<T, Error>;
11
12#[derive(Debug)]
13pub struct Error(pub String);
14
15impl fmt::Display for Error {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 f.write_str(&self.0)
18 }
19}
20
21impl std::error::Error for Error {}
22
23pub fn err<T>(msg: impl Into<String>) -> Result<T> {
24 Err(Error(msg.into()))
25}
26
27// Wire types.
28pub const WIRE_VARINT: u8 = 0;
29pub const WIRE_I64: u8 = 1;
30pub const WIRE_BYTES: u8 = 2;
31pub const WIRE_I32: u8 = 5;
32
33/// Cursor over one protobuf message body.
34#[derive(Clone)]
35pub struct Reader<'a> {
36 buf: &'a [u8],
37 pos: usize,
38}
39
40impl<'a> Reader<'a> {
41 pub fn new(buf: &'a [u8]) -> Self {
42 Reader { buf, pos: 0 }
43 }
44
45 #[inline]
46 pub fn at_end(&self) -> bool {
47 self.pos >= self.buf.len()
48 }
49
50 /// Next `(field_number, wire_type)`, or `None` at end of message.
51 pub fn next_field(&mut self) -> Result<Option<(u32, u8)>> {
52 if self.at_end() {
53 return Ok(None);
54 }
55 let key = self.uvarint()?;
56 let field = (key >> 3) as u32;
57 if field == 0 {
58 return err("protobuf field number 0");
59 }
60 Ok(Some((field, (key & 7) as u8)))
61 }
62
63 pub fn uvarint(&mut self) -> Result<u64> {
64 let mut val: u64 = 0;
65 let mut shift = 0u32;
66 loop {
67 if self.pos >= self.buf.len() {
68 return err("truncated varint");
69 }
70 let b = self.buf[self.pos];
71 self.pos += 1;
72 if shift >= 64 {
73 return err("varint longer than 64 bits");
74 }
75 val |= ((b & 0x7F) as u64) << shift;
76 if b & 0x80 == 0 {
77 return Ok(val);
78 }
79 shift += 7;
80 }
81 }
82
83 /// `sint32`/`sint64`: zigzag-decoded varint.
84 pub fn svarint(&mut self) -> Result<i64> {
85 Ok(zigzag(self.uvarint()?))
86 }
87
88 /// `int32`/`int64`: two's-complement varint (negatives are 10 bytes).
89 pub fn ivarint(&mut self) -> Result<i64> {
90 Ok(self.uvarint()? as i64)
91 }
92
93 /// Length-delimited payload, borrowed from the underlying buffer.
94 pub fn bytes(&mut self) -> Result<&'a [u8]> {
95 let len = self.uvarint()? as usize;
96 let end = self
97 .pos
98 .checked_add(len)
99 .filter(|e| *e <= self.buf.len())
100 .ok_or_else(|| Error("length-delimited field runs past end".into()))?;
101 let out = &self.buf[self.pos..end];
102 self.pos = end;
103 Ok(out)
104 }
105
106 /// Skip a field of the given wire type. Unknown fields must be skippable or
107 /// a schema addition upstream would break the reader.
108 pub fn skip(&mut self, wire: u8) -> Result<()> {
109 match wire {
110 WIRE_VARINT => {
111 self.uvarint()?;
112 }
113 WIRE_I64 => self.advance(8)?,
114 WIRE_BYTES => {
115 self.bytes()?;
116 }
117 WIRE_I32 => self.advance(4)?,
118 other => return err(format!("unsupported protobuf wire type {other}")),
119 }
120 Ok(())
121 }
122
123 fn advance(&mut self, n: usize) -> Result<()> {
124 let end = self
125 .pos
126 .checked_add(n)
127 .filter(|e| *e <= self.buf.len())
128 .ok_or_else(|| Error("fixed-width field runs past end".into()))?;
129 self.pos = end;
130 Ok(())
131 }
132
133 pub fn fixed32(&mut self) -> Result<u32> {
134 self.advance(4)?;
135 let s = &self.buf[self.pos - 4..self.pos];
136 Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
137 }
138}
139
140#[inline]
141pub fn zigzag(v: u64) -> i64 {
142 ((v >> 1) as i64) ^ -((v & 1) as i64)
143}
144
145/// Decode a packed `repeated uint64`/`int64` payload, appending to `out`.
146pub fn packed_uvarint(payload: &[u8], out: &mut Vec<u64>) -> Result<()> {
147 let mut r = Reader::new(payload);
148 while !r.at_end() {
149 out.push(r.uvarint()?);
150 }
151 Ok(())
152}
153
154/// Decode a packed `repeated uint32`/`int32` payload, appending to `out`.
155pub fn packed_u32(payload: &[u8], out: &mut Vec<u32>) -> Result<()> {
156 let mut r = Reader::new(payload);
157 while !r.at_end() {
158 out.push(r.uvarint()? as u32);
159 }
160 Ok(())
161}
162
163/// Decode a packed `repeated sint64` payload (zigzag), appending to `out`.
164pub fn packed_svarint(payload: &[u8], out: &mut Vec<i64>) -> Result<()> {
165 let mut r = Reader::new(payload);
166 while !r.at_end() {
167 out.push(r.svarint()?);
168 }
169 Ok(())
170}
171
172/// Decode a packed `repeated sint64` payload as a running delta sum. The PBF
173/// format delta-encodes ids and coordinates this way.
174pub fn packed_delta(payload: &[u8], out: &mut Vec<i64>) -> Result<()> {
175 let mut r = Reader::new(payload);
176 let mut acc: i64 = 0;
177 while !r.at_end() {
178 acc = acc.wrapping_add(r.svarint()?);
179 out.push(acc);
180 }
181 Ok(())
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 fn uvarint_bytes(mut v: u64) -> Vec<u8> {
189 let mut out = Vec::new();
190 loop {
191 let b = (v & 0x7F) as u8;
192 v >>= 7;
193 if v == 0 {
194 out.push(b);
195 return out;
196 }
197 out.push(b | 0x80);
198 }
199 }
200
201 #[test]
202 fn uvarint_round_trips_at_byte_boundaries() {
203 // 1/2/3/.../10-byte encodings, including each 7-bit boundary.
204 let mut cases = vec![0u64, 1, 127, 128, 129, 16383, 16384, u64::MAX];
205 for shift in 0..64 {
206 cases.push(1u64 << shift);
207 cases.push((1u64 << shift).wrapping_sub(1));
208 }
209 for v in cases {
210 let enc = uvarint_bytes(v);
211 let mut r = Reader::new(&enc);
212 assert_eq!(r.uvarint().unwrap(), v, "value {v}");
213 assert!(r.at_end(), "value {v} left {} bytes", enc.len());
214 }
215 assert_eq!(uvarint_bytes(127).len(), 1);
216 assert_eq!(uvarint_bytes(128).len(), 2);
217 assert_eq!(uvarint_bytes(u64::MAX).len(), 10);
218 }
219
220 #[test]
221 fn truncated_varint_is_an_error() {
222 let mut r = Reader::new(&[0x80, 0x80]);
223 assert!(r.uvarint().is_err());
224 }
225
226 #[test]
227 fn zigzag_matches_the_protobuf_spec() {
228 assert_eq!(zigzag(0), 0);
229 assert_eq!(zigzag(1), -1);
230 assert_eq!(zigzag(2), 1);
231 assert_eq!(zigzag(3), -2);
232 assert_eq!(zigzag(4294967294), 2147483647);
233 assert_eq!(zigzag(4294967295), -2147483648);
234 // Full round trip through the encoder's rule: (n << 1) ^ (n >> 63).
235 for n in [i64::MIN, -1, 0, 1, i64::MAX, -123456789, 123456789] {
236 let enc = ((n << 1) ^ (n >> 63)) as u64;
237 assert_eq!(zigzag(enc), n, "value {n}");
238 }
239 }
240
241 #[test]
242 fn negative_int64_uses_ten_bytes() {
243 // int64 (not sint64) encodes -1 as ten 0xFF-ish bytes.
244 let enc = uvarint_bytes(-1i64 as u64);
245 assert_eq!(enc.len(), 10);
246 let mut r = Reader::new(&enc);
247 assert_eq!(r.ivarint().unwrap(), -1);
248 }
249
250 #[test]
251 fn packed_delta_accumulates() {
252 // sint64 deltas 10, 5, -3 -> 10, 15, 12
253 let mut payload = Vec::new();
254 for d in [10i64, 5, -3] {
255 payload.extend(uvarint_bytes(((d << 1) ^ (d >> 63)) as u64));
256 }
257 let mut out = Vec::new();
258 packed_delta(&payload, &mut out).unwrap();
259 assert_eq!(out, vec![10, 15, 12]);
260 }
261
262 #[test]
263 fn skip_walks_past_unknown_fields() {
264 // field 1 varint = 300, field 2 bytes = "hi", field 3 i32, field 4 i64,
265 // then field 5 varint = 7 which we actually read.
266 let mut msg = Vec::new();
267 msg.push(1 << 3 | WIRE_VARINT);
268 msg.extend(uvarint_bytes(300));
269 msg.push(2 << 3 | WIRE_BYTES);
270 msg.extend(uvarint_bytes(2));
271 msg.extend_from_slice(b"hi");
272 msg.push(3 << 3 | WIRE_I32);
273 msg.extend_from_slice(&[1, 2, 3, 4]);
274 msg.push(4 << 3 | WIRE_I64);
275 msg.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
276 msg.push(5 << 3 | WIRE_VARINT);
277 msg.extend(uvarint_bytes(7));
278
279 let mut r = Reader::new(&msg);
280 let mut seen = None;
281 while let Some((field, wire)) = r.next_field().unwrap() {
282 if field == 5 {
283 seen = Some(r.uvarint().unwrap());
284 } else {
285 r.skip(wire).unwrap();
286 }
287 }
288 assert_eq!(seen, Some(7));
289 }
290
291 #[test]
292 fn length_delimited_past_end_is_an_error() {
293 let mut msg = vec![1 << 3 | WIRE_BYTES];
294 msg.extend(uvarint_bytes(99));
295 msg.extend_from_slice(b"short");
296 let mut r = Reader::new(&msg);
297 r.next_field().unwrap();
298 assert!(r.bytes().is_err());
299 }
300}