geolith_tiles_builder/sort/
chunk.rs1use std::fs::File;
11use std::io::{BufReader, BufWriter, Read, Write};
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
15
16use lz4_flex::frame::{FrameDecoder, FrameEncoder};
17
18use crate::sort::entry::SortEntry;
19use geolith::error::{GeolithError, Result};
20
21const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
23
24const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
28
29const READ_BUF_SIZE: usize = 1024 * 1024;
34
35pub struct ChunkSink {
40 dir: PathBuf,
42 chunk_paths: Vec<PathBuf>,
44 counter: Arc<AtomicU32>,
46}
47
48impl ChunkSink {
49 pub fn new(dir: PathBuf) -> Result<Self> {
58 std::fs::create_dir_all(&dir)?;
59 Ok(Self {
60 dir,
61 chunk_paths: Vec::new(),
62 counter: Arc::new(AtomicU32::new(0)),
63 })
64 }
65
66 pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
72 Self {
73 dir,
74 chunk_paths: Vec::new(),
75 counter,
76 }
77 }
78
79 pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
88 let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
89 let path = self.dir.join(format!("chunk_{id:06}.lz4"));
90
91 let file = File::create(&path)?;
92 let buf = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
93 let mut encoder = FrameEncoder::new(buf);
94
95 for entry in entries {
96 let bytes = entry.to_bytes()?;
97 let len = length_prefix(bytes.len())?;
98 encoder.write_all(&len.to_le_bytes())?;
99 encoder.write_all(&bytes)?;
100 }
101
102 encoder.finish()?;
103 self.chunk_paths.push(path.clone());
104 Ok(path)
105 }
106
107 #[must_use]
109 pub fn chunk_paths(&self) -> &[PathBuf] {
110 &self.chunk_paths
111 }
112
113 #[must_use]
115 pub const fn chunk_count(&self) -> usize {
116 self.chunk_paths.len()
117 }
118
119 #[must_use]
121 pub fn into_chunk_paths(self) -> Vec<PathBuf> {
122 self.chunk_paths
123 }
124
125 pub fn cleanup(&self) -> Result<()> {
131 for path in &self.chunk_paths {
132 if path.exists() {
133 std::fs::remove_file(path)?;
134 }
135 }
136 Ok(())
137 }
138}
139
140pub struct SortBuffer {
143 entries: Vec<SortEntry>,
144 approx_bytes: usize,
146 max_bytes: usize,
148}
149
150impl SortBuffer {
151 #[must_use]
153 pub fn new() -> Self {
154 Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
155 }
156
157 #[must_use]
159 pub fn with_max_bytes(max_bytes: usize) -> Self {
160 Self {
161 entries: Vec::with_capacity(1024),
162 approx_bytes: 0,
163 max_bytes,
164 }
165 }
166
167 #[inline]
171 pub fn push(&mut self, entry: SortEntry) -> bool {
172 self.approx_bytes +=
174 58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
175 self.entries.push(entry);
176 self.approx_bytes >= self.max_bytes
177 }
178
179 pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
187 if self.entries.is_empty() {
188 return Ok(());
189 }
190 self.entries.sort_unstable();
191 sink.write_chunk(&self.entries)?;
192 self.entries.clear();
193 self.approx_bytes = 0;
194 Ok(())
195 }
196
197 #[must_use]
199 pub const fn is_empty(&self) -> bool {
200 self.entries.is_empty()
201 }
202
203 #[must_use]
205 pub const fn len(&self) -> usize {
206 self.entries.len()
207 }
208}
209
210impl Default for SortBuffer {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
226 let file = File::open(path)?;
227 let buf = BufReader::with_capacity(READ_BUF_SIZE, file);
228 let mut decoder = FrameDecoder::new(buf);
229 let mut entries = Vec::with_capacity(1024);
230 let mut len_buf = [0u8; 4];
231 let mut data_buf = Vec::with_capacity(256);
232
233 loop {
234 match decoder.read_exact(&mut len_buf) {
235 Ok(()) => {}
236 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
237 Err(e) => return Err(e.into()),
238 }
239 let len = u32::from_le_bytes(len_buf) as usize;
240 if data_buf.len() < len {
241 data_buf.resize(len, 0);
242 }
243 decoder.read_exact(&mut data_buf[..len])?;
244 let entry = SortEntry::from_bytes(&data_buf[..len])?;
245 entries.push(entry);
246 }
247
248 Ok(entries)
249}
250
251pub struct ChunkReader {
256 decoder: FrameDecoder<BufReader<File>>,
257 peeked: Option<SortEntry>,
259 exhausted: bool,
261 data_buf: Vec<u8>,
263}
264
265impl ChunkReader {
266 pub fn open(path: &Path) -> Result<Self> {
273 let file = File::open(path)?;
274 let buf = BufReader::with_capacity(READ_BUF_SIZE, file);
275 let decoder = FrameDecoder::new(buf);
276 let mut reader = Self {
277 decoder,
278 peeked: None,
279 exhausted: false,
280 data_buf: Vec::with_capacity(256),
281 };
282 reader.advance()?;
283 Ok(reader)
284 }
285
286 #[inline]
288 #[must_use]
289 pub const fn peek(&self) -> Option<&SortEntry> {
290 self.peeked.as_ref()
291 }
292
293 pub fn take(&mut self) -> Result<Option<SortEntry>> {
299 let entry = self.peeked.take();
300 if entry.is_some() {
301 self.advance()?;
302 }
303 Ok(entry)
304 }
305
306 #[inline]
308 #[must_use]
309 pub const fn is_exhausted(&self) -> bool {
310 self.exhausted
311 }
312
313 fn advance(&mut self) -> Result<()> {
315 if self.exhausted {
316 return Ok(());
317 }
318 let mut len_buf = [0u8; 4];
319 match self.decoder.read_exact(&mut len_buf) {
320 Ok(()) => {}
321 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
322 self.exhausted = true;
323 return Ok(());
324 }
325 Err(e) => return Err(e.into()),
326 }
327 let len = u32::from_le_bytes(len_buf) as usize;
328 if self.data_buf.len() < len {
331 self.data_buf.resize(len, 0);
332 }
333 self.decoder.read_exact(&mut self.data_buf[..len])?;
334 let entry = SortEntry::from_bytes(&self.data_buf[..len])?;
335 self.peeked = Some(entry);
336 Ok(())
337 }
338}
339
340fn length_prefix(len: usize) -> Result<u32> {
342 u32::try_from(len).map_err(|_| {
343 GeolithError::Io(std::io::Error::new(
344 std::io::ErrorKind::InvalidData,
345 format!("sort entry of {len} bytes exceeds the u32 length prefix"),
346 ))
347 })
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 #[test]
355 fn an_entry_length_must_fit_the_u32_prefix() {
356 assert_eq!(
357 length_prefix(4_294_967_295).expect("u32::MAX fits"),
358 u32::MAX
359 );
360 assert!(length_prefix(4_294_967_296).is_err());
361 }
362 use std::sync::Arc;
363
364 use geolith::layer::Layer;
365 use geolith::tile::feature::{GeomType, TileFeature};
366
367 fn make_entry(key: u64) -> SortEntry {
368 SortEntry::new(
369 key,
370 TileFeature {
371 layer: Layer::Buildings,
372 id: key,
373 geom_type: GeomType::Polygon,
374 geometry: vec![9, 0, 0],
375 properties: Arc::new(vec![]),
376 sort_key: 0,
377 },
378 )
379 }
380
381 #[test]
382 fn roundtrip_chunk_write_read() {
383 let dir = tempfile::tempdir().expect("tmpdir");
384 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
385
386 let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
387 entries.sort_unstable();
388 sink.write_chunk(&entries).expect("write");
389
390 let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
391 assert_eq!(read_back.len(), 100);
392 for window in read_back.windows(2) {
394 assert!(window[0].key <= window[1].key);
395 }
396 }
397
398 #[test]
399 fn sort_buffer_flush_threshold() {
400 let mut buf = SortBuffer::with_max_bytes(100);
401 let mut full = false;
402 for i in 0..1000 {
403 if buf.push(make_entry(i)) {
404 full = true;
405 break;
406 }
407 }
408 assert!(full, "buffer should fill up");
409 assert!(!buf.is_empty());
410 }
411
412 #[test]
413 fn chunk_reader_streaming() {
414 let dir = tempfile::tempdir().expect("tmpdir");
415 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
416
417 let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
418 sink.write_chunk(&entries).expect("write");
419
420 let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
421 let mut count = 0;
422 while !reader.is_exhausted() {
423 let entry = reader.take().expect("take");
424 if entry.is_some() {
425 count += 1;
426 }
427 }
428 assert_eq!(count, 50);
429 }
430}