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

Modern-Apps.git / scripts / maps / mamaps_build / src / store_part4.rs

store_part4.rs258 lines · 9.9 KiBRaw
1impl WayReader {
2 #[cfg(test)]
3 pub fn open(path: &Path) -> Result<WayReader> {
4 let file = File::open(path)
5 .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
6 Ok(WayReader {
7 inner: WayIn::File(BufReader::with_capacity(1 << 20, file)),
8 last_id: 0,
9 seen: 0,
10 })
11 }
12
13 /// Anonymous twin of [`open`](Self::open): reads the sealed store from
14 /// [`WaySink::finish_anon`], shared by refcount. `path` names nothing —
15 /// it only rides along for error messages.
16 #[cfg(test)]
17 pub fn open_anon(
18 path: &Path,
19 store: std::sync::Arc<tile_build::anon::AnonStore>,
20 ) -> Result<WayReader> {
21 let _ = path;
22 Ok(WayReader {
23 inner: WayIn::Anon { store, at: 0, buf: Vec::new(), used: 0 },
24 last_id: 0,
25 seen: 0,
26 })
27 }
28
29 /// Open whichever backend the sink sealed: the shared anon store when present, else the file
30 /// at `path`. One helper so the four stage-A readers (two ref collectors, lanefill scan,
31 /// materialise) agree.
32 #[cfg(test)]
33 pub fn open_either(
34 path: &Path,
35 store: &Option<std::sync::Arc<tile_build::anon::AnonStore>>,
36 ) -> Result<WayReader> {
37 match store {
38 Some(anon) => Self::open_anon(path, std::sync::Arc::clone(anon)),
39 None => Self::open(path),
40 }
41 }
42
43 /// The next way's id, class, display name, lane count, per-lane turn masks and carriageway,
44 /// with its node refs written into `refs`.
45 ///
46 /// `refs` belongs to the caller and is cleared here, so one allocation serves the whole file.
47 /// Returning a fresh `Vec` instead would be one allocation per classified way, several million
48 /// of them, for a buffer whose contents are dead by the next call — the same reasoning as
49 /// [`WaySink::record`]. The name and masks are returned owned: only a minority of ways carry
50 /// them, so cloning costs nothing next to the geometry.
51 ///
52 /// A record that ends mid-varint or claims more refs than the file holds is a corrupt spill
53 /// rather than a way to skip: this file was written by [`WaySink`] moments ago in the same
54 /// process, so anything unreadable means it is not the file we wrote.
55 #[allow(clippy::type_complexity)]
56 pub fn next(
57 &mut self,
58 refs: &mut Vec<i64>,
59 ) -> Result<
60 Option<(
61 i64,
62 Class,
63 Option<String>,
64 u8,
65 Vec<u16>,
66 Vec<u16>,
67 Carriageway,
68 Option<BuildingAttrs>,
69 )>,
70 > {
71 refs.clear();
72 let Some(delta) = self.uvarint_or_end()? else {
73 return Ok(None);
74 };
75 let id = self.last_id.wrapping_add(zigzag(delta));
76 self.last_id = id;
77 self.seen += 1;
78 let class = unpack(self.uvarint()?);
79 let count = self.uvarint()?;
80 // No `reserve` on `count`: it comes off disk, and a corrupt one would be an allocation
81 // request rather than the error this returns for every other kind of damage. The buffer is
82 // the caller's and is reused across the whole file, so after the first few records it is
83 // already as large as any way needs.
84 let mut previous: i64 = 0;
85 for _ in 0..count {
86 previous = previous.wrapping_add(zigzag(self.uvarint()?));
87 refs.push(previous);
88 }
89 // The name: a byte length, then that many UTF-8 bytes. Zero length is nameless, which is
90 // nearly every way; a corrupt length is the same error as a corrupt ref count.
91 let name_len = self.uvarint()? as usize;
92 let name = if name_len == 0 {
93 None
94 } else {
95 if name_len > 1 << 20 {
96 return err(format!(
97 "a ways spill way claims a {name_len}-byte name, which is corruption"
98 ));
99 }
100 let mut bytes = vec![0u8; name_len];
101 self.read_exact_into(&mut bytes)?;
102 Some(
103 String::from_utf8(bytes)
104 .map_err(|_| Error("a ways spill way name is not UTF-8".to_string()))?,
105 )
106 };
107 // The lane count, then the two turn-mask lists (forward, backward): a count then each u16.
108 let lane_bits = self.uvarint()?;
109 let lane_count = u8::try_from(lane_bits)
110 .map_err(|_| Error("a ways spill way lane count does not fit a byte".to_string()))?;
111 let mut read_masks = || -> Result<Vec<u16>> {
112 let n = self.uvarint()? as usize;
113 if n > tilecodec::mamaps::body::FEATURE_RECORD_LEN * 1024 {
114 return err(format!("a ways spill way claims {n} turn masks, which is corruption"));
115 }
116 let mut v = Vec::with_capacity(n);
117 for _ in 0..n {
118 v.push(u16::try_from(self.uvarint()?).map_err(|_| {
119 Error("a ways spill turn mask does not fit a u16".to_string())
120 })?);
121 }
122 Ok(v)
123 };
124 let turn_fwd = read_masks()?;
125 let turn_bwd = read_masks()?;
126 let carriageway = unpack_carriageway(self.uvarint()?);
127 // The building attributes: a presence byte, then three packed words when set.
128 let building = if self.uvarint()? != 0 {
129 let a = self.uvarint()?;
130 let b = self.uvarint()?;
131 let c = self.uvarint()?;
132 Some(unpack_building(a, b, c))
133 } else {
134 None
135 };
136 Ok(Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)))
137 }
138
139 /// One varint, or `None` if the file ended cleanly on a record boundary.
140 fn uvarint_or_end(&mut self) -> Result<Option<u64>> {
141 let mut value: u64 = 0;
142 let mut shift: u32 = 0;
143 loop {
144 let buf = self.fill_buf()?;
145 if buf.is_empty() {
146 if shift == 0 {
147 return Ok(None);
148 }
149 return err(format!("the ways spill ends mid-varint after {} way(s)", self.seen));
150 }
151 // Consumed in one go per buffer fill rather than a byte at a time: a varint almost
152 // always lies wholly inside the buffer, and there are hundreds of millions of them.
153 let mut used = 0usize;
154 for &byte in buf {
155 used += 1;
156 if shift >= 64 {
157 return err("a ways spill varint is longer than 64 bits".to_string());
158 }
159 value |= ((byte & 0x7f) as u64) << shift;
160 shift += 7;
161 if byte & 0x80 == 0 {
162 self.consume(used);
163 return Ok(Some(value));
164 }
165 }
166 self.consume(used);
167 }
168 }
169
170 /// Peek at the buffered bytes without consuming, filling from the backend first.
171 fn fill_buf(&mut self) -> Result<&[u8]> {
172 match &mut self.inner {
173 #[cfg(test)]
174 WayIn::File(f) => f
175 .fill_buf()
176 .map_err(|e| Error(format!("cannot read the ways spill: {e}"))),
177 #[cfg(test)]
178 WayIn::Anon { store, at, buf, used } => {
179 if *used >= buf.len() {
180 // Refill: read the next window from the store. 1MB like the
181 // file backend's buffer, so the varint loop above behaves
182 // identically.
183 const WINDOW: u64 = 1 << 20;
184 let remaining = store.len().saturating_sub(*at);
185 if remaining == 0 {
186 // Empty view: return what's left (nothing).
187 buf.clear();
188 *used = 0;
189 return Ok(&[]);
190 }
191 let take = remaining.min(WINDOW) as usize;
192 buf.resize(take, 0);
193 store.read_at(*at, &mut buf[..]).map_err(|e| {
194 Error(format!("cannot read the anon ways spill: {e}"))
195 })?;
196 *at += take as u64;
197 *used = 0;
198 }
199 Ok(&buf[*used..])
200 }
201 WayIn::Slice { buf, used } => Ok(&buf[*used..]),
202 }
203 }
204
205 fn consume(&mut self, n: usize) {
206 match &mut self.inner {
207 #[cfg(test)]
208 WayIn::File(f) => f.consume(n),
209 #[cfg(test)]
210 WayIn::Anon { used, .. } => *used += n,
211 WayIn::Slice { used, .. } => *used += n,
212 }
213 }
214
215 fn uvarint(&mut self) -> Result<u64> {
216 match self.uvarint_or_end()? {
217 Some(value) => Ok(value),
218 None => err(format!("the ways spill ends mid-record after {} way(s)", self.seen)),
219 }
220 }
221
222 /// Exactly `bytes.len()` bytes from the cursor, for the name field above.
223 fn read_exact_into(&mut self, bytes: &mut [u8]) -> Result<()> {
224 let mut at = 0usize;
225 while at < bytes.len() {
226 let buf = self.fill_buf()?;
227 if buf.is_empty() {
228 return err(format!(
229 "the ways spill ends mid-name after {} way(s)",
230 self.seen
231 ));
232 }
233 let take = (bytes.len() - at).min(buf.len());
234 bytes[at..at + take].copy_from_slice(&buf[..take]);
235 self.consume(take);
236 at += take;
237 }
238 Ok(())
239 }
240}
241
242fn put_uvarint(out: &mut Vec<u8>, mut value: u64) {
243 loop {
244 let byte = (value & 0x7f) as u8;
245 value >>= 7;
246 if value == 0 {
247 out.push(byte);
248 return;
249 }
250 out.push(byte | 0x80);
251 }
252}
253
254/// Zigzagged, so a gap that happens to run backwards costs one bit rather than ten bytes.
255/// [`zigzag`] is the decoder, already in `osm_ingest` because the PBF itself is encoded this way.
256fn put_svarint(out: &mut Vec<u8>, value: i64) {
257 put_uvarint(out, ((value << 1) ^ (value >> 63)) as u64);
258}