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

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

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