Skip to main content

readcon_core/
compression.rs

1//=============================================================================
2// Transparent compression support
3//=============================================================================
4
5use std::io::{self, Read, Write};
6use std::path::Path;
7
8/// zlib/gzip level used for CON payloads.
9///
10/// This is [`flate2::Compression::default`] (level 6). The historical
11/// campaign median of 0.120 s was this level applied to a frame whose
12/// coordinates had already been cleared; the first sample of that run,
13/// still holding the lattice, was 0.371 s.
14pub const GZIP_LEVEL: u32 = 6;
15
16/// zstd level used for CON payloads. Level 3 is the zstd CLI default.
17pub const ZSTD_LEVEL: i32 = 3;
18
19/// Detected compression format based on magic bytes.
20///
21/// `Zstd` is only constructed when the `zstd` Cargo feature is enabled.
22/// Builds without the feature treat `.zst` files as opaque bytes and
23/// return an error from [`read_file_contents`] indicating the feature
24/// is required.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Compression {
27    None,
28    Gzip,
29    /// zstd data: a frame (`28 b5 2f fd`) or a skippable frame
30    /// (`5? 2a 4d 18`, RFC 8878). Build with `--features zstd`.
31    Zstd,
32}
33
34/// A Zstandard frame or a skippable frame, in the byte order on disk.
35///
36/// RFC 8878 gives a frame the magic `28 b5 2f fd` and a skippable frame
37/// one of `50 2a 4d 18` through `5f 2a 4d 18`. A file from `pzstd` can
38/// start with the skippable frame.
39fn is_zstd_magic(bytes: &[u8]) -> bool {
40    bytes.len() >= 4
41        && (bytes[..4] == [0x28, 0xb5, 0x2f, 0xfd]
42            || ((0x50..=0x5f).contains(&bytes[0])
43                && bytes[1] == 0x2a
44                && bytes[2] == 0x4d
45                && bytes[3] == 0x18))
46}
47
48/// Detect compression format from the first bytes of a file.
49///
50/// - `1f 8b` = gzip
51/// - `28 b5 2f fd` = zstd frame
52/// - `5? 2a 4d 18` = zstd skippable frame
53/// - Otherwise = uncompressed
54pub fn detect_compression(bytes: &[u8]) -> Compression {
55    if bytes.len() >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b {
56        return Compression::Gzip;
57    }
58    if is_zstd_magic(bytes) {
59        return Compression::Zstd;
60    }
61    Compression::None
62}
63
64/// Detect compression format from a file extension.
65///
66/// Returns `Compression::Gzip` for `.gz`, `Compression::Zstd` for
67/// `.zst`, `Compression::None` otherwise.
68pub fn detect_compression_from_extension(path: &Path) -> Compression {
69    match path.extension().and_then(|e| e.to_str()) {
70        Some("gz") => Compression::Gzip,
71        Some("zst") => Compression::Zstd,
72        _ => Compression::None,
73    }
74}
75
76/// Size in bytes from which [`read_file_contents`] maps an uncompressed file.
77/// A smaller one is read into a `String`.
78pub const MMAP_THRESHOLD: u64 = 64 * 1024;
79
80/// Reads file contents, decompressing if needed.
81///
82/// Detection strategy:
83/// 1. Read the first 4 bytes to check magic bytes.
84/// 2. If gzip or zstd: decompress entire file to a String.
85/// 3. If uncompressed and smaller than [`MMAP_THRESHOLD`]: read the rest into a String.
86/// 4. If uncompressed and at least [`MMAP_THRESHOLD`]: memory-mapped I/O.
87///
88/// The path is opened once and every byte comes from that handle, so a
89/// pipe works and a file replaced during the call is not mixed in.
90pub fn read_file_contents(path: &Path) -> Result<FileContents, Box<dyn std::error::Error>> {
91    read_file_contents_detected(path).map(|(contents, _)| contents)
92}
93
94/// [`read_file_contents`], also returning the compression it detected.
95pub fn read_file_contents_detected(
96    path: &Path,
97) -> Result<(FileContents, Compression), Box<dyn std::error::Error>> {
98    read_contents(path, true)
99}
100
101/// [`read_file_contents`] as one owned `String`. An uncompressed file is
102/// read into it at any size instead of being mapped, so the text is held
103/// once and later changes to the file do not reach it.
104pub fn read_file_text(path: &Path) -> Result<String, Box<dyn std::error::Error>> {
105    match read_contents(path, false)?.0 {
106        FileContents::Owned(text) => Ok(text),
107        FileContents::Mapped(_) => unreachable!("read_contents maps only when asked to"),
108    }
109}
110
111/// Bytes of one file, mapped when a plain file is large enough.
112///
113/// Compressed input is decoded into a buffer. A plain file under 64 KiB,
114/// or anything that is not a regular file, is read into a buffer. A larger
115/// plain file stays mapped for the parse and is not copied. The bytes are
116/// not checked as UTF-8; the parser reports a bad byte when it reaches it.
117pub enum ByteSource {
118    Buf(Vec<u8>),
119    Map(memmap2::Mmap),
120}
121
122impl ByteSource {
123    pub fn as_slice(&self) -> &[u8] {
124        match self {
125            ByteSource::Buf(bytes) => bytes,
126            ByteSource::Map(map) => map,
127        }
128    }
129}
130
131/// Load `path` for a parse. See [`ByteSource`].
132pub fn read_bytes_owned(path: &Path) -> Result<ByteSource, Box<dyn std::error::Error>> {
133    let mut file = std::fs::File::open(path)?;
134    let metadata = file.metadata()?;
135    let mut magic = [0u8; 4];
136    let n = (&mut file).take(4).read(&mut magic)?;
137    match detect_compression(&magic[..n]) {
138        Compression::None if metadata.is_file() && metadata.len() >= MMAP_THRESHOLD => {
139            let map = unsafe { memmap2::Mmap::map(&file)? };
140            Ok(ByteSource::Map(map))
141        }
142        Compression::None => {
143            let mut bytes = Vec::with_capacity(metadata.len().saturating_add(4) as usize);
144            bytes.extend_from_slice(&magic[..n]);
145            file.read_to_end(&mut bytes)?;
146            Ok(ByteSource::Buf(bytes))
147        }
148        Compression::Gzip | Compression::Zstd => {
149            drop(file);
150            Ok(ByteSource::Buf(read_file_bytes(path)?))
151        }
152    }
153}
154
155/// File bytes in one read when the file is not compressed.
156///
157/// Gzip and zstd still go through the decoder. Plain text skips the
158/// four-byte probe and the UTF-8 `String` allocation.
159pub fn read_file_bytes(path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
160    let bytes = std::fs::read(path)?;
161    let magic = &bytes[..bytes.len().min(4)];
162    match detect_compression(magic) {
163        Compression::None => Ok(bytes),
164        Compression::Gzip => gunzip_all(&bytes).map_err(Into::into),
165        Compression::Zstd => {
166            #[cfg(feature = "zstd")]
167            {
168                zstd_decode_all(&bytes).map_err(Into::into)
169            }
170            #[cfg(not(feature = "zstd"))]
171            {
172                let _ = bytes;
173                Err(zstd_unsupported().into())
174            }
175        }
176    }
177}
178
179fn read_contents(
180    path: &Path,
181    map_large: bool,
182) -> Result<(FileContents, Compression), Box<dyn std::error::Error>> {
183    let file = std::fs::File::open(path)?;
184    let metadata = file.metadata()?;
185
186    // gzip needs 2 magic bytes and zstd needs 4. They stay in front of the
187    // rest of the stream, since a pipe cannot seek back.
188    let mut magic = Vec::with_capacity(4);
189    (&file).take(4).read_to_end(&mut magic)?;
190    let compression = detect_compression(&magic);
191    let mut stream = magic.as_slice().chain(&file);
192
193    let contents = match compression {
194        Compression::Gzip => {
195            // Every gzip member, in order (CON-compress.1, D16). A file
196            // this crate wrote stores member starts in the first extra
197            // field and those slices are inflated together. Any other
198            // gzip stream, including one member and a foreign multi-member
199            // file, stays on the serial decoder.
200            let mut bytes = Vec::new();
201            stream.read_to_end(&mut bytes)?;
202            let plain = gunzip_all(&bytes)?;
203            let contents = String::from_utf8(plain).map_err(|err| {
204                io::Error::new(io::ErrorKind::InvalidData, err.utf8_error().to_string())
205            })?;
206            FileContents::Owned(contents)
207        }
208        Compression::Zstd => {
209            #[cfg(feature = "zstd")]
210            {
211                let mut bytes = Vec::new();
212                stream.read_to_end(&mut bytes)?;
213                let plain = zstd_decode_all(&bytes)?;
214                let contents = String::from_utf8(plain).map_err(|err| {
215                    io::Error::new(io::ErrorKind::InvalidData, err.utf8_error().to_string())
216                })?;
217                FileContents::Owned(contents)
218            }
219            #[cfg(not(feature = "zstd"))]
220            {
221                return Err(zstd_unsupported().into());
222            }
223        }
224        Compression::None if metadata.len() < MMAP_THRESHOLD => {
225            let mut bytes = Vec::with_capacity(metadata.len() as usize);
226            stream.read_to_end(&mut bytes)?;
227            let contents = String::from_utf8(bytes).map_err(|_| {
228                io::Error::new(
229                    io::ErrorKind::InvalidData,
230                    "stream did not contain valid UTF-8",
231                )
232            })?;
233            FileContents::Owned(contents)
234        }
235        Compression::None if map_large => {
236            let mmap = unsafe { memmap2::Mmap::map(&file)? };
237            FileContents::Mapped(mmap)
238        }
239        Compression::None => {
240            let mut bytes = Vec::with_capacity(metadata.len() as usize);
241            stream.read_to_end(&mut bytes)?;
242            // The message `as_str` gives for the same bytes when mapped.
243            FileContents::Owned(String::from_utf8(bytes).map_err(|e| e.utf8_error())?)
244        }
245    };
246    Ok((contents, compression))
247}
248
249#[cfg(not(feature = "zstd"))]
250fn zstd_unsupported() -> io::Error {
251    io::Error::new(
252        io::ErrorKind::Unsupported,
253        "zstd-compressed input detected; rebuild readcon-core with --features zstd",
254    )
255}
256
257/// The bytes of `path` as one stream, decompressed while it is read.
258///
259/// Compression is detected by magic bytes, as in [`read_file_contents`],
260/// and every gzip member is read in order.
261/// The only memory used is the decoder's own buffers, so it does not grow
262/// with the file.
263pub fn open_decoded(path: &Path) -> Result<Box<dyn Read + Send>, Box<dyn std::error::Error>> {
264    let mut file = std::fs::File::open(path)?;
265    let mut magic = Vec::with_capacity(4);
266    (&mut file).take(4).read_to_end(&mut magic)?;
267    let compression = detect_compression(&magic);
268    let stream = io::Cursor::new(magic).chain(file);
269    Ok(match compression {
270        Compression::Gzip => Box::new(flate2::read::MultiGzDecoder::new(stream)),
271        #[cfg(feature = "zstd")]
272        Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(stream)?),
273        #[cfg(not(feature = "zstd"))]
274        Compression::Zstd => return Err(zstd_unsupported().into()),
275        Compression::None => Box::new(stream),
276    })
277}
278
279/// Holds file contents either as an owned String or a memory-mapped region.
280pub enum FileContents {
281    Owned(String),
282    Mapped(memmap2::Mmap),
283}
284
285impl FileContents {
286    pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
287        match self {
288            FileContents::Owned(s) => Ok(s.as_str()),
289            FileContents::Mapped(m) => std::str::from_utf8(m),
290        }
291    }
292
293    pub fn as_bytes(&self) -> &[u8] {
294        match self {
295            FileContents::Owned(s) => s.as_bytes(),
296            FileContents::Mapped(m) => m,
297        }
298    }
299
300    /// Like [`Self::as_str`], but validates mapped files in newline-aligned
301    /// slices (in parallel with the `parallel` feature).
302    pub fn as_str_sliced(&self) -> Result<&str, std::str::Utf8Error> {
303        match self {
304            FileContents::Owned(s) => Ok(s.as_str()),
305            FileContents::Mapped(m) => crate::frame_index::validate_utf8_sliced(m),
306        }
307    }
308}
309
310/// Mapped bytes between two releases of the pages already read.
311const RELEASE_STEP: usize = 32 << 20;
312
313/// The text of one file, read from the front.
314///
315/// With `map`, an uncompressed file of 64 KiB or more stays mapped, and
316/// [`Self::release_before`] advises `MADV_DONTNEED` for the pages before the
317/// read position. On Linux that drops the file pages, so resident memory
318/// stays near [`RELEASE_STEP`] instead of the file size. macOS gets the same
319/// call, but its `MADV_DONTNEED` does not discard pages. Outside Unix the
320/// release is a no-op. On those systems the whole file can become resident.
321/// A mapped file is not a snapshot and must not change while it is read; a
322/// truncation can end the process with `SIGBUS`.
323pub struct ForwardText {
324    source: ByteSource,
325    released: usize,
326}
327
328impl ForwardText {
329    /// The bytes of `path`.
330    ///
331    /// With `map`, a large plain file stays mapped. Without it, the bytes
332    /// are copied. A bad UTF-8 byte is left for the parser, which names
333    /// the line (CON-file.1, CON-num.10). Opening the file does not reject it.
334    pub fn open(path: &Path, map: bool) -> Result<Self, Box<dyn std::error::Error>> {
335        let source = if map {
336            read_bytes_owned(path)?
337        } else {
338            ByteSource::Buf(read_file_bytes(path)?)
339        };
340        Ok(Self {
341            source,
342            released: 0,
343        })
344    }
345
346    /// Text the caller already holds. Page release is a no-op.
347    pub fn from_owned(text: String) -> Self {
348        Self {
349            source: ByteSource::Buf(text.into_bytes()),
350            released: 0,
351        }
352    }
353
354    pub fn as_bytes(&self) -> &[u8] {
355        self.source.as_slice()
356    }
357
358    /// The file as text when every byte is UTF-8.
359    pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
360        std::str::from_utf8(self.as_bytes())
361    }
362
363    /// Release the mapped pages before byte `pos` once [`RELEASE_STEP`]
364    /// bytes have been read since the last release. A later read of them
365    /// maps them in again. A `pos` past the end counts as the end.
366    pub fn release_before(&mut self, pos: usize) -> io::Result<()> {
367        if let ByteSource::Map(m) = &self.source
368            && pos >= self.released + RELEASE_STEP
369        {
370            let pos = pos.min(m.len());
371            release(m, self.released, pos)?;
372            self.released = pos;
373        }
374        Ok(())
375    }
376}
377
378/// Drop resident pages of `map` on `workers` threads, then the caller
379/// unmaps. Each thread advises a disjoint byte range. The page size is
380/// `sysconf(SC_PAGESIZE)`, not a host-tuned cutoff.
381pub fn advise_dontneed_parallel(map: &memmap2::Mmap, workers: usize) {
382    let len = map.len();
383    if len == 0 {
384        return;
385    }
386    let workers = workers.max(1);
387    if workers == 1 {
388        let _ = release(map, 0, len);
389        return;
390    }
391    let step = len.div_ceil(workers);
392    let advise_one = |worker: usize| {
393        let start = worker.saturating_mul(step);
394        if start >= len {
395            return;
396        }
397        let end = (start + step).min(len);
398        let _ = release(map, start, end);
399    };
400    // Inside the read's pool this stays on those workers. Outside it,
401    // a private scope avoids the global pool.
402    #[cfg(feature = "parallel")]
403    if rayon::current_thread_index().is_some() {
404        use rayon::prelude::*;
405        (0..workers).into_par_iter().for_each(advise_one);
406        return;
407    }
408    std::thread::scope(|scope| {
409        for worker in 0..workers {
410            scope.spawn(move || advise_one(worker));
411        }
412    });
413}
414
415/// Advise `MADV_DONTNEED` for the whole 64 KiB blocks of the map that
416/// `start..end` reaches, cut at the map end.
417fn release(map: &memmap2::Mmap, start: usize, end: usize) -> io::Result<()> {
418    // A multiple of every Linux page size. The map starts on a page, so the
419    // range stays inside it, and the page that contains `end` stays mapped.
420    const BLOCK: usize = 64 * 1024;
421    let start = start & !(BLOCK - 1);
422    let end = end.min(map.len()) & !(BLOCK - 1);
423    if end <= start {
424        return Ok(());
425    }
426    // SAFETY: `start..end` lies inside the map, which is shared and read
427    // only, so dropped pages read back from the file. Miri has no
428    // `MADV_DONTNEED`; skipping the hint leaves the bytes in place.
429    #[cfg(all(unix, not(miri)))]
430    unsafe {
431        map.unchecked_advise_range(memmap2::UncheckedAdvice::DontNeed, start, end - start)?;
432    }
433    #[cfg(not(all(unix, not(miri))))]
434    let _ = (map, start, end);
435    Ok(())
436}
437
438/// Creates a gzip-compressed writer wrapping a file at the given path.
439pub fn gzip_writer(path: &Path) -> io::Result<flate2::write::GzEncoder<std::fs::File>> {
440    let file = std::fs::File::create(path)?;
441    Ok(flate2::write::GzEncoder::new(
442        file,
443        flate2::Compression::new(GZIP_LEVEL),
444    ))
445}
446
447/// How many independent compression members a payload of `nbytes` uses.
448///
449/// Below 1 MiB the file stays one member, so small fixtures keep a single
450/// gzip stream. Larger payloads use about 2 MiB of plain text per member,
451/// and at least four members per core, so a read can keep every worker
452/// busy instead of waiting on one fat member. Capped at 64.
453pub fn compression_workers(nbytes: usize) -> usize {
454    const MIN_CHUNKED: usize = 1 << 20;
455    const PLAIN_PER_MEMBER: usize = 2 << 20;
456    if nbytes < MIN_CHUNKED {
457        return 1;
458    }
459    let threads = std::thread::available_parallelism()
460        .map(|n| n.get())
461        .unwrap_or(1);
462    let by_size = (nbytes / PLAIN_PER_MEMBER).max(1);
463    by_size.max(threads.saturating_mul(4)).clamp(1, 64)
464}
465
466/// Deflate workers for a write that did not ask for a thread count.
467///
468/// The member count stays wide so a read can split the file. Running one
469/// thread per member oversubscribes an 8-core host once that count hits
470/// 32. The cap is `available_parallelism`.
471pub fn default_deflate_threads(members: usize) -> usize {
472    let cores = std::thread::available_parallelism()
473        .map(|count| count.get())
474        .unwrap_or(1)
475        .max(1);
476    members.max(1).min(cores)
477}
478
479fn split_chunks(data: &[u8], workers: usize) -> Vec<&[u8]> {
480    if data.is_empty() || workers <= 1 {
481        return vec![data];
482    }
483    let workers = workers.max(1);
484    let mut cuts = Vec::with_capacity(workers + 1);
485    cuts.push(0usize);
486    for index in 1..workers {
487        let mut at = index * data.len() / workers;
488        if at > 0 && at < data.len() && data[at - 1] != b'\n' {
489            let forward = memchr::memchr(b'\n', &data[at..]).map(|rel| at + rel + 1);
490            let back = memchr::memrchr(b'\n', &data[..at]).map(|rel| rel + 1);
491            let previous = *cuts.last().unwrap_or(&0);
492            at = match (forward, back) {
493                (Some(next), Some(prev))
494                    if next < data.len() && (prev <= previous || next - at <= at - prev) =>
495                {
496                    next
497                }
498                (Some(next), _) if next < data.len() => next,
499                (_, Some(prev)) if prev > previous => prev,
500                _ => at,
501            };
502        }
503        if cuts.last().copied() != Some(at) && at < data.len() {
504            cuts.push(at);
505        }
506    }
507    if cuts.last().copied() != Some(data.len()) {
508        cuts.push(data.len());
509    }
510    cuts.windows(2)
511        .filter(|span| span[1] > span[0])
512        .map(|span| &data[span[0]..span[1]])
513        .collect()
514}
515
516/// `(first coordinate row, row count)` for each plain slice.
517///
518/// `None` when the text is not one coordinate block after a header, so
519/// the reader keeps the full-frame parser. Old indexes omit this table
520/// and still decode.
521fn coord_member_rows(data: &[u8], parts: &[&[u8]]) -> Option<Vec<(u32, u32)>> {
522    if parts.len() < 2 || data.is_empty() {
523        return None;
524    }
525    let mut line_at = Vec::new();
526    let mut pos = 0usize;
527    while let Some(rel) = memchr::memchr(b'\n', &data[pos..]) {
528        line_at.push(pos);
529        pos += rel + 1;
530        if line_at.len() > 64 && line_at.len() > 9 {
531            break;
532        }
533    }
534    if line_at.len() < 9 {
535        return None;
536    }
537    let line = |index: usize| -> Option<&[u8]> {
538        let start = *line_at.get(index)?;
539        let end = line_at.get(index + 1).copied().unwrap_or(data.len());
540        let end = end.saturating_sub(usize::from(end > start && data[end - 1] == b'\n'));
541        Some(&data[start..end])
542    };
543    let types_text = std::str::from_utf8(line(6)?).ok()?;
544    let natm_types = crate::parser::parse_count_line(types_text, 1).ok()?[0];
545    // Species headers sit between coordinate groups. A member can be one
546    // contiguous coordinate run only when the frame has a single species;
547    // anything else keeps the full-frame parser.
548    if natm_types != 1 {
549        return None;
550    }
551    let counts_text = std::str::from_utf8(line(7)?).ok()?;
552    let counts = crate::parser::parse_count_line(counts_text, natm_types).ok()?;
553    let natoms: usize = counts.iter().sum();
554    if natoms == 0 {
555        return None;
556    }
557    let header_lines = 9 + natm_types * 2;
558    // A per-newline callback over a million rows is slower than the
559    // deflate it is trying to index. Count bytes in each slice instead.
560    let mut counts = Vec::with_capacity(parts.len());
561    for part in parts {
562        counts.push(count_newlines(part) as u32);
563    }
564    if counts[0] < header_lines as u32 {
565        return None;
566    }
567    counts[0] -= header_lines as u32;
568    let total: u32 = counts.iter().copied().sum();
569    if total as usize != natoms {
570        return None;
571    }
572    if let Some(last_nl) = memchr::memrchr(b'\n', data) {
573        if data[last_nl + 1..]
574            .iter()
575            .any(|byte| !byte.is_ascii_whitespace())
576        {
577            return None;
578        }
579    }
580    let mut row = 0u32;
581    let mut table = Vec::with_capacity(parts.len());
582    for count in counts {
583        table.push((row, count));
584        row = row.saturating_add(count);
585    }
586    if row as usize != natoms {
587        return None;
588    }
589    Some(table)
590}
591
592fn count_newlines(data: &[u8]) -> usize {
593    #[cfg(target_arch = "x86_64")]
594    {
595        static AVX2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
596        if *AVX2.get_or_init(|| is_x86_feature_detected!("avx2")) {
597            return unsafe { count_newlines_avx2(data) };
598        }
599    }
600    data.iter().filter(|byte| **byte == b'\n').count()
601}
602
603#[cfg(target_arch = "x86_64")]
604#[target_feature(enable = "avx2")]
605unsafe fn count_newlines_avx2(data: &[u8]) -> usize {
606    use std::arch::x86_64::*;
607    unsafe {
608        let mut n = 0usize;
609        let mut i = 0usize;
610        let nl = _mm256_set1_epi8(b'\n' as i8);
611        while i + 128 <= data.len() {
612            let mut mask_n = 0usize;
613            for lane in 0..4 {
614                let v = _mm256_loadu_si256(data.as_ptr().add(i + lane * 32) as *const _);
615                mask_n += _mm256_movemask_epi8(_mm256_cmpeq_epi8(v, nl)).count_ones() as usize;
616            }
617            n += mask_n;
618            i += 128;
619        }
620        while i + 32 <= data.len() {
621            let v = _mm256_loadu_si256(data.as_ptr().add(i) as *const _);
622            n += _mm256_movemask_epi8(_mm256_cmpeq_epi8(v, nl)).count_ones() as usize;
623            i += 32;
624        }
625        while i < data.len() {
626            n += usize::from(*data.get_unchecked(i) == b'\n');
627            i += 1;
628        }
629        n
630    }
631}
632
633fn gzip_member(data: &[u8]) -> io::Result<Vec<u8>> {
634    let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::new(GZIP_LEVEL));
635    enc.write_all(data)?;
636    enc.finish()
637}
638
639/// Writes `data` as gzip members at [`GZIP_LEVEL`].
640///
641/// One member when the payload is small. Otherwise each core compresses a
642/// slice. A wide file stores the member starts in the first member's extra
643/// field so the reader can inflate those slices together. A one-member file
644/// is an ordinary gzip stream.
645pub fn write_gzip_members(path: &Path, data: &[u8]) -> io::Result<usize> {
646    write_gzip_members_n(path, data, compression_workers(data.len()))
647}
648
649/// [`write_gzip_members`] with an explicit member count.
650///
651/// `members == 1` is one gzip stream and does not use another core.
652/// The member count is also the worker count.
653pub fn write_gzip_members_n(path: &Path, data: &[u8], members: usize) -> io::Result<usize> {
654    write_gzip_members_limited(path, data, members, members.max(1))
655}
656
657/// [`write_gzip_members_n`] with a separate worker count.
658///
659/// Eight members on two workers compress four slices per worker. The
660/// bytes match a one-worker write of the same slices.
661/// Format each atom slice and deflate it on that same worker.
662///
663/// The plain text is the binding header on the first slice plus coordinate
664/// lines. One member stays on the streaming encoder so its bytes do not
665/// change. `threads == 1` is the caller's problem: this function always
666/// uses `threads` workers.
667pub fn write_fused_gzip_frame(
668    path: &Path,
669    frame: &crate::types::ConFrame,
670    members: usize,
671    threads: usize,
672) -> io::Result<usize> {
673    write_fused_frame(path, frame, members, threads, true)
674}
675
676/// [`write_fused_gzip_frame`] for zstd frames.
677#[cfg(feature = "zstd")]
678pub fn write_fused_zstd_frame(
679    path: &Path,
680    frame: &crate::types::ConFrame,
681    members: usize,
682    threads: usize,
683) -> io::Result<usize> {
684    write_fused_frame(path, frame, members, threads, false)
685}
686
687fn write_fused_frame(
688    path: &Path,
689    frame: &crate::types::ConFrame,
690    members: usize,
691    threads: usize,
692    gzip: bool,
693) -> io::Result<usize> {
694    let n = frame.atom_data.len();
695    let members = members.max(2).min(n.max(2));
696    let mut ranges = Vec::with_capacity(members);
697    let mut rows = Vec::with_capacity(members);
698    let mut row = 0u32;
699    let mut start = 0usize;
700    for index in 0..members {
701        let end = if index + 1 == members {
702            n
703        } else {
704            (index + 1) * n / members
705        };
706        if end <= start {
707            continue;
708        }
709        let count = (end - start) as u32;
710        rows.push((row, count));
711        row += count;
712        ranges.push((start, end));
713        start = end;
714    }
715    let header = crate::writer::binding_header_bytes(frame)
716        .map_err(|err| io::Error::other(err.to_string()))?;
717    let slots: Vec<GzipMemberSlot> = (0..ranges.len())
718        .map(|_| std::sync::Mutex::new(None))
719        .collect();
720    let threads = threads.max(1).min(ranges.len());
721    let ranges_ref = &ranges;
722    std::thread::scope(|scope| {
723        for (begin, end) in worker_ranges(ranges.len(), threads) {
724            let slots = &slots;
725            let header = &header;
726            scope.spawn(move || {
727                let mut plain = Vec::new();
728                for index in begin..end {
729                    let (atom_from, atom_to) = ranges_ref[index];
730                    plain.clear();
731                    if atom_from == 0 {
732                        plain.extend_from_slice(header);
733                    }
734                    match crate::writer::format_coord_range(frame, atom_from, atom_to) {
735                        Ok(rows) => plain.extend(rows),
736                        Err(err) => {
737                            *slots[index].lock().unwrap() =
738                                Some(Err(io::Error::other(err.to_string())));
739                            continue;
740                        }
741                    }
742                    let plain_len = plain.len();
743                    let encoded = if gzip {
744                        gzip_member(&plain)
745                    } else {
746                        #[cfg(feature = "zstd")]
747                        {
748                            zstd_compress_part(&plain)
749                        }
750                        #[cfg(not(feature = "zstd"))]
751                        {
752                            let _ = &plain;
753                            Err(zstd_unsupported())
754                        }
755                    };
756                    *slots[index].lock().unwrap() = Some(encoded.map(|bytes| (bytes, plain_len)));
757                }
758            });
759        }
760    });
761    let mut encoded = Vec::with_capacity(ranges.len());
762    let mut plain_lens = Vec::with_capacity(ranges.len());
763    for slot in slots {
764        match slot.into_inner().unwrap_or(None) {
765            Some(Ok((bytes, plain_len))) => {
766                encoded.push(bytes);
767                plain_lens.push(plain_len);
768            }
769            Some(Err(err)) => return Err(err),
770            None => return Err(io::Error::other("compress")),
771        }
772    }
773    if gzip {
774        if encoded.len() > 1 {
775            stamp_gzip_index(&mut encoded, &plain_lens, Some(&rows));
776        }
777        write_members(path, &encoded)?;
778    } else {
779        #[cfg(feature = "zstd")]
780        {
781            let mut file = std::fs::File::create(path)?;
782            if encoded.len() > 1 {
783                file.write_all(&zstd_index_frame(&encoded, &plain_lens, Some(&rows)))?;
784            }
785            for part in &encoded {
786                file.write_all(part)?;
787            }
788            file.flush()?;
789        }
790    }
791    Ok(encoded.len())
792}
793
794pub fn write_gzip_members_limited(
795    path: &Path,
796    data: &[u8],
797    members: usize,
798    threads: usize,
799) -> io::Result<usize> {
800    let trace = std::env::var_os("READCON_WRITE_TRACE").is_some();
801    let t0 = std::time::Instant::now();
802    let parts = split_chunks(data, members.max(1));
803    let plain: Vec<usize> = parts.iter().map(|part| part.len()).collect();
804    let t_split = t0.elapsed().as_secs_f64();
805    let t1 = std::time::Instant::now();
806    let mut encoded = encode_parts(&parts, threads, gzip_member)?;
807    let t_encode = t1.elapsed().as_secs_f64();
808    let t2 = std::time::Instant::now();
809    if encoded.len() > 1 {
810        let rows = coord_member_rows(data, &parts);
811        stamp_gzip_index(&mut encoded, &plain, rows.as_deref());
812    }
813    let t_index = t2.elapsed().as_secs_f64();
814    let t3 = std::time::Instant::now();
815    let count = encoded.len();
816    write_members(path, &encoded)?;
817    if trace {
818        eprintln!(
819            "gzip-write split={t_split:.4} encode={t_encode:.4} index={t_index:.4} io={:.4} members={count} threads={threads}",
820            t3.elapsed().as_secs_f64()
821        );
822    }
823    Ok(count)
824}
825
826/// `RC` extra-field payload: `RCZ1`, member count, compressed starts,
827/// then each member's plain length.
828#[cfg(feature = "parallel")]
829fn row_table(data: &[u8], count: usize) -> Option<Vec<(u32, u32)>> {
830    let at = 6 + 16 * count;
831    if data.len() < at + 8 * count {
832        return None;
833    }
834    let mut rows = Vec::with_capacity(count);
835    for index in 0..count {
836        let off = at + 8 * index;
837        let base = u32::from_le_bytes(data[off..off + 4].try_into().ok()?);
838        let n = u32::from_le_bytes(data[off + 4..off + 8].try_into().ok()?);
839        rows.push((base, n));
840    }
841    Some(rows)
842}
843
844fn stamp_gzip_index(members: &mut [Vec<u8>], plain: &[usize], rows: Option<&[(u32, u32)]>) {
845    let count = members.len();
846    let row_bytes = usize::from(rows.is_some()) * 8 * count;
847    let extra_len = 4 + 2 + 16 * count + row_bytes;
848    let inserted = 2 + 4 + extra_len;
849    let mut starts = Vec::with_capacity(count);
850    let mut offset = inserted;
851    for member in members.iter() {
852        starts.push(offset as u64);
853        offset += member.len();
854    }
855    starts[0] = 0;
856    let mut payload = Vec::with_capacity(extra_len);
857    payload.extend_from_slice(b"RCZ1");
858    payload.extend_from_slice(&(count as u16).to_le_bytes());
859    for start in &starts {
860        payload.extend_from_slice(&start.to_le_bytes());
861    }
862    for len in plain {
863        payload.extend_from_slice(&(*len as u64).to_le_bytes());
864    }
865    if let Some(rows) = rows {
866        for (base, n) in rows {
867            payload.extend_from_slice(&base.to_le_bytes());
868            payload.extend_from_slice(&n.to_le_bytes());
869        }
870    }
871    let mut extra = Vec::with_capacity(inserted);
872    extra.extend_from_slice(&((4 + payload.len()) as u16).to_le_bytes());
873    extra.extend_from_slice(b"RC");
874    extra.extend_from_slice(&(payload.len() as u16).to_le_bytes());
875    extra.extend_from_slice(&payload);
876    let first = &mut members[0];
877    debug_assert_eq!(&first[0..2], b"\x1f\x8b");
878    first[3] |= 0x04;
879    first.splice(10..10, extra);
880}
881
882struct MemberPlan {
883    starts: Vec<usize>,
884    plain: Option<Vec<usize>>,
885    /// `(first coordinate row, row count)` per member, when the payload is
886    /// one coordinate block after a single header.
887    #[cfg(feature = "parallel")]
888    rows: Option<Vec<(u32, u32)>>,
889}
890
891type GzipMemberSlot = std::sync::Mutex<Option<io::Result<(Vec<u8>, usize)>>>;
892
893fn gzip_member_starts(bytes: &[u8]) -> Option<MemberPlan> {
894    if bytes.len() < 16 || bytes[0] != 0x1f || bytes[1] != 0x8b || bytes[3] & 0x04 == 0 {
895        return None;
896    }
897    let xlen = u16::from_le_bytes([bytes[10], bytes[11]]) as usize;
898    let extra = bytes.get(12..12 + xlen)?;
899    let mut cursor = 0;
900    while cursor + 4 <= extra.len() {
901        let len = u16::from_le_bytes([extra[cursor + 2], extra[cursor + 3]]) as usize;
902        let data = extra.get(cursor + 4..cursor + 4 + len)?;
903        if &extra[cursor..cursor + 2] == b"RC" && data.starts_with(b"RCZ1") && data.len() >= 6 {
904            let count = u16::from_le_bytes([data[4], data[5]]) as usize;
905            if data.len() < 6 + 8 * count || count == 0 {
906                return None;
907            }
908            let mut starts = Vec::with_capacity(count);
909            for index in 0..count {
910                let at = 6 + 8 * index;
911                let start = u64::from_le_bytes(data[at..at + 8].try_into().ok()?) as usize;
912                if start > bytes.len() || (index > 0 && start <= starts[index - 1]) {
913                    return None;
914                }
915                starts.push(start);
916            }
917            let plain = if data.len() >= 6 + 16 * count {
918                let mut lens = Vec::with_capacity(count);
919                for index in 0..count {
920                    let at = 6 + 8 * count + 8 * index;
921                    lens.push(u64::from_le_bytes(data[at..at + 8].try_into().ok()?) as usize);
922                }
923                Some(lens)
924            } else {
925                None
926            };
927            #[cfg(feature = "parallel")]
928            let rows = row_table(data, count);
929            return Some(MemberPlan {
930                starts,
931                plain,
932                #[cfg(feature = "parallel")]
933                rows,
934            });
935        }
936        cursor += 4 + len;
937    }
938    None
939}
940
941/// `0` uses one worker per member. `1` stays on the calling thread.
942pub(crate) fn decode_thread_budget() -> usize {
943    DECODE_THREADS.with(|flag| flag.get())
944}
945
946std::thread_local! {
947    static DECODE_THREADS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
948}
949
950/// Run `body` with indexed members inflated on at most `threads` workers.
951///
952/// `threads < 2` is the calling thread. The previous budget is restored
953/// when `body` returns, including on unwind.
954pub fn with_decode_threads<T>(threads: usize, body: impl FnOnce() -> T) -> T {
955    let previous = DECODE_THREADS.with(|flag| flag.replace(threads));
956    struct Reset(usize);
957    impl Drop for Reset {
958        fn drop(&mut self) {
959            DECODE_THREADS.with(|flag| flag.set(self.0));
960        }
961    }
962    let _reset = Reset(previous);
963    body()
964}
965
966/// Run `body` with multi-member inflation forced onto one thread.
967pub fn with_serial_decode<T>(body: impl FnOnce() -> T) -> T {
968    with_decode_threads(1, body)
969}
970
971fn gunzip_member(bytes: &[u8]) -> io::Result<Vec<u8>> {
972    let (out, exact) = gzip_one_member(bytes)?;
973    if !exact {
974        return Err(io::Error::new(
975            io::ErrorKind::InvalidData,
976            "gzip member does not fill its index slice",
977        ));
978    }
979    Ok(out)
980}
981
982fn gunzip_all(bytes: &[u8]) -> io::Result<Vec<u8>> {
983    let mut out = Vec::new();
984    inflate_gzip(bytes, &mut out)?;
985    Ok(out)
986}
987
988fn worker_limit_from_budget(members: usize) -> usize {
989    let members = members.max(1);
990    match decode_thread_budget() {
991        0 => members,
992        budget => budget.min(members).max(1),
993    }
994}
995
996fn worker_ranges(jobs: usize, threads: usize) -> Vec<(usize, usize)> {
997    let threads = threads.max(1).min(jobs.max(1));
998    let mut ranges = Vec::with_capacity(threads);
999    let mut start = 0usize;
1000    for worker in 0..threads {
1001        let end = if worker + 1 == threads {
1002            jobs
1003        } else {
1004            (worker + 1) * jobs / threads
1005        };
1006        if end > start {
1007            ranges.push((start, end));
1008            start = end;
1009        }
1010    }
1011    ranges
1012}
1013
1014fn par_ranges(jobs: usize, threads: usize, work: impl Fn(usize, usize) + Sync + Send) {
1015    let ranges = worker_ranges(jobs, threads);
1016    if ranges.len() < 2 {
1017        for (begin, end) in ranges {
1018            work(begin, end);
1019        }
1020        return;
1021    }
1022    #[cfg(feature = "parallel")]
1023    {
1024        crate::parser::on_pool(ranges.len(), || {
1025            use rayon::prelude::*;
1026            ranges
1027                .par_iter()
1028                .for_each(|(begin, end)| work(*begin, *end));
1029        });
1030    }
1031    #[cfg(not(feature = "parallel"))]
1032    {
1033        std::thread::scope(|scope| {
1034            for (worker, (begin, end)) in ranges.into_iter().enumerate() {
1035                let work = &work;
1036                scope.spawn(move || {
1037                    crate::parser::pin_worker(worker);
1038                    work(begin, end);
1039                });
1040            }
1041        });
1042    }
1043}
1044
1045fn gzip_one_member(src: &[u8]) -> io::Result<(Vec<u8>, bool)> {
1046    // `read::GzDecoder` wraps a `BufReader` and may pull bytes past the
1047    // member. The bufread decoder on a cursor reports the member's end.
1048    let mut decoder = flate2::bufread::GzDecoder::new(std::io::Cursor::new(src));
1049    let mut out = Vec::new();
1050    decoder.read_to_end(&mut out)?;
1051    let consumed = decoder.get_ref().position() as usize;
1052    Ok((out, consumed == src.len()))
1053}
1054
1055fn gzip_into(src: &[u8], dst: &mut [u8]) -> io::Result<()> {
1056    // Inflate into the caller's slice. A temporary member buffer was a
1057    // second copy of every slice, and a million-atom CON.gz paid it on
1058    // top of the serial decoder the older releases use.
1059    let mut decoder = flate2::bufread::GzDecoder::new(std::io::Cursor::new(src));
1060    decoder.read_exact(dst)?;
1061    let mut extra = [0u8; 1];
1062    match decoder.read(&mut extra) {
1063        Ok(0) => {}
1064        Ok(_) => {
1065            return Err(io::Error::new(
1066                io::ErrorKind::InvalidData,
1067                "gzip member does not fill its index slice",
1068            ));
1069        }
1070        // A trailer cut by 1–8 bytes surfaces here. Treating that as a
1071        // finished member skipped the CRC and size checks.
1072        Err(err) => return Err(err),
1073    }
1074    let consumed = decoder.get_ref().position() as usize;
1075    if consumed != src.len() {
1076        return Err(io::Error::new(
1077            io::ErrorKind::InvalidData,
1078            "gzip member does not fill its index slice",
1079        ));
1080    }
1081    Ok(())
1082}
1083
1084fn inflate_gzip(bytes: &[u8], out: &mut Vec<u8>) -> io::Result<()> {
1085    if decode_thread_budget() != 1 {
1086        if let Some(plan) = gzip_member_starts(bytes) {
1087            if plan.starts.len() > 1 {
1088                let threads = worker_limit_from_budget(plan.starts.len());
1089                let indexed = if let Some(plain) = plan.plain.as_deref() {
1090                    if plain.len() == plan.starts.len() {
1091                        inflate_sized(bytes, &plan.starts, plain, threads, gzip_into, out)
1092                    } else {
1093                        Err(io::Error::new(
1094                            io::ErrorKind::InvalidData,
1095                            "gzip index has no plain length for every member",
1096                        ))
1097                    }
1098                } else {
1099                    let parts = inflate_unknown(bytes, &plan.starts, threads, gunzip_member)?;
1100                    out.clear();
1101                    for part in parts {
1102                        out.extend_from_slice(&part);
1103                    }
1104                    Ok(())
1105                };
1106                if indexed.is_ok() {
1107                    return indexed;
1108                }
1109                // A stale or partial index must not hide a later member.
1110                // The serial decoder is what a file without our index uses.
1111                out.clear();
1112            }
1113        }
1114    }
1115    let mut decoder = flate2::read::MultiGzDecoder::new(bytes);
1116    out.clear();
1117    decoder.read_to_end(out)?;
1118    Ok(())
1119}
1120
1121/// Largest plain length an index may claim for a file of `file_len` bytes.
1122///
1123/// The index is attacker-controlled. A flipped high bit must fail the
1124/// decode instead of reserving that many bytes.
1125fn plain_length_budget(file_len: usize) -> usize {
1126    file_len.saturating_mul(8192).saturating_add(1024 * 1024)
1127}
1128
1129pub(crate) fn trusted_plain_total(file_len: usize, plain: &[usize]) -> Option<usize> {
1130    let cap = plain_length_budget(file_len);
1131    let mut total = 0usize;
1132    for len in plain {
1133        if *len > cap {
1134            return None;
1135        }
1136        total = total.checked_add(*len).filter(|sum| *sum <= cap)?;
1137    }
1138    Some(total)
1139}
1140
1141/// Atom count implied by a row table, when every span fits in `plain_total`.
1142#[cfg(feature = "parallel")]
1143pub(crate) fn trusted_row_total(plain_total: usize, rows: &[(u32, u32)]) -> Option<usize> {
1144    let cap = plain_total / 8 + 16;
1145    let mut total = 0usize;
1146    let mut spans = Vec::with_capacity(rows.len());
1147    for (base, count) in rows {
1148        let base = *base as usize;
1149        let count = *count as usize;
1150        total = total.checked_add(count).filter(|sum| *sum <= cap)?;
1151        let end = base.checked_add(count)?;
1152        spans.push((base, end));
1153    }
1154    // The spans must cover every atom once. A gap leaves an uninitialized
1155    // atom, and dropping that atom reads a dangling pointer.
1156    spans.sort_unstable();
1157    let mut cursor = 0usize;
1158    for (base, end) in spans {
1159        if base != cursor || end > total {
1160            return None;
1161        }
1162        cursor = end;
1163    }
1164    if cursor != total {
1165        return None;
1166    }
1167    Some(total)
1168}
1169
1170fn inflate_sized(
1171    bytes: &[u8],
1172    starts: &[usize],
1173    plain: &[usize],
1174    threads: usize,
1175    decode: impl Fn(&[u8], &mut [u8]) -> io::Result<()> + Sync + Send,
1176    out: &mut Vec<u8>,
1177) -> io::Result<()> {
1178    let Some(total) = trusted_plain_total(bytes.len(), plain) else {
1179        return Err(io::Error::new(
1180            io::ErrorKind::InvalidData,
1181            "member plain length exceeds the compressed file",
1182        ));
1183    };
1184    // `reserve(n)` grows until `capacity >= len + n`, not `capacity >= old + n`.
1185    // A reused buffer whose length was cleared still has its old capacity, so
1186    // reserving only the shortfall against that capacity leaves `set_len` past
1187    // the end.
1188    out.clear();
1189    if out.capacity() < total {
1190        let extra = total - out.len();
1191        out.reserve(extra);
1192    }
1193    // `u8` has no destructor. `set_len(0)` on the error path drops nothing
1194    // unread. Every successful return overwrites `0..total`.
1195    unsafe { out.set_len(total) };
1196    let mut offsets = Vec::with_capacity(plain.len());
1197    let mut cursor = 0usize;
1198    for len in plain {
1199        offsets.push(cursor);
1200        cursor += *len;
1201    }
1202    let mut ends = Vec::with_capacity(starts.len());
1203    ends.extend_from_slice(&starts[1..]);
1204    ends.push(bytes.len());
1205    let error = std::sync::Mutex::new(None);
1206    let base = out.as_mut_ptr() as usize;
1207    par_ranges(starts.len(), threads, |begin, end| {
1208        for index in begin..end {
1209            if ends[index] < starts[index] || ends[index] > bytes.len() {
1210                *error.lock().unwrap() = Some(io::Error::new(
1211                    io::ErrorKind::InvalidData,
1212                    "member range is outside the file",
1213                ));
1214                return;
1215            }
1216            let src = &bytes[starts[index]..ends[index]];
1217            let dst = unsafe {
1218                std::slice::from_raw_parts_mut((base as *mut u8).add(offsets[index]), plain[index])
1219            };
1220            if let Err(err) = decode(src, dst) {
1221                *error.lock().unwrap() = Some(err);
1222                return;
1223            }
1224        }
1225    });
1226    if let Some(err) = error.into_inner().unwrap_or(None) {
1227        unsafe { out.set_len(0) };
1228        return Err(err);
1229    }
1230    Ok(())
1231}
1232
1233fn inflate_unknown(
1234    bytes: &[u8],
1235    starts: &[usize],
1236    threads: usize,
1237    decode: impl Fn(&[u8]) -> io::Result<Vec<u8>> + Sync + Send,
1238) -> io::Result<Vec<Vec<u8>>> {
1239    let mut ends = Vec::with_capacity(starts.len());
1240    ends.extend_from_slice(&starts[1..]);
1241    ends.push(bytes.len());
1242    let slots: Vec<std::sync::Mutex<Option<io::Result<Vec<u8>>>>> = (0..starts.len())
1243        .map(|_| std::sync::Mutex::new(None))
1244        .collect();
1245    par_ranges(starts.len(), threads, |begin, end| {
1246        for index in begin..end {
1247            let part = if ends[index] < starts[index] || ends[index] > bytes.len() {
1248                Err(io::Error::new(
1249                    io::ErrorKind::InvalidData,
1250                    "member range is outside the file",
1251                ))
1252            } else {
1253                decode(&bytes[starts[index]..ends[index]])
1254            };
1255            *slots[index].lock().unwrap() = Some(part);
1256        }
1257    });
1258    let mut out = Vec::with_capacity(starts.len());
1259    for slot in slots {
1260        match slot.into_inner().unwrap_or(None) {
1261            Some(Ok(part)) => out.push(part),
1262            Some(Err(err)) => return Err(err),
1263            None => return Err(io::Error::other("inflate")),
1264        }
1265    }
1266    Ok(out)
1267}
1268
1269fn encode_parts<F>(parts: &[&[u8]], threads: usize, encode: F) -> io::Result<Vec<Vec<u8>>>
1270where
1271    F: Fn(&[u8]) -> io::Result<Vec<u8>> + Sync,
1272{
1273    if parts.len() < 2 || threads <= 1 {
1274        let mut out = Vec::with_capacity(parts.len().max(1));
1275        if parts.is_empty() {
1276            out.push(encode(b"")?);
1277            return Ok(out);
1278        }
1279        for part in parts {
1280            out.push(encode(part)?);
1281        }
1282        return Ok(out);
1283    }
1284    let slots: Vec<std::sync::Mutex<Option<io::Result<Vec<u8>>>>> = (0..parts.len())
1285        .map(|_| std::sync::Mutex::new(None))
1286        .collect();
1287    // One OS thread per worker, as the original member writer did. The
1288    // pinned pool is the parser's; sharing it with deflate left the
1289    // eight-thread gzip write slower than four.
1290    let ranges = worker_ranges(parts.len(), threads);
1291    std::thread::scope(|scope| {
1292        for (begin, end) in ranges {
1293            let slots = &slots;
1294            let parts = &parts;
1295            let encode = &encode;
1296            scope.spawn(move || {
1297                for index in begin..end {
1298                    *slots[index].lock().unwrap() = Some(encode(parts[index]));
1299                }
1300            });
1301        }
1302    });
1303    let mut out = Vec::with_capacity(parts.len());
1304    for slot in slots {
1305        match slot.into_inner().unwrap_or(None) {
1306            Some(Ok(part)) => out.push(part),
1307            Some(Err(err)) => return Err(err),
1308            None => return Err(io::Error::other("compress")),
1309        }
1310    }
1311    Ok(out)
1312}
1313
1314fn write_members(path: &Path, members: &[Vec<u8>]) -> io::Result<()> {
1315    let mut file = std::fs::File::create(path)?;
1316    for member in members {
1317        file.write_all(member)?;
1318    }
1319    file.flush()
1320}
1321
1322/// Creates a zstd-compressed writer wrapping a file at the given path.
1323///
1324/// Returns a finished writer ready for streaming line writes; the caller
1325/// is responsible for dropping the writer to flush the final frame.
1326/// Available only when the `zstd` Cargo feature is enabled.
1327#[cfg(feature = "zstd")]
1328pub fn zstd_writer(
1329    path: &Path,
1330) -> io::Result<zstd::stream::write::AutoFinishEncoder<'static, std::fs::File>> {
1331    let file = std::fs::File::create(path)?;
1332    // Level 3 is the zstd CLI default; balances ratio against speed.
1333    let encoder = zstd::stream::write::Encoder::new(file, ZSTD_LEVEL)?;
1334    Ok(encoder.auto_finish())
1335}
1336
1337/// Writes `data` as concatenated zstd frames at [`ZSTD_LEVEL`].
1338///
1339/// One frame when the payload is small. A wide file leads with a skippable
1340/// frame that lists the data-frame starts, which the serial decoder ignores.
1341#[cfg(feature = "zstd")]
1342pub fn write_zstd_members(path: &Path, data: &[u8]) -> io::Result<usize> {
1343    write_zstd_members_n(path, data, compression_workers(data.len()))
1344}
1345
1346/// [`write_zstd_members`] with an explicit frame count.
1347#[cfg(feature = "zstd")]
1348pub fn write_zstd_members_n(path: &Path, data: &[u8], members: usize) -> io::Result<usize> {
1349    write_zstd_members_limited(path, data, members, members.max(1))
1350}
1351
1352/// [`write_zstd_members_n`] with a separate worker count.
1353#[cfg(feature = "zstd")]
1354pub fn write_zstd_members_limited(
1355    path: &Path,
1356    data: &[u8],
1357    members: usize,
1358    threads: usize,
1359) -> io::Result<usize> {
1360    let trace = std::env::var_os("READCON_WRITE_TRACE").is_some();
1361    let t0 = std::time::Instant::now();
1362    let parts = split_chunks(data, members.max(1));
1363    let plain: Vec<usize> = parts.iter().map(|part| part.len()).collect();
1364    let t_split = t0.elapsed().as_secs_f64();
1365    let t1 = std::time::Instant::now();
1366    // One frame keeps the `bulk::compress` bytes. Several frames reuse a
1367    // context; the plaintext is what callers compare.
1368    let encoded = if parts.len() < 2 {
1369        encode_parts(&parts, 1, |part| {
1370            zstd::bulk::compress(part, ZSTD_LEVEL).map_err(|err| io::Error::other(err.to_string()))
1371        })?
1372    } else {
1373        encode_parts(&parts, threads, zstd_compress_part)?
1374    };
1375    let t_encode = t1.elapsed().as_secs_f64();
1376    let t2 = std::time::Instant::now();
1377    let count = encoded.len();
1378    let mut file = std::fs::File::create(path)?;
1379    if count > 1 {
1380        let rows = coord_member_rows(data, &parts);
1381        file.write_all(&zstd_index_frame(&encoded, &plain, rows.as_deref()))?;
1382    }
1383    let t_index = t2.elapsed().as_secs_f64();
1384    let t3 = std::time::Instant::now();
1385    for frame in &encoded {
1386        file.write_all(frame)?;
1387    }
1388    file.flush()?;
1389    if trace {
1390        eprintln!(
1391            "zstd-write split={t_split:.4} encode={t_encode:.4} index={t_index:.4} io={:.4} members={count} threads={threads}",
1392            t3.elapsed().as_secs_f64()
1393        );
1394    }
1395    Ok(count)
1396}
1397
1398#[cfg(feature = "zstd")]
1399fn zstd_compress_part(part: &[u8]) -> io::Result<Vec<u8>> {
1400    // One member stays on `bulk::compress`, which is the single-frame
1401    // byte image. Several members reuse a context on the worker.
1402    if part.is_empty() {
1403        return zstd::bulk::compress(part, ZSTD_LEVEL)
1404            .map_err(|err| io::Error::other(err.to_string()));
1405    }
1406    std::thread_local! {
1407        static COMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Compressor<'static>>> =
1408            const { std::cell::RefCell::new(None) };
1409    }
1410    COMPRESSOR.with(|cell| {
1411        let mut slot = cell.borrow_mut();
1412        if slot.is_none() {
1413            *slot = Some(
1414                zstd::bulk::Compressor::new(ZSTD_LEVEL)
1415                    .map_err(|err| io::Error::other(err.to_string()))?,
1416            );
1417        }
1418        slot.as_mut()
1419            .expect("compressor")
1420            .compress(part)
1421            .map_err(|err| io::Error::other(err.to_string()))
1422    })
1423}
1424
1425#[cfg(feature = "zstd")]
1426fn zstd_index_frame(frames: &[Vec<u8>], plain: &[usize], rows: Option<&[(u32, u32)]>) -> Vec<u8> {
1427    let row_bytes = usize::from(rows.is_some()) * 8 * frames.len();
1428    let payload_len = 4 + 2 + 16 * frames.len() + row_bytes;
1429    let mut starts = Vec::with_capacity(frames.len());
1430    let mut offset = 8 + payload_len;
1431    for frame in frames {
1432        starts.push(offset as u64);
1433        offset += frame.len();
1434    }
1435    let mut payload = Vec::with_capacity(payload_len);
1436    payload.extend_from_slice(b"RCZ1");
1437    payload.extend_from_slice(&(frames.len() as u16).to_le_bytes());
1438    for start in starts {
1439        payload.extend_from_slice(&start.to_le_bytes());
1440    }
1441    for len in plain {
1442        payload.extend_from_slice(&(*len as u64).to_le_bytes());
1443    }
1444    if let Some(rows) = rows {
1445        for (base, n) in rows {
1446            payload.extend_from_slice(&base.to_le_bytes());
1447            payload.extend_from_slice(&n.to_le_bytes());
1448        }
1449    }
1450    let mut bytes = Vec::with_capacity(8 + payload.len());
1451    bytes.extend_from_slice(&0x184D_2A50u32.to_le_bytes());
1452    bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
1453    bytes.extend_from_slice(&payload);
1454    bytes
1455}
1456
1457#[cfg(feature = "zstd")]
1458fn zstd_frame_starts(bytes: &[u8]) -> Option<MemberPlan> {
1459    if bytes.len() < 12 || bytes[0..4] != [0x50, 0x2a, 0x4d, 0x18] {
1460        return None;
1461    }
1462    let size = u32::from_le_bytes(bytes[4..8].try_into().ok()?) as usize;
1463    let payload = bytes.get(8..8 + size)?;
1464    if !payload.starts_with(b"RCZ1") || payload.len() < 6 {
1465        return None;
1466    }
1467    let count = u16::from_le_bytes([payload[4], payload[5]]) as usize;
1468    if payload.len() < 6 + 8 * count || count == 0 {
1469        return None;
1470    }
1471    let mut starts = Vec::with_capacity(count);
1472    for index in 0..count {
1473        let at = 6 + 8 * index;
1474        let start = u64::from_le_bytes(payload[at..at + 8].try_into().ok()?) as usize;
1475        if start > bytes.len() || (index > 0 && start <= starts[index - 1]) {
1476            return None;
1477        }
1478        starts.push(start);
1479    }
1480    let plain = if payload.len() >= 6 + 16 * count {
1481        let mut lens = Vec::with_capacity(count);
1482        for index in 0..count {
1483            let at = 6 + 8 * count + 8 * index;
1484            lens.push(u64::from_le_bytes(payload[at..at + 8].try_into().ok()?) as usize);
1485        }
1486        Some(lens)
1487    } else {
1488        None
1489    };
1490    #[cfg(feature = "parallel")]
1491    let rows = row_table(payload, count);
1492    Some(MemberPlan {
1493        starts,
1494        plain,
1495        #[cfg(feature = "parallel")]
1496        rows,
1497    })
1498}
1499
1500#[cfg(feature = "zstd")]
1501fn zstd_into(src: &[u8], dst: &mut [u8]) -> io::Result<()> {
1502    std::thread_local! {
1503        static DECODER: std::cell::RefCell<Option<zstd::bulk::Decompressor<'static>>> =
1504            const { std::cell::RefCell::new(None) };
1505    }
1506    DECODER.with(|cell| {
1507        let mut slot = cell.borrow_mut();
1508        if slot.is_none() {
1509            *slot = Some(
1510                zstd::bulk::Decompressor::new().map_err(|err| io::Error::other(err.to_string()))?,
1511            );
1512        }
1513        let n = slot
1514            .as_mut()
1515            .expect("decoder")
1516            .decompress_to_buffer(src, dst)
1517            .map_err(|err| io::Error::other(err.to_string()))?;
1518        if n != dst.len() {
1519            return Err(io::Error::new(
1520                io::ErrorKind::InvalidData,
1521                "zstd frame length does not match the index",
1522            ));
1523        }
1524        let frame = zstd::zstd_safe::find_frame_compressed_size(src).map_err(|_| {
1525            io::Error::new(io::ErrorKind::InvalidData, "zstd frame size is not known")
1526        })?;
1527        if frame != src.len() {
1528            return Err(io::Error::new(
1529                io::ErrorKind::InvalidData,
1530                "zstd frame does not fill its index slice",
1531            ));
1532        }
1533        Ok(())
1534    })
1535}
1536
1537#[cfg(feature = "zstd")]
1538fn zstd_decode_all(bytes: &[u8]) -> io::Result<Vec<u8>> {
1539    let mut out = Vec::new();
1540    inflate_zstd(bytes, &mut out)?;
1541    Ok(out)
1542}
1543
1544#[cfg(feature = "zstd")]
1545fn inflate_zstd(bytes: &[u8], out: &mut Vec<u8>) -> io::Result<()> {
1546    if decode_thread_budget() != 1 {
1547        if let Some(plan) = zstd_frame_starts(bytes) {
1548            if plan.starts.len() > 1 {
1549                let threads = worker_limit_from_budget(plan.starts.len());
1550                let indexed = if let Some(plain) = plan.plain.as_deref() {
1551                    if plain.len() == plan.starts.len() {
1552                        inflate_sized(bytes, &plan.starts, plain, threads, zstd_into, out)
1553                    } else {
1554                        Err(io::Error::new(
1555                            io::ErrorKind::InvalidData,
1556                            "zstd index has no plain length for every frame",
1557                        ))
1558                    }
1559                } else {
1560                    let parts = inflate_unknown(bytes, &plan.starts, threads, |part| {
1561                        zstd::stream::decode_all(part)
1562                            .map_err(|err| io::Error::other(err.to_string()))
1563                    })?;
1564                    out.clear();
1565                    for part in parts {
1566                        out.extend_from_slice(&part);
1567                    }
1568                    Ok(())
1569                };
1570                if indexed.is_ok() {
1571                    return indexed;
1572                }
1573                out.clear();
1574            }
1575        }
1576    }
1577    let mut decoder = zstd::stream::read::Decoder::new(bytes)?;
1578    out.clear();
1579    decoder.read_to_end(out)?;
1580    Ok(())
1581}
1582
1583/// Inflate a gzip or zstd buffer with `threads` workers and no CON parse.
1584pub fn codec_inflate(bytes: &[u8], threads: usize) -> io::Result<Vec<u8>> {
1585    with_decode_threads(threads.max(1), || {
1586        if bytes.len() >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b {
1587            gunzip_all(bytes)
1588        } else if is_zstd_magic(bytes) {
1589            #[cfg(feature = "zstd")]
1590            {
1591                zstd_decode_all(bytes)
1592            }
1593            #[cfg(not(feature = "zstd"))]
1594            {
1595                Err(zstd_unsupported())
1596            }
1597        } else {
1598            Ok(bytes.to_vec())
1599        }
1600    })
1601}
1602
1603/// Deflate `plain` into `members` slices on `threads` workers.
1604///
1605/// The returned bytes are the concatenated members, including the index
1606/// a reader needs. The timed work is the codec, not a CON parse.
1607pub fn codec_deflate(
1608    plain: &[u8],
1609    members: usize,
1610    threads: usize,
1611    gzip: bool,
1612) -> io::Result<Vec<u8>> {
1613    if gzip {
1614        let parts = split_chunks(plain, members.max(1));
1615        let lens: Vec<usize> = parts.iter().map(|part| part.len()).collect();
1616        let mut encoded = encode_parts(&parts, threads, gzip_member)?;
1617        if encoded.len() > 1 {
1618            let rows = coord_member_rows(plain, &parts);
1619            stamp_gzip_index(&mut encoded, &lens, rows.as_deref());
1620        }
1621        let mut out = Vec::new();
1622        for part in encoded {
1623            out.extend(part);
1624        }
1625        return Ok(out);
1626    }
1627    #[cfg(feature = "zstd")]
1628    {
1629        let parts = split_chunks(plain, members.max(1));
1630        let lens: Vec<usize> = parts.iter().map(|part| part.len()).collect();
1631        let encoded = encode_parts(&parts, threads, zstd_compress_part)?;
1632        let mut out = Vec::new();
1633        if encoded.len() > 1 {
1634            let rows = coord_member_rows(plain, &parts);
1635            out.extend(zstd_index_frame(&encoded, &lens, rows.as_deref()));
1636        }
1637        for part in encoded {
1638            out.extend(part);
1639        }
1640        Ok(out)
1641    }
1642    #[cfg(not(feature = "zstd"))]
1643    {
1644        let _ = (plain, members, threads);
1645        Err(zstd_unsupported())
1646    }
1647}
1648
1649/// Indexed members whose plain lengths and coordinate-row spans are known.
1650#[cfg(feature = "parallel")]
1651pub(crate) struct IndexedMembers {
1652    pub starts: Vec<usize>,
1653    pub plain: Vec<usize>,
1654    pub rows: Vec<(u32, u32)>,
1655    pub gzip: bool,
1656}
1657
1658#[cfg(feature = "parallel")]
1659pub(crate) fn indexed_members(bytes: &[u8]) -> Option<IndexedMembers> {
1660    if bytes.len() >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b {
1661        let plan = gzip_member_starts(bytes)?;
1662        let plain = plan.plain?;
1663        let rows = plan.rows?;
1664        if plain.len() != plan.starts.len() || rows.len() != plan.starts.len() || plain.len() < 2 {
1665            return None;
1666        }
1667        return Some(IndexedMembers {
1668            starts: plan.starts,
1669            plain,
1670            rows,
1671            gzip: true,
1672        });
1673    }
1674    #[cfg(feature = "zstd")]
1675    if is_zstd_magic(bytes) {
1676        let plan = zstd_frame_starts(bytes)?;
1677        let plain = plan.plain?;
1678        let rows = plan.rows?;
1679        if plain.len() != plan.starts.len() || rows.len() != plan.starts.len() || plain.len() < 2 {
1680            return None;
1681        }
1682        return Some(IndexedMembers {
1683            starts: plan.starts,
1684            plain,
1685            rows,
1686            gzip: false,
1687        });
1688    }
1689    None
1690}
1691
1692#[cfg(feature = "parallel")]
1693pub(crate) fn inflate_member(gzip: bool, src: &[u8], dst: &mut [u8]) -> io::Result<()> {
1694    if gzip {
1695        gzip_into(src, dst)
1696    } else {
1697        #[cfg(feature = "zstd")]
1698        {
1699            zstd_into(src, dst)
1700        }
1701        #[cfg(not(feature = "zstd"))]
1702        {
1703            let _ = (src, dst);
1704            Err(zstd_unsupported())
1705        }
1706    }
1707}
1708
1709std::thread_local! {
1710    static PLAIN_BUF: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
1711}
1712
1713/// Inflate `file` into a buffer and hand that slice to `body`.
1714///
1715/// The plain text is dropped before this returns. A read that then copies
1716/// coordinates must not keep the inflated file beside those copies.
1717pub(crate) fn with_inflated_plain<T>(
1718    file: &[u8],
1719    body: impl FnOnce(&[u8]) -> Result<T, Box<dyn std::error::Error>>,
1720) -> Result<T, Box<dyn std::error::Error>> {
1721    PLAIN_BUF.with(|cell| {
1722        let mut buf = cell.borrow_mut();
1723        if file.len() >= 2 && file[0] == 0x1f && file[1] == 0x8b {
1724            inflate_gzip(file, &mut buf)
1725                .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)?;
1726        } else if is_zstd_magic(file) {
1727            #[cfg(feature = "zstd")]
1728            {
1729                inflate_zstd(file, &mut buf)
1730                    .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)?;
1731            }
1732            #[cfg(not(feature = "zstd"))]
1733            {
1734                return Err(Box::new(zstd_unsupported()) as Box<dyn std::error::Error>);
1735            }
1736        } else {
1737            buf.clear();
1738            buf.extend_from_slice(file);
1739        }
1740        let result = body(buf.as_slice())?;
1741        *buf = Vec::new();
1742        Ok(result)
1743    })
1744}
1745
1746#[cfg(test)]
1747mod tests {
1748    use super::*;
1749    use std::io::Write;
1750
1751    fn text_of_at_least(len: usize) -> Vec<u8> {
1752        let frame = include_bytes!("../resources/test/tiny_cuh2.con");
1753        frame.repeat(len / frame.len() + 2)
1754    }
1755
1756    fn large_text() -> Vec<u8> {
1757        text_of_at_least(MMAP_THRESHOLD as usize)
1758    }
1759
1760    /// Independent members inflate back to the same bytes. One member stays
1761    /// a single frame; several members carry the index a parallel read uses.
1762    #[test]
1763    fn codec_deflate_round_trips_one_member_and_several() {
1764        let plain = b"aaaa\nbbbb\ncccc\ndddd\neeee\nffff\n".repeat(80);
1765        for members in [1usize, 4] {
1766            let gzip = codec_deflate(&plain, members, 2, true).unwrap();
1767            assert!(gzip.starts_with(&[0x1f, 0x8b]));
1768            assert_eq!(codec_inflate(&gzip, 2).unwrap(), plain);
1769            #[cfg(feature = "zstd")]
1770            {
1771                let zstd_bytes = codec_deflate(&plain, members, 2, false).unwrap();
1772                assert_eq!(codec_inflate(&zstd_bytes, 2).unwrap(), plain);
1773            }
1774        }
1775        let raw = b"not a compressed buffer";
1776        assert_eq!(codec_inflate(raw, 1).unwrap(), raw);
1777    }
1778
1779    /// A one-thread read stays on the serial decoder. Several decode
1780    /// threads inflate each member straight into its output slice. Both
1781    /// return the same plain text.
1782    #[test]
1783    fn a_one_thread_inflate_matches_the_slice_inflate() {
1784        let plain = b"0123456789\n".repeat(200);
1785        let gzip = codec_deflate(&plain, 4, 4, true).unwrap();
1786        let serial = with_serial_decode(|| codec_inflate(&gzip, 1)).unwrap();
1787        let sliced = codec_inflate(&gzip, 4).unwrap();
1788        assert_eq!(serial, plain);
1789        assert_eq!(sliced, plain);
1790        assert_eq!(decode_thread_budget(), 0);
1791
1792        let member = {
1793            let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1794            enc.write_all(&plain).unwrap();
1795            enc.finish().unwrap()
1796        };
1797        let mut exact = vec![0u8; plain.len()];
1798        gzip_into(&member, &mut exact).unwrap();
1799        assert_eq!(exact, plain);
1800        let mut short = vec![0u8; plain.len() - 1];
1801        assert!(gzip_into(&member, &mut short).is_err());
1802    }
1803
1804    /// A member concatenated after an indexed stream is part of the file.
1805    /// The parallel reader used to stop at the index and drop it.
1806    #[test]
1807    fn a_trailing_member_is_not_dropped() {
1808        let plain = b"frame-one\n".repeat(40);
1809        let extra = b"frame-two\n".repeat(20);
1810        let mut expect = plain.clone();
1811        expect.extend_from_slice(&extra);
1812
1813        let indexed = codec_deflate(&plain, 2, 2, true).unwrap();
1814        let extra_gzip = {
1815            let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1816            enc.write_all(&extra).unwrap();
1817            enc.finish().unwrap()
1818        };
1819        assert_eq!(
1820            with_serial_decode(|| codec_inflate(&extra_gzip, 1)).unwrap(),
1821            extra
1822        );
1823        let mut gzip = indexed.clone();
1824        gzip.extend_from_slice(&extra_gzip);
1825        let serial = with_serial_decode(|| codec_inflate(&gzip, 1)).unwrap();
1826        let markers = |bytes: &[u8]| bytes.windows(2).filter(|w| *w == b"\x1f\x8b").count();
1827        assert_eq!(
1828            (
1829                markers(&indexed),
1830                markers(&gzip),
1831                serial.len(),
1832                plain.len(),
1833                extra.len()
1834            ),
1835            (2, 3, expect.len(), plain.len(), extra.len()),
1836            "member scan"
1837        );
1838        assert!(
1839            serial.starts_with(&plain) && serial.ends_with(&extra),
1840            "len {} plain {} extra {} tail {}",
1841            serial.len(),
1842            plain.len(),
1843            extra.len(),
1844            String::from_utf8_lossy(&serial[serial.len().saturating_sub(24)..])
1845        );
1846        assert_eq!(codec_inflate(&gzip, 4).unwrap(), expect);
1847        let mut truncated = indexed;
1848        truncated.extend_from_slice(&extra_gzip[..8]);
1849        assert!(with_serial_decode(|| codec_inflate(&truncated, 1)).is_err());
1850        assert!(codec_inflate(&truncated, 4).is_err());
1851
1852        #[cfg(feature = "zstd")]
1853        {
1854            let indexed = codec_deflate(&plain, 2, 2, false).unwrap();
1855            let extra_zstd = zstd::stream::encode_all(extra.as_slice(), 3).unwrap();
1856            let mut zstd_bytes = indexed.clone();
1857            zstd_bytes.extend_from_slice(&extra_zstd);
1858            assert_eq!(
1859                with_serial_decode(|| codec_inflate(&zstd_bytes, 1)).unwrap(),
1860                expect
1861            );
1862            assert_eq!(codec_inflate(&zstd_bytes, 4).unwrap(), expect);
1863            let mut truncated = indexed;
1864            truncated.extend_from_slice(&extra_zstd[..8]);
1865            assert!(with_serial_decode(|| codec_inflate(&truncated, 1)).is_err());
1866            assert!(codec_inflate(&truncated, 4).is_err());
1867        }
1868    }
1869
1870    fn mapped_text(path: &Path) -> Result<String, String> {
1871        let contents = read_file_contents(path).map_err(|e| e.to_string())?;
1872        contents
1873            .as_str()
1874            .map(str::to_owned)
1875            .map_err(|e| e.to_string())
1876    }
1877
1878    #[test]
1879    fn compressed_text_that_is_not_utf8_is_rejected() {
1880        let dir = tempfile::tempdir().unwrap();
1881        let raw = b"Cu \xff";
1882        let gz = dir.path().join("bad.con.gz");
1883        {
1884            let mut enc = flate2::write::GzEncoder::new(
1885                std::fs::File::create(&gz).unwrap(),
1886                flate2::Compression::default(),
1887            );
1888            enc.write_all(raw).unwrap();
1889            enc.finish().unwrap();
1890        }
1891        let err = read_file_text(&gz).unwrap_err().to_string();
1892        assert!(err.contains("invalid utf-8"), "{err}");
1893        #[cfg(feature = "zstd")]
1894        {
1895            let zst = dir.path().join("bad.con.zst");
1896            std::fs::write(&zst, zstd::stream::encode_all(&raw[..], 3).unwrap()).unwrap();
1897            let err = read_file_text(&zst).unwrap_err().to_string();
1898            assert!(err.contains("invalid utf-8"), "{err}");
1899        }
1900    }
1901
1902    /// File-backed maps are not available under Miri.
1903    #[test]
1904    #[cfg(not(miri))]
1905    fn dontneed_outside_a_rayon_pool_keeps_the_bytes() {
1906        let dir = tempfile::tempdir().unwrap();
1907        let path = dir.path().join("wide.con");
1908        let bytes = large_text();
1909        std::fs::write(&path, &bytes).unwrap();
1910        let file = std::fs::File::open(&path).unwrap();
1911        let map = unsafe { memmap2::Mmap::map(&file).unwrap() };
1912        advise_dontneed_parallel(&map, 4);
1913        assert_eq!(&map[..bytes.len()], bytes.as_slice());
1914    }
1915
1916    #[test]
1917    fn file_text_matches_the_mapped_read() {
1918        let dir = tempfile::tempdir().unwrap();
1919        let small = dir.path().join("small.con");
1920        std::fs::write(&small, include_bytes!("../resources/test/tiny_cuh2.con")).unwrap();
1921        let large = dir.path().join("large.con");
1922        std::fs::write(&large, large_text()).unwrap();
1923        assert!(matches!(
1924            read_file_contents(&large).unwrap(),
1925            FileContents::Mapped(_)
1926        ));
1927        let gz = dir.path().join("large.con.gz");
1928        let mut enc = gzip_writer(&gz).unwrap();
1929        enc.write_all(&large_text()).unwrap();
1930        enc.finish().unwrap();
1931        for path in [&small, &large, &gz] {
1932            let text = read_file_text(path).unwrap();
1933            assert_eq!(Ok(text), mapped_text(path), "{}", path.display());
1934        }
1935    }
1936
1937    #[test]
1938    fn file_text_reports_invalid_utf8_as_the_mapped_read() {
1939        let dir = tempfile::tempdir().unwrap();
1940        for (name, len) in [("small.con", 100), ("large.con", large_text().len())] {
1941            let mut bytes = large_text()[..len].to_vec();
1942            bytes[len - 40] = 0xff;
1943            let path = dir.path().join(name);
1944            std::fs::write(&path, &bytes).unwrap();
1945            let err = read_file_text(&path).unwrap_err().to_string();
1946            assert_eq!(Err(err), mapped_text(&path), "{name}");
1947        }
1948    }
1949
1950    #[test]
1951    fn forward_text_reads_back_released_pages() {
1952        let dir = tempfile::tempdir().unwrap();
1953        let bytes = text_of_at_least(RELEASE_STEP + (200 << 10));
1954        let path = dir.path().join("two-steps.con");
1955        std::fs::write(&path, &bytes).unwrap();
1956        let mut mapped = ForwardText::open(&path, true).unwrap();
1957        assert!(matches!(mapped.source, ByteSource::Map(_)));
1958        assert_eq!(mapped.as_bytes(), bytes.as_slice());
1959        for pos in (0..=bytes.len()).step_by(1 << 20) {
1960            mapped.release_before(pos).unwrap();
1961        }
1962        assert_eq!(mapped.released, RELEASE_STEP);
1963        assert_eq!(mapped.as_bytes(), bytes.as_slice());
1964        let owned = ForwardText::open(&path, false).unwrap();
1965        assert!(matches!(owned.source, ByteSource::Buf(_)));
1966        assert_eq!(owned.as_bytes(), mapped.as_bytes());
1967    }
1968
1969    /// The guard is private anonymous memory right after the file map, which
1970    /// `MADV_DONTNEED` would zero.
1971    ///
1972    /// The kernel puts a new map at the top of the highest free gap that fits
1973    /// it. The test frees the space below the guard after it fills every gap
1974    /// above, so the file map must end at the guard. A map made by another
1975    /// test thread in between would take that space, so the test body runs
1976    /// alone in a child process of this test binary.
1977    #[cfg(target_os = "linux")]
1978    #[test]
1979    fn release_before_past_the_end_leaves_the_next_mapping_alone() {
1980        const NAME: &str =
1981            "compression::tests::release_before_past_the_end_leaves_the_next_mapping_alone";
1982        const CHILD: &str = "READCON_RELEASE_TEST_CHILD";
1983        if std::env::var_os(CHILD).is_none() {
1984            let out = std::process::Command::new(std::env::current_exe().unwrap())
1985                .args([NAME, "--exact", "--test-threads=1"])
1986                .env(CHILD, "1")
1987                .output()
1988                .unwrap();
1989            let stdout = String::from_utf8_lossy(&out.stdout);
1990            assert!(
1991                out.status.success() && stdout.contains("test result: ok. 1 passed;"),
1992                "{stdout}{}",
1993                String::from_utf8_lossy(&out.stderr)
1994            );
1995            return;
1996        }
1997        const GUARD: usize = 1 << 20;
1998        let dir = tempfile::tempdir().unwrap();
1999        let bytes = text_of_at_least(3 * MMAP_THRESHOLD as usize);
2000        let path = dir.path().join("short.con");
2001        std::fs::write(&path, &bytes).unwrap();
2002        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;
2003        let map_len = bytes.len().next_multiple_of(page);
2004        let anonymous = |len: usize| {
2005            let map = unsafe {
2006                libc::mmap(
2007                    std::ptr::null_mut(),
2008                    len,
2009                    libc::PROT_READ | libc::PROT_WRITE,
2010                    libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
2011                    -1,
2012                    0,
2013                )
2014            };
2015            assert_ne!(map, libc::MAP_FAILED);
2016            map
2017        };
2018        let region = anonymous(map_len + GUARD);
2019        let guard =
2020            unsafe { std::slice::from_raw_parts_mut(region.cast::<u8>().add(map_len), GUARD) };
2021        guard.fill(0xab);
2022        // Each filler takes the highest gap that fits the file map. The first
2023        // one below the region shows that no such gap is left above it.
2024        let mut fillers = Vec::new();
2025        loop {
2026            let filler = anonymous(map_len);
2027            if filler < region {
2028                unsafe { libc::munmap(filler, map_len) };
2029                break;
2030            }
2031            fillers.push(filler);
2032        }
2033        unsafe { libc::munmap(region, map_len) };
2034        let mut text = ForwardText::open(&path, true).unwrap();
2035        assert!(
2036            std::ptr::eq(text.as_bytes().as_ptr(), region.cast::<u8>()),
2037            "the file map does not end at the guard"
2038        );
2039        for pos in [bytes.len() + RELEASE_STEP, 3 * RELEASE_STEP, usize::MAX] {
2040            text.release_before(pos).unwrap();
2041        }
2042        assert_eq!(text.released, bytes.len());
2043        assert!(guard.iter().all(|&b| b == 0xab));
2044        assert_eq!(text.as_bytes(), bytes.as_slice());
2045        unsafe { libc::munmap(guard.as_mut_ptr().cast(), GUARD) };
2046        for filler in fillers {
2047            unsafe { libc::munmap(filler, map_len) };
2048        }
2049    }
2050
2051    #[test]
2052    fn forward_text_leaves_invalid_utf8_for_the_parser() {
2053        let dir = tempfile::tempdir().unwrap();
2054        let mut bytes = text_of_at_least(RELEASE_STEP + (200 << 10));
2055        let at = bytes.len() - 100;
2056        bytes[at] = 0xc3;
2057        let path = dir.path().join("bad.con");
2058        std::fs::write(&path, &bytes).unwrap();
2059        for map in [true, false] {
2060            let text = ForwardText::open(&path, map).unwrap();
2061            assert_eq!(text.as_bytes(), bytes.as_slice(), "map {map}");
2062            assert!(text.as_str().is_err(), "map {map}");
2063        }
2064    }
2065
2066    #[test]
2067    fn skippable_frame_magic_is_zstd() {
2068        assert_eq!(
2069            detect_compression(&[0x50, 0x2a, 0x4d, 0x18]),
2070            Compression::Zstd
2071        );
2072        assert_eq!(
2073            detect_compression(&[0x5f, 0x2a, 0x4d, 0x18]),
2074            Compression::Zstd
2075        );
2076        assert_eq!(
2077            detect_compression(&[0x4f, 0x2a, 0x4d, 0x18]),
2078            Compression::None
2079        );
2080        assert_eq!(detect_compression(&[0x50, 0x2a, 0x4d]), Compression::None);
2081        assert_eq!(
2082            detect_compression(&[0x28, 0xb5, 0x2f, 0xfd]),
2083            Compression::Zstd
2084        );
2085    }
2086
2087    fn skippable_prefix(nibble: u8, payload: &[u8]) -> Vec<u8> {
2088        let mut bytes = Vec::new();
2089        bytes.extend_from_slice(&(0x184D_2A50u32 + u32::from(nibble)).to_le_bytes());
2090        bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
2091        bytes.extend_from_slice(payload);
2092        bytes
2093    }
2094
2095    #[cfg(not(feature = "zstd"))]
2096    #[test]
2097    fn a_leading_skippable_frame_needs_the_zstd_feature() {
2098        let dir = tempfile::tempdir().unwrap();
2099        let path = dir.path().join("skip-first.zst");
2100        std::fs::write(&path, skippable_prefix(0, b"index")).unwrap();
2101        let err = read_file_text(&path).unwrap_err().to_string();
2102        assert!(err.contains("zstd-compressed input detected"), "{err}");
2103        match open_decoded(&path) {
2104            Err(err) => {
2105                assert!(
2106                    err.to_string().contains("zstd-compressed input detected"),
2107                    "{err}"
2108                );
2109            }
2110            Ok(_) => panic!("a skippable frame was treated as uncompressed"),
2111        }
2112    }
2113
2114    #[cfg(feature = "zstd")]
2115    #[test]
2116    fn a_leading_skippable_frame_decodes_with_the_frames_after_it() {
2117        let text = include_str!("../resources/test/tiny_cuh2.con");
2118        let frame = zstd::stream::encode_all(text.as_bytes(), 1).unwrap();
2119        let dir = tempfile::tempdir().unwrap();
2120        let first = dir.path().join("skip-first.con.zst");
2121        let mut bytes = skippable_prefix(0, b"index");
2122        bytes.extend_from_slice(&frame);
2123        std::fs::write(&first, &bytes).unwrap();
2124        assert_eq!(read_file_text(&first).unwrap(), text);
2125        let frames = crate::iterators::read_all_frames(&first).unwrap();
2126        assert_eq!(frames.len(), 1);
2127
2128        let mut between = frame.clone();
2129        between.extend(skippable_prefix(0, b"index"));
2130        between.extend_from_slice(&frame);
2131        let mid = dir.path().join("skip-between.con.zst");
2132        std::fs::write(&mid, &between).unwrap();
2133        assert_eq!(read_file_text(&mid).unwrap(), format!("{text}{text}"));
2134    }
2135
2136    fn gzip_member_count(bytes: &[u8]) -> usize {
2137        let mut rest = bytes;
2138        let mut count = 0;
2139        while !rest.is_empty() {
2140            let mut decoder = flate2::bufread::GzDecoder::new(rest);
2141            let mut out = Vec::new();
2142            std::io::Read::read_to_end(&mut decoder, &mut out).unwrap();
2143            let next = decoder.into_inner();
2144            assert!(
2145                next.len() < rest.len() || out.is_empty(),
2146                "gzip member did not consume input"
2147            );
2148            if next.len() == rest.len() {
2149                break;
2150            }
2151            rest = next;
2152            count += 1;
2153        }
2154        count
2155    }
2156
2157    #[test]
2158    fn indexed_gzip_members_are_cut_on_newlines() {
2159        let mut data = Vec::new();
2160        for i in 0..50_000 {
2161            writeln!(data, "Cu {i}.0 2.0 3.0 0 {i}").unwrap();
2162        }
2163        assert!(data.len() > (1 << 20));
2164        let dir = tempfile::tempdir().unwrap();
2165        let path = dir.path().join("wide.con.gz");
2166        let members = write_gzip_members_n(&path, &data, 8).unwrap();
2167        assert!(members > 1, "a wide payload is more than one gzip member");
2168        let bytes = std::fs::read(&path).unwrap();
2169        let starts = gzip_member_starts(&bytes).expect("index").starts;
2170        assert_eq!(starts.len(), members);
2171        let mut plain = Vec::new();
2172        for (index, start) in starts.iter().copied().enumerate() {
2173            let end = starts.get(index + 1).copied().unwrap_or(bytes.len());
2174            let part = gunzip_member(&bytes[start..end]).unwrap();
2175            assert!(
2176                part.ends_with(b"\n"),
2177                "member {index} ends mid-line ({} bytes)",
2178                part.len()
2179            );
2180            plain.extend_from_slice(&part);
2181        }
2182        assert_eq!(plain, data);
2183    }
2184
2185    #[test]
2186    fn a_short_indexed_plain_length_uses_the_serial_decoder() {
2187        let data = b"Cu 1.0 2.0 3.0 0 1\nH 4.0 5.0 6.0 0 2\n".repeat(8);
2188        let dir = tempfile::tempdir().unwrap();
2189        let path = dir.path().join("short-index.con.gz");
2190        assert!(write_gzip_members_n(&path, &data, 2).unwrap() > 1);
2191        let mut bytes = std::fs::read(&path).unwrap();
2192        assert_eq!(gunzip_all(&bytes).unwrap(), data);
2193        let at = bytes
2194            .windows(4)
2195            .position(|window| window == b"RCZ1")
2196            .expect("index");
2197        let count = u16::from_le_bytes([bytes[at + 4], bytes[at + 5]]) as usize;
2198        let len_at = at + 6 + 8 * count;
2199        let len = u64::from_le_bytes(bytes[len_at..len_at + 8].try_into().unwrap());
2200        assert!(len > 1);
2201        bytes[len_at..len_at + 8].copy_from_slice(&(len - 1).to_le_bytes());
2202        // A short plain length fails the indexed slice, then the serial
2203        // decoder still returns the member. A truncated tail does not.
2204        assert_eq!(gunzip_all(&bytes).unwrap(), data);
2205        bytes.truncate(bytes.len().saturating_sub(8).max(1));
2206        assert!(gunzip_all(&bytes).is_err());
2207    }
2208
2209    #[test]
2210    fn a_gzip_trailer_cut_by_one_to_eight_bytes_fails_both_decoders() {
2211        let data = b"Cu 1.0 2.0 3.0 0 1\n".repeat(64);
2212        let member = gzip_member(&data).unwrap();
2213        assert_eq!(gunzip_member(&member).unwrap(), data);
2214        for cut in 1..=8 {
2215            let short = &member[..member.len() - cut];
2216            assert!(
2217                gunzip_member(short).is_err(),
2218                "one member cut by {cut} bytes"
2219            );
2220            let one = with_serial_decode(|| codec_inflate(short, 1));
2221            assert!(one.is_err(), "one-thread cut by {cut} bytes: {one:?}");
2222        }
2223        let dir = tempfile::tempdir().unwrap();
2224        let path = dir.path().join("indexed.con.gz");
2225        assert!(write_gzip_members_n(&path, &data, 4).unwrap() > 1);
2226        let indexed = std::fs::read(&path).unwrap();
2227        assert_eq!(codec_inflate(&indexed, 4).unwrap(), data);
2228        assert_eq!(
2229            with_serial_decode(|| codec_inflate(&indexed, 1)).unwrap(),
2230            data
2231        );
2232        for cut in 1..=8 {
2233            let short = &indexed[..indexed.len() - cut];
2234            let parallel = codec_inflate(short, 4);
2235            assert!(
2236                parallel.is_err(),
2237                "indexed slice cut by {cut} bytes: {parallel:?}"
2238            );
2239            let one = with_serial_decode(|| codec_inflate(short, 1));
2240            assert!(one.is_err(), "one-thread file cut by {cut} bytes: {one:?}");
2241        }
2242    }
2243
2244    #[test]
2245    fn one_member_gzip_matches_the_streaming_encoder() {
2246        let data = b"Cu 1.0 2.0 3.0 0 1\n".repeat(32);
2247        let direct = gzip_member(&data).unwrap();
2248        let dir = tempfile::tempdir().unwrap();
2249        let path = dir.path().join("one.con.gz");
2250        assert_eq!(write_gzip_members_n(&path, &data, 1).unwrap(), 1);
2251        assert_eq!(std::fs::read(&path).unwrap(), direct);
2252        let auto = dir.path().join("auto.con.gz");
2253        assert_eq!(write_gzip_members(&auto, &data).unwrap(), 1);
2254        assert_eq!(std::fs::read(&auto).unwrap(), direct);
2255    }
2256
2257    #[test]
2258    fn default_deflate_threads_stay_within_the_machine() {
2259        let cores = std::thread::available_parallelism()
2260            .map(|count| count.get())
2261            .unwrap_or(1)
2262            .max(1);
2263        assert_eq!(default_deflate_threads(1), 1);
2264        assert_eq!(default_deflate_threads(cores.saturating_mul(4)), cores);
2265        assert!(default_deflate_threads(64) <= cores);
2266    }
2267
2268    #[test]
2269    fn gzip_worker_count_does_not_change_the_bytes() {
2270        let mut data = Vec::new();
2271        for i in 0..20_000 {
2272            writeln!(data, "Cu {i}.25 1.5 2.5 0 {i}").unwrap();
2273        }
2274        let dir = tempfile::tempdir().unwrap();
2275        let one = dir.path().join("t1.con.gz");
2276        let eight = dir.path().join("t8.con.gz");
2277        write_gzip_members_limited(&one, &data, 8, 1).unwrap();
2278        write_gzip_members_limited(&eight, &data, 8, 8).unwrap();
2279        assert_eq!(std::fs::read(&one).unwrap(), std::fs::read(&eight).unwrap());
2280        assert_eq!(read_file_bytes(&one).unwrap(), data);
2281    }
2282
2283    #[test]
2284    fn chunked_gzip_roundtrips_at_level_6_with_one_member_per_slice() {
2285        // A single gzip member of this payload is the old streaming writer.
2286        // Four members is the chunked level-6 writer.
2287        let unit = b"Cu 1.0 2.0 3.0 0 1\n";
2288        let data = unit.repeat(80_000);
2289        assert!(data.len() > (1 << 20));
2290        let dir = tempfile::tempdir().unwrap();
2291        let path = dir.path().join("wide.con.gz");
2292        let members = write_gzip_members(&path, &data).unwrap();
2293        assert!(
2294            members > 1,
2295            "a wide payload must be more than one gzip member"
2296        );
2297        let bytes = std::fs::read(&path).unwrap();
2298        assert_eq!(gzip_member_count(&bytes), members);
2299        assert_eq!(bytes[8], 0, "XFL 0 is gzip level 6, not the fast level");
2300        assert_eq!(read_file_bytes(&path).unwrap(), data);
2301    }
2302
2303    #[cfg(feature = "zstd")]
2304    #[test]
2305    fn chunked_zstd_roundtrips_at_level_3() {
2306        let data = b"0.0 1.0 2.0 0 0\n".repeat(80_000);
2307        let dir = tempfile::tempdir().unwrap();
2308        let path = dir.path().join("wide.con.zst");
2309        let members = write_zstd_members(&path, &data).unwrap();
2310        assert!(members > 1);
2311        assert_eq!(read_file_bytes(&path).unwrap(), data);
2312        assert_eq!(
2313            with_serial_decode(|| read_file_bytes(&path).unwrap()),
2314            data,
2315            "serial decode of an indexed file matches the parallel decode"
2316        );
2317    }
2318
2319    #[test]
2320    fn a_single_gzip_stream_without_an_index_still_reads() {
2321        let text = include_str!("../resources/test/tiny_cuh2.con");
2322        let dir = tempfile::tempdir().unwrap();
2323        let path = dir.path().join("one.con.gz");
2324        {
2325            let mut writer = gzip_writer(&path).unwrap();
2326            writer.write_all(text.as_bytes()).unwrap();
2327            writer.finish().unwrap();
2328        }
2329        let bytes = std::fs::read(&path).unwrap();
2330        assert!(gzip_member_starts(&bytes).is_none());
2331        assert_eq!(read_file_text(&path).unwrap(), text);
2332        assert_eq!(read_file_bytes(&path).unwrap(), text.as_bytes());
2333    }
2334
2335    #[test]
2336    fn a_foreign_multi_member_gzip_without_our_index_still_reads() {
2337        let mut bytes = gzip_member(b"alpha\n").unwrap();
2338        bytes.extend(gzip_member(b"beta\n").unwrap());
2339        assert!(gzip_member_starts(&bytes).is_none());
2340        let dir = tempfile::tempdir().unwrap();
2341        let path = dir.path().join("foreign.con.gz");
2342        std::fs::write(&path, &bytes).unwrap();
2343        assert_eq!(read_file_bytes(&path).unwrap(), b"alpha\nbeta\n");
2344    }
2345
2346    #[cfg(feature = "zstd")]
2347    #[test]
2348    fn a_single_zstd_frame_without_an_index_still_reads() {
2349        let text = include_str!("../resources/test/tiny_cuh2.con");
2350        let dir = tempfile::tempdir().unwrap();
2351        let path = dir.path().join("one.con.zst");
2352        std::fs::write(&path, zstd::stream::encode_all(text.as_bytes(), 3).unwrap()).unwrap();
2353        assert!(zstd_frame_starts(&std::fs::read(&path).unwrap()).is_none());
2354        assert_eq!(read_file_text(&path).unwrap(), text);
2355    }
2356
2357    fn cli_stdout(program: &str, args: &[&str]) -> std::process::Output {
2358        std::process::Command::new(program)
2359            .args(args)
2360            .output()
2361            .unwrap_or_else(|err| panic!("{program} failed to start: {err}"))
2362    }
2363
2364    #[test]
2365    fn gzip_cli_decodes_one_member_and_an_indexed_file() {
2366        let text = include_str!("../resources/test/tiny_cuh2.con");
2367        let wide = b"Cu 1.0 2.0 3.0 0 1\n".repeat(80_000);
2368        let dir = tempfile::tempdir().unwrap();
2369        let one = dir.path().join("one.con.gz");
2370        {
2371            let mut writer = gzip_writer(&one).unwrap();
2372            writer.write_all(text.as_bytes()).unwrap();
2373            writer.finish().unwrap();
2374        }
2375        let many = dir.path().join("wide.con.gz");
2376        write_gzip_members(&many, &wide).unwrap();
2377        for (path, expect) in [(&one, text.as_bytes()), (&many, wide.as_slice())] {
2378            let out = cli_stdout("gzip", &["-dc", path.to_str().unwrap()]);
2379            assert!(
2380                out.status.success(),
2381                "{}",
2382                String::from_utf8_lossy(&out.stderr)
2383            );
2384            assert_eq!(out.stdout, expect);
2385        }
2386    }
2387
2388    #[cfg(feature = "zstd")]
2389    #[test]
2390    fn zstd_cli_decodes_one_frame_and_an_indexed_file() {
2391        let text = include_str!("../resources/test/tiny_cuh2.con");
2392        let wide = b"0.0 1.0 2.0 0 0\n".repeat(80_000);
2393        let dir = tempfile::tempdir().unwrap();
2394        let one = dir.path().join("one.con.zst");
2395        std::fs::write(&one, zstd::stream::encode_all(text.as_bytes(), 3).unwrap()).unwrap();
2396        let many = dir.path().join("wide.con.zst");
2397        write_zstd_members(&many, &wide).unwrap();
2398        for (path, expect) in [(&one, text.as_bytes()), (&many, wide.as_slice())] {
2399            let out = cli_stdout("zstd", &["-dc", path.to_str().unwrap()]);
2400            assert!(
2401                out.status.success(),
2402                "{}",
2403                String::from_utf8_lossy(&out.stderr)
2404            );
2405            assert_eq!(out.stdout, expect);
2406        }
2407    }
2408
2409    fn copper_frame(n: usize) -> crate::types::ConFrame {
2410        let mut builder =
2411            crate::types::ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
2412        for i in 0..n {
2413            builder.add_atom(
2414                "Cu",
2415                i as f64,
2416                0.25,
2417                0.5,
2418                [false, false, false],
2419                i as u64,
2420                63.546,
2421            );
2422        }
2423        builder.build().unwrap()
2424    }
2425
2426    fn coords(frame: &crate::types::ConFrame) -> Vec<f64> {
2427        (0..frame.atom_data.len())
2428            .flat_map(|index| frame.xyz_at(index))
2429            .collect()
2430    }
2431
2432    #[test]
2433    fn fused_gzip_round_trips_an_odd_atom_count_on_one_and_many_threads() {
2434        let frame = copper_frame(5);
2435        let dir = tempfile::tempdir().unwrap();
2436        let path = dir.path().join("odd.con.gz");
2437        let members = write_fused_gzip_frame(&path, &frame, 3, 2).unwrap();
2438        assert!(members >= 2);
2439        let one = crate::iterators::read_all_frames_phased(&path, Some(1)).unwrap();
2440        let many = crate::iterators::read_all_frames_phased(&path, Some(4)).unwrap();
2441        assert_eq!(one.frames.len(), 1);
2442        assert_eq!(coords(&one.frames[0]), coords(&frame));
2443        assert_eq!(coords(&many.frames[0]), coords(&frame));
2444    }
2445
2446    #[test]
2447    fn fused_gzip_round_trips_two_species_on_many_threads() {
2448        let mut builder =
2449            crate::types::ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
2450        for i in 0..4 {
2451            builder.add_atom("Cu", i as f64, 0.0, 0.0, [false; 3], i as u64, 63.546);
2452        }
2453        for i in 0..3 {
2454            builder.add_atom("H", i as f64, 1.0, 0.0, [false; 3], 4 + i as u64, 1.008);
2455        }
2456        let frame = builder.build().unwrap();
2457        let dir = tempfile::tempdir().unwrap();
2458        let path = dir.path().join("alloy.con.gz");
2459        write_fused_gzip_frame(&path, &frame, 2, 2).unwrap();
2460        let one = crate::iterators::read_all_frames_phased(&path, Some(1)).unwrap();
2461        let many = crate::iterators::read_all_frames_phased(&path, Some(4)).unwrap();
2462        assert_eq!(coords(&one.frames[0]), coords(&frame));
2463        assert_eq!(coords(&many.frames[0]), coords(&frame));
2464        assert_eq!(
2465            many.frames[0].atom_data[0].symbol.as_ref(),
2466            frame.atom_data[0].symbol.as_ref()
2467        );
2468        assert_eq!(
2469            many.frames[0].atom_data[4].symbol.as_ref(),
2470            frame.atom_data[4].symbol.as_ref()
2471        );
2472    }
2473
2474    #[test]
2475    fn fused_worker_count_does_not_change_the_bytes() {
2476        let frame = copper_frame(4_096);
2477        let dir = tempfile::tempdir().unwrap();
2478        let one = dir.path().join("one.con.gz");
2479        let eight = dir.path().join("eight.con.gz");
2480        assert!(write_fused_gzip_frame(&one, &frame, 8, 1).unwrap() > 1);
2481        assert!(write_fused_gzip_frame(&eight, &frame, 8, 8).unwrap() > 1);
2482        assert_eq!(std::fs::read(&one).unwrap(), std::fs::read(&eight).unwrap());
2483        let loaded = crate::iterators::read_all_frames_phased(&eight, Some(8)).unwrap();
2484        assert_eq!(coords(&loaded.frames[0]), coords(&frame));
2485    }
2486
2487    #[cfg(feature = "zstd")]
2488    #[test]
2489    fn fused_zstd_worker_count_does_not_change_the_bytes() {
2490        let frame = copper_frame(4_096);
2491        let dir = tempfile::tempdir().unwrap();
2492        let one = dir.path().join("one.con.zst");
2493        let eight = dir.path().join("eight.con.zst");
2494        assert!(write_fused_zstd_frame(&one, &frame, 8, 1).unwrap() > 1);
2495        assert!(write_fused_zstd_frame(&eight, &frame, 8, 8).unwrap() > 1);
2496        assert_eq!(std::fs::read(&one).unwrap(), std::fs::read(&eight).unwrap());
2497        let loaded = crate::iterators::read_all_frames_phased(&eight, Some(4)).unwrap();
2498        assert_eq!(coords(&loaded.frames[0]), coords(&frame));
2499    }
2500}