Skip to main content

readcon_core/
conbin.rs

1//! CON-bin: one page of header, then every frame's positions as one run
2//! of little-endian values, then the velocities the same way.
3//!
4//! [`map_file`] maps that file and faults it in place. The runs are the
5//! columns: the caller does not allocate a second buffer, so the read does
6//! not take a write fault per destination page. [`read_into_threads`] is the
7//! `pread` fill of a caller-owned slice, kept so a measurement can pair the
8//! two on the same file.
9
10use std::cell::RefCell;
11use std::fs::File;
12use std::io::{IoSlice, Read, Write};
13#[cfg(unix)]
14use std::os::fd::AsRawFd;
15use std::path::Path;
16
17use crate::error::ParseError;
18use crate::iterators::ConFrameIterator;
19
20const MAGIC: &[u8; 8] = b"CONBIN01";
21const VERSION_1: u32 = 1;
22const VERSION_2: u32 = 2;
23const FLAG_F32: u32 = 1;
24const FLAG_VELOCITY: u32 = 2;
25const FLAG_FORCE: u32 = 4;
26const FLAG_MASS: u32 = 8;
27const FLAG_FIXED: u32 = 16;
28const FLAG_CELL: u32 = 32;
29const FLAG_IDS: u32 = 64;
30
31/// Magic, version, flags, frame count, atom count, payload offset.
32/// 8 + 4 + 4 + 8 + 8 + 8.
33const FIELD_BYTES: usize = 40;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct ConBinHeader {
37    pub version: u32,
38    pub n_frames: u64,
39    pub n_atoms: u64,
40    pub binary32: bool,
41    pub velocities: bool,
42    pub forces: bool,
43    pub masses: bool,
44    pub fixed: bool,
45    pub cell: bool,
46    pub atom_ids: bool,
47}
48
49impl ConBinHeader {
50    /// Version 1: positions, and velocities when `velocities` is set.
51    pub fn version1(n_frames: u64, n_atoms: u64, binary32: bool, velocities: bool) -> Self {
52        Self {
53            version: VERSION_1,
54            n_frames,
55            n_atoms,
56            binary32,
57            velocities,
58            forces: false,
59            masses: false,
60            fixed: false,
61            cell: false,
62            atom_ids: false,
63        }
64    }
65
66    fn flags(&self) -> u32 {
67        let mut flags = 0u32;
68        if self.binary32 {
69            flags |= FLAG_F32;
70        }
71        if self.velocities {
72            flags |= FLAG_VELOCITY;
73        }
74        if self.version >= VERSION_2 {
75            if self.forces {
76                flags |= FLAG_FORCE;
77            }
78            if self.masses {
79                flags |= FLAG_MASS;
80            }
81            if self.fixed {
82                flags |= FLAG_FIXED;
83            }
84            if self.cell {
85                flags |= FLAG_CELL;
86            }
87            if self.atom_ids {
88                flags |= FLAG_IDS;
89            }
90        }
91        flags
92    }
93
94    fn elem_width(&self) -> usize {
95        if self.binary32 { 4 } else { 8 }
96    }
97
98    pub fn position_len(&self) -> Result<usize, ParseError> {
99        (self.n_frames as usize)
100            .checked_mul(self.n_atoms as usize)
101            .and_then(|n| n.checked_mul(3))
102            .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))
103    }
104}
105
106/// How the mapped pages are made resident before the caller reads them.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum Prefetch {
109    /// One `MADV_POPULATE_READ` per worker, covering that worker's span.
110    Span,
111    /// `MADV_POPULATE_READ` in queue-sized pieces of each worker's span.
112    ChunkPopulate,
113    /// `posix_fadvise(POSIX_FADV_WILLNEED)` of the next queue-sized piece
114    /// on a private file descriptor, issued before the caller reads.
115    ChunkWillneed,
116    /// Will-need the next piece, then `MADV_POPULATE_READ` the current one.
117    Hybrid,
118}
119
120/// Limits read from the block queue that holds `path`.
121///
122/// `max_request` is `max_sectors_kb` times 1024, the largest request that
123/// queue accepts
124/// (<https://docs.kernel.org/admin-guide/abi-stable.html#abi-sys-block-disk-queue-max-sectors-kb>).
125/// `nr_requests` is how many requests the queue can hold
126/// (<https://docs.kernel.org/admin-guide/abi-stable.html#abi-sys-block-disk-queue-nr-requests>).
127/// `read_ahead` is `read_ahead_kb`
128/// times 1024, the kernel readahead window. A partition is walked to its
129/// parent disk, which is the sysfs node that holds `queue/`. A missing
130/// queue file yields the page size, the unit `madvise` accepts, and a
131/// missing `nr_requests` yields 1. `rotational` is recorded and does not
132/// select the plan.
133#[derive(Debug, Clone, Copy)]
134pub struct QueueLimits {
135    pub page: usize,
136    pub logical_block: usize,
137    pub max_request: usize,
138    pub nr_requests: usize,
139    pub read_ahead: usize,
140    /// Hardware queues. blk-mq applies `nr_requests` to each one.
141    pub nr_hw_queues: usize,
142    /// `queue/rotational` is 1 when the queue file says so.
143    /// The flag is recorded. It does not select the read plan.
144    pub rotational: bool,
145}
146
147impl QueueLimits {
148    /// Page-sized stand-in used when the file has no block queue.
149    ///
150    /// btrfs, tmpfs, overlayfs and NFS have no `queue/` directory.
151    /// The page is the unit `madvise` accepts, so one request of one
152    /// page is the stand-in.
153    pub fn page_default(page: usize) -> Self {
154        Self {
155            page,
156            logical_block: page,
157            max_request: page,
158            nr_requests: 1,
159            read_ahead: page,
160            nr_hw_queues: 1,
161            rotational: false,
162        }
163    }
164
165    pub fn of(path: &Path) -> Result<Self, ParseError> {
166        let page = page_size()?;
167        #[cfg(target_os = "linux")]
168        {
169            let file =
170                File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
171            let dev = std::os::unix::fs::MetadataExt::dev(
172                &file
173                    .metadata()
174                    .map_err(|err| ParseError::ValidationError(err.to_string()))?,
175            );
176            Ok(Self::from_sysfs(dev, page))
177        }
178        #[cfg(not(target_os = "linux"))]
179        {
180            let _ = path;
181            Ok(Self::page_default(page))
182        }
183    }
184
185    #[cfg(target_os = "linux")]
186    fn from_sysfs(dev: u64, page: usize) -> Self {
187        let num =
188            |name: &str| queue_text(dev, name).and_then(|text| text.trim().parse::<usize>().ok());
189        let logical = num("logical_block_size").unwrap_or(page).max(1);
190        let max_request = num("max_sectors_kb")
191            .map(|kb| kb.saturating_mul(1024))
192            .unwrap_or(page)
193            .max(page);
194        let nr_requests = num("nr_requests").unwrap_or(1).max(1);
195        let read_ahead = num("read_ahead_kb")
196            .map(|kb| kb.saturating_mul(1024))
197            .unwrap_or(page)
198            .max(page);
199        let rotational = num("rotational").unwrap_or(0) != 0;
200        Self {
201            page,
202            logical_block: logical,
203            max_request,
204            nr_requests,
205            read_ahead,
206            nr_hw_queues: hw_queue_count(dev),
207            rotational,
208        }
209    }
210
211    /// Bytes one worker submits while the others share the same queue.
212    ///
213    /// The queue holds `nr_requests` requests of `max_request` bytes.
214    /// `workers` share it, so each gets `nr_requests / workers` requests,
215    /// or one request when the queue is shorter than the worker count.
216    /// The span is at least the kernel readahead window, because a shorter
217    /// hint still pulls that window, and it is aligned down to the page.
218    pub fn worker_span(&self, workers: usize) -> usize {
219        let workers = workers.max(1);
220        let requests = (self.nr_requests / workers).max(1);
221        let queued = requests.saturating_mul(self.max_request);
222        let span = queued.max(self.read_ahead).max(self.page);
223        let aligned = span & !(self.page - 1);
224        aligned.max(self.page)
225    }
226}
227
228#[cfg(target_os = "linux")]
229pub(crate) fn dev_nums(dev: u64) -> (u64, u64) {
230    // glibc `sys/sysmacros.h`, the encoding major(3) documents.
231    let major = ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0xfff);
232    let minor = ((dev >> 12) & 0xffff_ff00) | (dev & 0xff);
233    (major, minor)
234}
235
236/// `queue/nr_hw_queues` when the file exists. Otherwise the number of
237/// directories under `mq/`, which blk-mq creates, one per hardware queue.
238/// A missing tree means one queue.
239#[cfg(target_os = "linux")]
240fn hw_queue_count(dev: u64) -> usize {
241    if let Some(text) = queue_text(dev, "nr_hw_queues")
242        && let Ok(count) = text.trim().parse::<usize>()
243    {
244        return count.max(1);
245    }
246    let (major, minor) = dev_nums(dev);
247    let mut dir = std::path::PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
248    if dir.join("partition").is_file() {
249        dir.push("..");
250    }
251    let mq = dir.join("mq");
252    let count = std::fs::read_dir(&mq)
253        .ok()
254        .map(|entries| entries.filter_map(|entry| entry.ok()).count())
255        .unwrap_or(0);
256    count.max(1)
257}
258
259/// Read one queue file. A partition node has `partition` and no `queue`.
260/// Its parent is the disk, and that directory holds `queue/`.
261/// `Documentation/admin-guide/devices.rst` describes the block sysfs tree.
262#[cfg(target_os = "linux")]
263fn queue_text(dev: u64, name: &str) -> Option<String> {
264    let (major, minor) = dev_nums(dev);
265    let dir = std::path::PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
266    let own = dir.join("queue").join(name);
267    if let Ok(text) = std::fs::read_to_string(&own) {
268        return Some(text);
269    }
270    if dir.join("partition").is_file() {
271        let parent = dir.join("..").join("queue").join(name);
272        if let Ok(text) = std::fs::read_to_string(&parent) {
273            return Some(text);
274        }
275    }
276    None
277}
278
279/// Host page size. `madvise` rejects an address that is not a multiple of it.
280fn page_size() -> Result<usize, ParseError> {
281    #[cfg(unix)]
282    let page = {
283        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
284        if page <= 0 {
285            return Err(ParseError::ValidationError(
286                "sysconf(SC_PAGESIZE) failed".into(),
287            ));
288        }
289        page as usize
290    };
291    #[cfg(windows)]
292    let page = {
293        // dwPageSize is the DWORD after the 4-byte architecture union in
294        // SYSTEM_INFO, on both 32-bit and 64-bit Windows.
295        // https://learn.microsoft.com/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
296        #[link(name = "kernel32")]
297        unsafe extern "system" {
298            fn GetSystemInfo(info: *mut std::ffi::c_void);
299        }
300        let mut info = [0u8; 64];
301        unsafe { GetSystemInfo(info.as_mut_ptr().cast()) };
302        u32::from_ne_bytes(info[4..8].try_into().unwrap()) as usize
303    };
304    if !page.is_power_of_two() || page == 0 {
305        return Err(ParseError::ValidationError(
306            "the host page size is not a power of two".into(),
307        ));
308    }
309    Ok(page)
310}
311
312fn header_fields(header: &ConBinHeader, payload_off: u64) -> [u8; FIELD_BYTES] {
313    let mut out = [0u8; FIELD_BYTES];
314    out[..8].copy_from_slice(MAGIC);
315    out[8..12].copy_from_slice(&header.version.to_le_bytes());
316    out[12..16].copy_from_slice(&header.flags().to_le_bytes());
317    out[16..24].copy_from_slice(&header.n_frames.to_le_bytes());
318    out[24..32].copy_from_slice(&header.n_atoms.to_le_bytes());
319    out[32..40].copy_from_slice(&payload_off.to_le_bytes());
320    out
321}
322
323fn parse_fields(bytes: &[u8]) -> Result<(ConBinHeader, u64), ParseError> {
324    if bytes.len() < FIELD_BYTES || &bytes[..8] != MAGIC {
325        return Err(ParseError::ValidationError(
326            "CON-bin header is not CONBIN01".into(),
327        ));
328    }
329    let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
330    if version != VERSION_1 && version != VERSION_2 {
331        return Err(ParseError::ValidationError(format!(
332            "CON-bin version {version} is not {VERSION_1} or {VERSION_2}"
333        )));
334    }
335    let flags = u32::from_le_bytes(bytes[12..16].try_into().unwrap());
336    let offset = u64::from_le_bytes(bytes[32..40].try_into().unwrap());
337    let v2 = version >= VERSION_2;
338    Ok((
339        ConBinHeader {
340            version,
341            n_frames: u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
342            n_atoms: u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
343            binary32: flags & FLAG_F32 != 0,
344            velocities: flags & FLAG_VELOCITY != 0,
345            forces: v2 && flags & FLAG_FORCE != 0,
346            masses: v2 && flags & FLAG_MASS != 0,
347            fixed: v2 && flags & FLAG_FIXED != 0,
348            cell: v2 && flags & FLAG_CELL != 0,
349            atom_ids: v2 && flags & FLAG_IDS != 0,
350        },
351        offset,
352    ))
353}
354
355/// Payload start stored in the header. Any 8-byte alignment inside the
356/// file is accepted, so a file written on a 4 KiB host still opens when
357/// the host page is 16 KiB or 64 KiB. An offset of 0 is not a stand-in
358/// for the host page.
359fn checked_payload_offset(stored: u64, file_len: usize) -> Result<usize, ParseError> {
360    let off = usize::try_from(stored)
361        .map_err(|_| ParseError::ValidationError("CON-bin payload offset does not fit".into()))?;
362    if off < FIELD_BYTES || off > file_len || off % 8 != 0 {
363        return Err(ParseError::ValidationError(
364            "CON-bin payload offset is not an 8-byte aligned address inside the file".into(),
365        ));
366    }
367    Ok(off)
368}
369
370#[derive(Clone, Copy)]
371struct F64Payload {
372    offset: usize,
373    end: usize,
374}
375
376/// Binary64 columns with a velocity run. Binary32 and a missing velocity
377/// run are errors: `sum_mapped` reads those two binary64 runs.
378fn f64_payload(header_bytes: &[u8], file_len: usize) -> Result<F64Payload, ParseError> {
379    let (header, stored) = parse_fields(header_bytes)?;
380    if header.binary32 {
381        return Err(ParseError::ValidationError(
382            "CON-bin file is binary32; sum_mapped reads binary64".into(),
383        ));
384    }
385    if !header.velocities {
386        return Err(ParseError::ValidationError(
387            "CON-bin file has no velocity run".into(),
388        ));
389    }
390    let offset = checked_payload_offset(stored, file_len)?;
391    let values = header
392        .position_len()?
393        .checked_mul(2)
394        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
395    let nbytes = values
396        .checked_mul(8)
397        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
398    let end = offset
399        .checked_add(nbytes)
400        .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
401    if end > file_len {
402        return Err(ParseError::IncompleteFrame);
403    }
404    Ok(F64Payload { offset, end })
405}
406
407/// A mapped CON-bin. The position run and the velocity run are the file.
408pub struct ConBinMap {
409    /// `MAP_PRIVATE` copy-on-write (`MmapOptions::map_copy`). A store copies
410    /// the page and does not write the file.
411    pub map: memmap2::MmapMut,
412    pub header: ConBinHeader,
413    pub payload_off: usize,
414}
415
416impl ConBinMap {
417    pub fn positions_f64(&self) -> Result<&[f64], ParseError> {
418        self.run(std::mem::size_of::<f64>(), 0)
419    }
420
421    pub fn positions_f64_mut(&mut self) -> Result<&mut [f64], ParseError> {
422        self.run_mut(std::mem::size_of::<f64>(), 0)
423    }
424
425    pub fn velocities_f64(&self) -> Result<&[f64], ParseError> {
426        let n = self.header.position_len()?;
427        self.run(std::mem::size_of::<f64>(), n)
428    }
429
430    pub fn positions_f32(&self) -> Result<&[f32], ParseError> {
431        self.run(std::mem::size_of::<f32>(), 0)
432    }
433
434    pub fn velocities_f32(&self) -> Result<&[f32], ParseError> {
435        let n = self.header.position_len()?;
436        self.run(std::mem::size_of::<f32>(), n)
437    }
438
439    /// Byte offset of the first section after positions, velocities and forces.
440    fn after_motion(&self) -> Result<usize, ParseError> {
441        let width = self.header.elem_width();
442        let block = self
443            .header
444            .position_len()?
445            .checked_mul(width)
446            .ok_or_else(|| {
447                ParseError::InvalidCount("CON-bin column byte length overflows".into())
448            })?;
449        let mut at = self
450            .payload_off
451            .checked_add(block)
452            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
453        if self.header.velocities {
454            at = at.checked_add(block).ok_or_else(|| {
455                ParseError::InvalidCount("CON-bin payload offset overflows".into())
456            })?;
457        }
458        if self.header.forces {
459            at = at.checked_add(block).ok_or_else(|| {
460                ParseError::InvalidCount("CON-bin payload offset overflows".into())
461            })?;
462        }
463        Ok(at)
464    }
465
466    fn atoms_per_file(&self) -> Result<usize, ParseError> {
467        (self.header.n_frames as usize)
468            .checked_mul(self.header.n_atoms as usize)
469            .ok_or_else(|| ParseError::InvalidCount("CON-bin atom count overflows".into()))
470    }
471
472    pub fn masses_f64(&self) -> Result<Option<&[f64]>, ParseError> {
473        if !self.header.masses || self.header.binary32 {
474            return Ok(None);
475        }
476        let n = self.atoms_per_file()?;
477        self.view_at(self.after_motion()?, n).map(Some)
478    }
479
480    /// The `(frames, 6)` cell column of a binary64 file, `a b c alpha beta
481    /// gamma` per frame, or `None` when the file has none or is binary32.
482    ///
483    /// # Errors
484    ///
485    /// [`ParseError::NonFiniteValue`] naming the field (`cell[i]`) and the
486    /// frame when the column holds a NaN or an infinity.
487    pub fn cell_f64(&self) -> Result<Option<&[f64]>, ParseError> {
488        if !self.header.cell || self.header.binary32 {
489            return Ok(None);
490        }
491        let mut at = self.after_motion()?;
492        if self.header.masses {
493            let n = self
494                .atoms_per_file()?
495                .checked_mul(8)
496                .ok_or_else(|| ParseError::InvalidCount("CON-bin mass bytes overflow".into()))?;
497            at = at.checked_add(n).ok_or_else(|| {
498                ParseError::InvalidCount("CON-bin payload offset overflows".into())
499            })?;
500        }
501        let n = (self.header.n_frames as usize)
502            .checked_mul(6)
503            .ok_or_else(|| ParseError::InvalidCount("CON-bin cell length overflows".into()))?;
504        let cells = self.view_at::<f64>(at, n)?;
505        // The cell column is six numbers a frame, read once here. A NaN or
506        // an infinity is stored bit for bit in the file, so it is named
507        // before the caller sees the slice.
508        crate::types::check_cell_rows(cells)?;
509        Ok(Some(cells))
510    }
511
512    pub fn atom_ids(&self) -> Result<Option<&[u64]>, ParseError> {
513        if !self.header.atom_ids {
514            return Ok(None);
515        }
516        self.view_at(self.ids_off()?, self.atoms_per_file()?)
517            .map(Some)
518    }
519
520    pub fn fixed_masks(&self) -> Result<Option<&[u8]>, ParseError> {
521        if !self.header.fixed {
522            return Ok(None);
523        }
524        let mut at = self.ids_off()?;
525        if self.header.atom_ids {
526            let n = self
527                .atoms_per_file()?
528                .checked_mul(8)
529                .ok_or_else(|| ParseError::InvalidCount("CON-bin id bytes overflow".into()))?;
530            at = at.checked_add(n).ok_or_else(|| {
531                ParseError::InvalidCount("CON-bin payload offset overflows".into())
532            })?;
533        }
534        self.view_at(at, self.atoms_per_file()?).map(Some)
535    }
536
537    fn ids_off(&self) -> Result<usize, ParseError> {
538        let mut at = self.after_motion()?;
539        let width = self.header.elem_width();
540        if self.header.masses {
541            let n = self
542                .atoms_per_file()?
543                .checked_mul(width)
544                .ok_or_else(|| ParseError::InvalidCount("CON-bin mass bytes overflow".into()))?;
545            at = at.checked_add(n).ok_or_else(|| {
546                ParseError::InvalidCount("CON-bin payload offset overflows".into())
547            })?;
548        }
549        if self.header.cell {
550            let n = (self.header.n_frames as usize)
551                .checked_mul(6)
552                .and_then(|n| n.checked_mul(width))
553                .ok_or_else(|| ParseError::InvalidCount("CON-bin cell bytes overflow".into()))?;
554            at = at.checked_add(n).ok_or_else(|| {
555                ParseError::InvalidCount("CON-bin payload offset overflows".into())
556            })?;
557        }
558        Ok(at)
559    }
560
561    fn view_at<T>(&self, start: usize, n: usize) -> Result<&[T], ParseError> {
562        let nbytes = n.checked_mul(std::mem::size_of::<T>()).ok_or_else(|| {
563            ParseError::InvalidCount("CON-bin column byte length overflows".into())
564        })?;
565        let end = start.checked_add(nbytes).ok_or_else(|| {
566            ParseError::InvalidCount("CON-bin column extends past the file".into())
567        })?;
568        if end > self.map.len() {
569            return Err(ParseError::IncompleteFrame);
570        }
571        let bytes = &self.map[start..end];
572        if bytes.as_ptr().align_offset(std::mem::align_of::<T>()) != 0 {
573            return Err(ParseError::ValidationError(
574                "CON-bin payload is not aligned for its element type".into(),
575            ));
576        }
577        Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<T>(), n) })
578    }
579
580    fn run<T>(&self, width: usize, column: usize) -> Result<&[T], ParseError> {
581        let n = self.header.position_len()?;
582        let start = self
583            .payload_off
584            .checked_add(column.checked_mul(width).ok_or_else(|| {
585                ParseError::InvalidCount("CON-bin column byte length overflows".into())
586            })?)
587            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
588        let nbytes = n.checked_mul(width).ok_or_else(|| {
589            ParseError::InvalidCount("CON-bin column byte length overflows".into())
590        })?;
591        let end = start.checked_add(nbytes).ok_or_else(|| {
592            ParseError::InvalidCount("CON-bin column extends past the file".into())
593        })?;
594        if end > self.map.len() {
595            return Err(ParseError::IncompleteFrame);
596        }
597        let bytes = &self.map[start..end];
598        if !cfg!(target_endian = "little") {
599            return Err(ParseError::ValidationError(
600                "CON-bin is little-endian; this host cannot view it in place".into(),
601            ));
602        }
603        if bytes.as_ptr().align_offset(std::mem::align_of::<T>()) != 0 {
604            return Err(ParseError::ValidationError(
605                "CON-bin payload is not aligned for its element type".into(),
606            ));
607        }
608        // SAFETY: `bytes` is inside the map, its length is a multiple of `T`,
609        // and the pointer is aligned for `T`. The file is little-endian and
610        // the host is little-endian, so the bit pattern is the value.
611        // The map stays borrowed for the returned slice.
612        Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<T>(), n) })
613    }
614
615    fn run_mut<T>(&mut self, width: usize, column: usize) -> Result<&mut [T], ParseError> {
616        let n = self.header.position_len()?;
617        let start = self
618            .payload_off
619            .checked_add(column.checked_mul(width).ok_or_else(|| {
620                ParseError::InvalidCount("CON-bin column byte length overflows".into())
621            })?)
622            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
623        let nbytes = n.checked_mul(width).ok_or_else(|| {
624            ParseError::InvalidCount("CON-bin column byte length overflows".into())
625        })?;
626        let end = start.checked_add(nbytes).ok_or_else(|| {
627            ParseError::InvalidCount("CON-bin column extends past the file".into())
628        })?;
629        if end > self.map.len() {
630            return Err(ParseError::IncompleteFrame);
631        }
632        if !cfg!(target_endian = "little") {
633            return Err(ParseError::ValidationError(
634                "CON-bin is little-endian; this host cannot view it in place".into(),
635            ));
636        }
637        let ptr = self.map[start..end].as_mut_ptr();
638        if ptr.align_offset(std::mem::align_of::<T>()) != 0 {
639            return Err(ParseError::ValidationError(
640                "CON-bin payload is not aligned for its element type".into(),
641            ));
642        }
643        // SAFETY: same alignment and length rules as `run`. The map is
644        // `MAP_PRIVATE`, so stores copy a page and do not write the file.
645        Ok(unsafe { std::slice::from_raw_parts_mut(ptr.cast::<T>(), n) })
646    }
647}
648
649/// Sum both binary64 columns of `path`.
650///
651/// The default is one `readahead` stream.
652/// Two sessions on one boot compared one stream with a stream per span.
653/// Neither plan won at every thread count in both.
654/// The host cache was not controlled.
655/// The default stays one stream, the simpler plan.
656/// `nr_requests` is the depth of each hardware queue (`nr_hw_queues`
657/// of them, blk-mq), not one device-wide pool.
658/// Workers sum a piece after that piece is faulted in, and the piece
659/// sums are added in file order. The header's payload offset, length
660/// and dtype select the bytes. Binary32 and a missing velocity run are
661/// errors. Other platforms map the file and sum it with no `readahead`.
662pub fn sum_mapped(path: &Path, threads: usize) -> Result<f64, ParseError> {
663    #[cfg(target_os = "linux")]
664    {
665        let limits = QueueLimits::of(path)?;
666        sequential_resident_sum(path, threads.max(1), &limits)
667    }
668    #[cfg(not(target_os = "linux"))]
669    {
670        let _ = threads;
671        plain_sum(path)
672    }
673}
674
675#[cfg(not(target_os = "linux"))]
676fn plain_sum(path: &Path) -> Result<f64, ParseError> {
677    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
678    let map = unsafe { memmap2::Mmap::map(&file) }
679        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
680    if map.len() < FIELD_BYTES {
681        return Err(ParseError::ValidationError(
682            "CON-bin header is not CONBIN01".into(),
683        ));
684    }
685    let payload = f64_payload(&map[..FIELD_BYTES], map.len())?;
686    if !cfg!(target_endian = "little") {
687        return Err(ParseError::ValidationError(
688            "CON-bin is little-endian; this host cannot view it in place".into(),
689        ));
690    }
691    let bytes = &map[payload.offset..payload.end];
692    let ptr = bytes.as_ptr();
693    if ptr.align_offset(std::mem::align_of::<f64>()) != 0 {
694        return Err(ParseError::ValidationError(
695            "CON-bin payload is not aligned for its element type".into(),
696        ));
697    }
698    let data = unsafe { std::slice::from_raw_parts(ptr.cast::<f64>(), bytes.len() / 8) };
699    Ok(data.iter().copied().sum())
700}
701
702#[cfg(target_os = "linux")]
703fn sequential_resident_sum(
704    path: &Path,
705    threads: usize,
706    limits: &QueueLimits,
707) -> Result<f64, ParseError> {
708    let owned = open_map(path)?;
709    let page = limits.page;
710    let len = owned.len;
711    let base = owned.ptr as usize;
712    let header =
713        unsafe { std::slice::from_raw_parts(owned.ptr.cast::<u8>(), FIELD_BYTES.min(len)) };
714    let payload = f64_payload(header, len)?;
715    let request = (limits.max_request & !(page - 1)).max(page);
716    let pieces = piece_list(0, len, request);
717    if pages_all_resident(owned.ptr, len, page)? {
718        return Ok(sum_pieces_in_order(
719            base,
720            payload.offset,
721            payload.end,
722            threads,
723            &pieces,
724        ));
725    }
726    // One stream fills the read side of the queue.
727    let depth = limits.nr_requests.max(1);
728    let (tx, rx) = std::sync::mpsc::sync_channel::<usize>(depth);
729    let (err_tx, err_rx) = std::sync::mpsc::channel::<String>();
730    let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));
731    let addr = owned.ptr as usize;
732    let found = std::thread::scope(|scope| {
733        let queued = pieces.clone();
734        scope.spawn(move || {
735            let fd = match File::open(path) {
736                Ok(fd) => fd,
737                Err(err) => {
738                    let _ = err_tx.send(err.to_string());
739                    return;
740                }
741            };
742            // Keep `depth` requests in flight. Submit the next piece only
743            // after the oldest one has been waited on, so the count does not
744            // become depth + 1.
745            let mut submitted = 0usize;
746            while submitted < depth.min(queued.len()) {
747                if let Err(err) = advise_readahead(&fd, queued[submitted].0, queued[submitted].1) {
748                    let _ = err_tx.send(err);
749                    return;
750                }
751                submitted += 1;
752            }
753            for i in 0..queued.len() {
754                let (off, n) = queued[i];
755                if let Err(err) = wait_resident(addr, off, n, page) {
756                    let _ = err_tx.send(err);
757                    return;
758                }
759                let _ = tx.send(i);
760                if submitted < queued.len() {
761                    if let Err(err) =
762                        advise_readahead(&fd, queued[submitted].0, queued[submitted].1)
763                    {
764                        let _ = err_tx.send(err);
765                        return;
766                    }
767                    submitted += 1;
768                }
769            }
770        });
771        let slots = std::sync::Arc::new(std::sync::Mutex::new(vec![0.0f64; pieces.len()]));
772        let mut handles = Vec::with_capacity(threads);
773        for _ in 0..threads {
774            let rx = std::sync::Arc::clone(&rx);
775            let slots = std::sync::Arc::clone(&slots);
776            let pieces = pieces.clone();
777            handles.push(scope.spawn(move || {
778                loop {
779                    let msg = rx.lock().expect("piece queue").recv();
780                    let Ok(index) = msg else { break };
781                    let (off, n) = pieces[index];
782                    let part = sum_range(base, off, off + n, payload.offset, payload.end);
783                    slots.lock().expect("piece sums")[index] = part;
784                }
785            }));
786        }
787        for handle in handles {
788            handle.join().expect("column sum");
789        }
790        let slots = slots.lock().expect("piece sums");
791        slots.iter().copied().sum::<f64>()
792    });
793    if let Ok(err) = err_rx.try_recv() {
794        return Err(ParseError::ValidationError(err));
795    }
796    Ok(found)
797}
798
799/// One `readahead` stream per worker, each over a disjoint span.
800///
801/// The piece is `max_sectors_kb` times 1024. `nr_requests` is the depth
802/// of each hardware queue, so each worker keeps
803/// `max(1, nr_requests / workers)` pieces in flight.
804/// Two sessions on one boot compared one stream with a stream per span.
805/// Neither plan won at every thread count in both.
806/// The host cache was not controlled.
807/// The default stays one stream, the simpler plan.
808#[cfg(target_os = "linux")]
809pub fn sum_split_streams(path: &Path, threads: usize) -> Result<f64, ParseError> {
810    let limits = QueueLimits::of(path)?;
811    split_stream_sum(path, threads.max(1), &limits)
812}
813
814#[cfg(not(target_os = "linux"))]
815pub fn sum_split_streams(path: &Path, threads: usize) -> Result<f64, ParseError> {
816    let _ = threads;
817    plain_sum(path)
818}
819
820#[cfg(target_os = "linux")]
821fn split_stream_sum(path: &Path, threads: usize, limits: &QueueLimits) -> Result<f64, ParseError> {
822    let owned = open_map(path)?;
823    let page = limits.page;
824    let len = owned.len;
825    let base = owned.ptr as usize;
826    let header =
827        unsafe { std::slice::from_raw_parts(owned.ptr.cast::<u8>(), FIELD_BYTES.min(len)) };
828    let payload = f64_payload(header, len)?;
829    let request = (limits.max_request & !(page - 1)).max(page);
830    let ranges = worker_ranges(len, threads, page);
831    if pages_all_resident(owned.ptr, len, page)? {
832        let pieces = piece_list(0, len, request);
833        return Ok(sum_pieces_in_order(
834            base,
835            payload.offset,
836            payload.end,
837            threads,
838            &pieces,
839        ));
840    }
841    let depth = (limits.nr_requests / ranges.len()).max(1);
842    let (err_tx, err_rx) = std::sync::mpsc::channel::<String>();
843    let sum = std::thread::scope(|scope| {
844        let mut handles = Vec::with_capacity(ranges.len());
845        for (span, end) in ranges {
846            let err_tx = err_tx.clone();
847            handles.push(scope.spawn(move || {
848                match stream_one_span(
849                    path,
850                    SpanGeom {
851                        base,
852                        span,
853                        end,
854                        page,
855                        payload_off: payload.offset,
856                        payload_end: payload.end,
857                        request,
858                        depth,
859                    },
860                ) {
861                    Ok(part) => part,
862                    Err(err) => {
863                        let _ = err_tx.send(err);
864                        0.0
865                    }
866                }
867            }));
868        }
869        drop(err_tx);
870        handles
871            .into_iter()
872            .map(|handle| handle.join().expect("split stream"))
873            .sum::<f64>()
874    });
875    if let Ok(err) = err_rx.try_recv() {
876        return Err(ParseError::ValidationError(err));
877    }
878    Ok(sum)
879}
880
881#[cfg(target_os = "linux")]
882struct SpanGeom {
883    base: usize,
884    span: usize,
885    end: usize,
886    page: usize,
887    payload_off: usize,
888    payload_end: usize,
889    request: usize,
890    depth: usize,
891}
892
893#[cfg(target_os = "linux")]
894fn stream_one_span(path: &Path, geom: SpanGeom) -> Result<f64, String> {
895    let SpanGeom {
896        base,
897        span,
898        end,
899        page,
900        payload_off,
901        payload_end,
902        request,
903        depth,
904    } = geom;
905    let fd = File::open(path).map_err(|err| err.to_string())?;
906    let pieces = piece_list(span, end, request);
907    let depth = depth.max(1);
908    let mut next_submit = 0usize;
909    let mut next_sum = 0usize;
910    let mut acc = 0.0f64;
911    while next_sum < pieces.len() {
912        while next_submit < pieces.len() && next_submit - next_sum < depth {
913            let (off, n) = pieces[next_submit];
914            advise_readahead(&fd, off, n)?;
915            next_submit += 1;
916        }
917        let (off, n) = pieces[next_sum];
918        wait_resident(base, off, n, page)?;
919        acc += sum_range(base, off, off + n, payload_off, payload_end);
920        next_sum += 1;
921    }
922    Ok(acc)
923}
924
925#[cfg(target_os = "linux")]
926fn sum_pieces_in_order(
927    base: usize,
928    payload_off: usize,
929    payload_end: usize,
930    threads: usize,
931    pieces: &[(usize, usize)],
932) -> f64 {
933    let mut slots = vec![0.0f64; pieces.len()];
934    let next = std::sync::atomic::AtomicUsize::new(0);
935    std::thread::scope(|scope| {
936        let mut handles = Vec::with_capacity(threads);
937        for _ in 0..threads {
938            handles.push(scope.spawn(|| {
939                let mut local = Vec::new();
940                loop {
941                    let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
942                    if index >= pieces.len() {
943                        break;
944                    }
945                    let (off, n) = pieces[index];
946                    local.push((
947                        index,
948                        sum_range(base, off, off + n, payload_off, payload_end),
949                    ));
950                }
951                local
952            }));
953        }
954        for handle in handles {
955            for (index, part) in handle.join().expect("column sum") {
956                slots[index] = part;
957            }
958        }
959    });
960    slots.iter().copied().sum()
961}
962
963#[cfg(target_os = "linux")]
964fn pages_all_resident(ptr: *mut libc::c_void, len: usize, page: usize) -> Result<bool, ParseError> {
965    if len == 0 {
966        return Ok(true);
967    }
968    let pages = len.div_ceil(page);
969    let mut vec = vec![0u8; pages];
970    let rc = unsafe { libc::mincore(ptr, len, vec.as_mut_ptr()) };
971    if rc != 0 {
972        return Err(ParseError::ValidationError(
973            std::io::Error::last_os_error().to_string(),
974        ));
975    }
976    Ok(vec.iter().all(|byte| byte & 1 == 1))
977}
978
979/// `Ok` means the range is resident. `Err` is the errno from `madvise`.
980/// Only `EINVAL` means this kernel has no `MADV_POPULATE_READ`, so the
981/// caller may fault the pages itself. `EFAULT`, `EIO`, `EHWPOISON` and
982/// `ENOMEM` are failures (man 2 madvise).
983#[cfg(target_os = "linux")]
984fn populate_followup(code: i32) -> Result<(), i32> {
985    if code == libc::EINVAL {
986        Ok(())
987    } else {
988        Err(code)
989    }
990}
991
992#[cfg(target_os = "linux")]
993fn touch_pages(addr: usize, off: usize, len: usize, page: usize) {
994    let pages = len.div_ceil(page);
995    for index in 0..pages {
996        let at = index * page;
997        if at >= len {
998            break;
999        }
1000        let byte = (addr + off + at) as *const u8;
1001        std::hint::black_box(unsafe { std::ptr::read_volatile(byte) });
1002    }
1003}
1004
1005#[cfg(target_os = "linux")]
1006fn wait_resident(addr: usize, off: usize, len: usize, page: usize) -> Result<(), String> {
1007    // One readahead has already been submitted. MADV_POPULATE_READ (Linux
1008    // 5.14) faults this range and waits. The address is checked before the
1009    // call, so EINVAL is the old-kernel miss and one byte of each page is
1010    // read. EAGAIN is a transient kernel resource (man 2 madvise) and is
1011    // retried once per page of the range. Any other errno is returned.
1012    if page == 0 || !(addr + off).is_multiple_of(page) {
1013        return Err("madvise address is not page-aligned".into());
1014    }
1015    let start = (addr + off) as *mut libc::c_void;
1016    let pages = len.div_ceil(page).max(1);
1017    let mut tried = 0usize;
1018    loop {
1019        let rc = unsafe { libc::madvise(start, len, libc::MADV_POPULATE_READ) };
1020        if rc == 0 {
1021            return Ok(());
1022        }
1023        let err = std::io::Error::last_os_error();
1024        let code = err.raw_os_error().unwrap_or(0);
1025        if code == libc::EAGAIN && tried < pages {
1026            tried += 1;
1027            continue;
1028        }
1029        if populate_followup(code).is_ok() {
1030            touch_pages(addr, off, len, page);
1031            return Ok(());
1032        }
1033        return Err(err.to_string());
1034    }
1035}
1036
1037#[cfg(target_os = "linux")]
1038fn advise_readahead(file: &File, off: usize, len: usize) -> Result<(), String> {
1039    let rc = unsafe { libc::readahead(file.as_raw_fd(), off as i64, len) };
1040    if rc != 0 {
1041        Err(std::io::Error::last_os_error().to_string())
1042    } else {
1043        Ok(())
1044    }
1045}
1046
1047#[cfg(target_os = "linux")]
1048struct OwnedMap {
1049    ptr: *mut libc::c_void,
1050    len: usize,
1051}
1052
1053#[cfg(target_os = "linux")]
1054impl Drop for OwnedMap {
1055    fn drop(&mut self) {
1056        unsafe { libc::munmap(self.ptr, self.len) };
1057    }
1058}
1059
1060#[cfg(target_os = "linux")]
1061fn open_map(path: &Path) -> Result<OwnedMap, ParseError> {
1062    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1063    let len = file
1064        .metadata()
1065        .map_err(|err| ParseError::ValidationError(err.to_string()))?
1066        .len() as usize;
1067    let ptr = unsafe {
1068        libc::mmap(
1069            std::ptr::null_mut(),
1070            len,
1071            libc::PROT_READ,
1072            libc::MAP_PRIVATE,
1073            file.as_raw_fd(),
1074            0,
1075        )
1076    };
1077    if ptr == libc::MAP_FAILED {
1078        return Err(ParseError::ValidationError(
1079            std::io::Error::last_os_error().to_string(),
1080        ));
1081    }
1082    unsafe {
1083        libc::madvise(ptr, len, libc::MADV_SEQUENTIAL);
1084        libc::madvise(ptr, len, libc::MADV_HUGEPAGE);
1085    }
1086    Ok(OwnedMap { ptr, len })
1087}
1088
1089#[cfg(target_os = "linux")]
1090fn sum_range(base: usize, start: usize, end: usize, payload_off: usize, payload_end: usize) -> f64 {
1091    let from = start.max(payload_off);
1092    let to = end.min(payload_end);
1093    if to <= from {
1094        return 0.0;
1095    }
1096    let data = unsafe { std::slice::from_raw_parts((base + from) as *const f64, (to - from) / 8) };
1097    let mut acc = 0.0f64;
1098    for &value in data {
1099        acc += value;
1100    }
1101    acc
1102}
1103
1104/// Map `path` and fault the pages in before returning.
1105///
1106/// The map is `MAP_PRIVATE` and writable. A store to a page copies that
1107/// page. It does not modify the file. `mmap(2)` leaves it unspecified
1108/// whether a later write to the file by someone else appears in a page
1109/// the caller has not stored to. Truncation can raise `SIGBUS`.
1110///
1111/// `MADV_SEQUENTIAL` and `MADV_WILLNEED` describe one forward pass.
1112/// `MADV_HUGEPAGE` is the request used when transparent huge pages are in
1113/// `madvise` mode (`CONFIG_TRANSPARENT_HUGEPAGE_MADVISE`). File-backed
1114/// huge pages also need `CONFIG_READ_ONLY_THP_FOR_FS`
1115/// (Documentation/admin-guide/mm/transhuge.rst). This kernel's
1116/// `/proc/config.gz` has that option unset, and a mapped read showed
1117/// `FilePmdMapped` 0. The advice stays, because it is the switch the
1118/// kernel documents, and it is a no-op without that option.
1119/// `MADV_POPULATE_READ` (Linux 5.14) is the span hint. A failure, including
1120/// `EINVAL` from a kernel before 5.14, leaves the mapping in place and one
1121/// byte of each page is read, so the caller still sees the file.
1122/// `MAP_POPULATE` hides errors and cannot be split across the caller's
1123/// threads after `mmap` returns. When `mmap` itself fails, the file is
1124/// read into a private mapping and the accessors return those bytes.
1125/// `threads` workers fault page-aligned spans. A file shorter than one
1126/// page per worker stays on one worker. The page is `sysconf(SC_PAGESIZE)`.
1127pub fn map_file(path: &Path, threads: usize) -> Result<ConBinMap, ParseError> {
1128    map_file_with(path, threads, Prefetch::Span)
1129}
1130
1131/// [`map_file`] with an explicit prefetch. The benchmark pairs these.
1132pub fn map_file_with(
1133    path: &Path,
1134    threads: usize,
1135    prefetch: Prefetch,
1136) -> Result<ConBinMap, ParseError> {
1137    // A crash-safe write publishes by rename. An open taken before that
1138    // rename still names the previous inode, so the map of that open is
1139    // not the file now at `path`. If the path changes while this call
1140    // holds the first mapping, map the published file instead.
1141    let mapped = map_current(path, threads, prefetch)?;
1142    #[cfg(unix)]
1143    if path_identity(path) != Some(mapped.0) {
1144        return Ok(map_current(path, threads, prefetch)?.1);
1145    }
1146    Ok(mapped.1)
1147}
1148
1149/// `(device, inode)` of `path`, when the path exists.
1150#[cfg(unix)]
1151fn path_identity(path: &Path) -> Option<(u64, u64)> {
1152    let meta = std::fs::metadata(path).ok()?;
1153    Some(file_identity_meta(&meta))
1154}
1155
1156#[cfg(unix)]
1157fn file_identity(file: &File) -> Result<(u64, u64), ParseError> {
1158    let meta = file
1159        .metadata()
1160        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1161    Ok(file_identity_meta(&meta))
1162}
1163
1164#[cfg(unix)]
1165fn file_identity_meta(meta: &std::fs::Metadata) -> (u64, u64) {
1166    use std::os::unix::fs::MetadataExt;
1167    (meta.dev(), meta.ino())
1168}
1169
1170fn map_current(
1171    path: &Path,
1172    threads: usize,
1173    prefetch: Prefetch,
1174) -> Result<((u64, u64), ConBinMap), ParseError> {
1175    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1176    #[cfg(unix)]
1177    let identity = file_identity(&file)?;
1178    #[cfg(not(unix))]
1179    let identity = (0, 0);
1180    // MAP_PRIVATE, PROT_READ|PROT_WRITE. Writes copy the page.
1181    // When `mmap` itself fails, the file is read into a private mapping
1182    // that holds the same bytes, so the accessors return the same values.
1183    let map = map_copy_or_read(&file)?;
1184    if map.len() < FIELD_BYTES {
1185        return Err(ParseError::ValidationError(
1186            "CON-bin header is not CONBIN01".into(),
1187        ));
1188    }
1189    let (header, offset) = parse_fields(&map[..FIELD_BYTES])?;
1190    let page = page_size()?;
1191    let payload_off = checked_payload_offset(offset, map.len())?;
1192    fault_in(path, &map, threads, page, prefetch)?;
1193    Ok((
1194        identity,
1195        ConBinMap {
1196            map,
1197            header,
1198            payload_off,
1199        },
1200    ))
1201}
1202
1203#[cfg(test)]
1204thread_local! {
1205    static POPULATE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1206    static MAP_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1207}
1208
1209/// File-backed private map, or an anonymous map filled by `read` when `mmap` fails.
1210fn map_copy_or_read(file: &File) -> Result<memmap2::MmapMut, ParseError> {
1211    #[cfg(test)]
1212    if MAP_FAILS.with(|flag| flag.get()) {
1213        return private_copy(file);
1214    }
1215    match unsafe { memmap2::MmapOptions::new().map_copy(file) } {
1216        Ok(map) => Ok(map),
1217        Err(_) => private_copy(file),
1218    }
1219}
1220
1221fn private_copy(file: &File) -> Result<memmap2::MmapMut, ParseError> {
1222    let len = usize::try_from(
1223        file.metadata()
1224            .map_err(|err| ParseError::ValidationError(err.to_string()))?
1225            .len(),
1226    )
1227    .map_err(|_| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
1228    if len < FIELD_BYTES {
1229        return Err(ParseError::ValidationError(
1230            "CON-bin header is not CONBIN01".into(),
1231        ));
1232    }
1233    let mut anon = memmap2::MmapOptions::new()
1234        .len(len)
1235        .map_anon()
1236        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1237    let mut reader = file
1238        .try_clone()
1239        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1240    reader
1241        .read_exact(&mut anon[..])
1242        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1243    Ok(anon)
1244}
1245
1246fn touch_mapped_pages(map: &memmap2::MmapMut, page: usize) {
1247    let page = page.max(1);
1248    for chunk in map.chunks(page) {
1249        std::hint::black_box(chunk.first().copied());
1250    }
1251}
1252
1253fn fault_in(
1254    path: &Path,
1255    map: &memmap2::MmapMut,
1256    threads: usize,
1257    page: usize,
1258    prefetch: Prefetch,
1259) -> Result<(), ParseError> {
1260    #[cfg(unix)]
1261    let _ = map.advise(memmap2::Advice::Sequential);
1262    #[cfg(target_os = "linux")]
1263    let _ = map.advise(memmap2::Advice::HugePage);
1264    #[cfg(target_os = "linux")]
1265    {
1266        match prefetch {
1267            Prefetch::Span => {
1268                let _ = map.advise(memmap2::Advice::WillNeed);
1269                // `MADV_POPULATE_READ` is a hint. Kernels before 5.14 return
1270                // `EINVAL`, and some filesystems return other errors. A failed
1271                // hint leaves the mapping in place; the pages are touched so
1272                // the caller still reads the same values.
1273                let hint_failed = {
1274                    #[cfg(test)]
1275                    {
1276                        POPULATE_FAILS.with(|flag| flag.get())
1277                    }
1278                    #[cfg(not(test))]
1279                    {
1280                        false
1281                    }
1282                };
1283                if hint_failed
1284                    || advise_spans(map, memmap2::Advice::PopulateRead, threads, page).is_err()
1285                {
1286                    touch_mapped_pages(map, page);
1287                }
1288            }
1289            Prefetch::ChunkPopulate => {
1290                let window = QueueLimits::of(path)?.worker_span(threads);
1291                chunk_each(map, threads, page, window, ChunkOp::Populate)?;
1292            }
1293            Prefetch::ChunkWillneed => {
1294                let window = QueueLimits::of(path)?.worker_span(threads);
1295                chunk_each(map, threads, page, window, ChunkOp::Willneed { path })?;
1296            }
1297            Prefetch::Hybrid => {
1298                let window = QueueLimits::of(path)?.worker_span(threads);
1299                chunk_each(map, threads, page, window, ChunkOp::Hybrid { path })?;
1300            }
1301        }
1302    }
1303    #[cfg(not(target_os = "linux"))]
1304    {
1305        let _ = (path, threads, prefetch);
1306        for chunk in map.chunks(page) {
1307            std::hint::black_box(chunk.first().copied());
1308        }
1309    }
1310    Ok(())
1311}
1312
1313#[cfg(target_os = "linux")]
1314enum ChunkOp<'a> {
1315    Populate,
1316    Willneed { path: &'a Path },
1317    Hybrid { path: &'a Path },
1318}
1319
1320#[cfg(target_os = "linux")]
1321fn chunk_each(
1322    map: &memmap2::MmapMut,
1323    threads: usize,
1324    page: usize,
1325    window: usize,
1326    op: ChunkOp<'_>,
1327) -> Result<(), ParseError> {
1328    let ranges = worker_ranges(map.len(), threads, page);
1329    let shared = match op {
1330        ChunkOp::Populate => ChunkOp::Populate,
1331        ChunkOp::Willneed { path } => ChunkOp::Willneed { path },
1332        ChunkOp::Hybrid { path } => ChunkOp::Hybrid { path },
1333    };
1334    std::thread::scope(|scope| {
1335        let mut handles = Vec::with_capacity(ranges.len());
1336        for (start, end) in ranges {
1337            let op = match shared {
1338                ChunkOp::Populate => ChunkOp::Populate,
1339                ChunkOp::Willneed { path } => ChunkOp::Willneed { path },
1340                ChunkOp::Hybrid { path } => ChunkOp::Hybrid { path },
1341            };
1342            handles.push(scope.spawn(move || chunk_worker(map, start, end, window, page, op)));
1343        }
1344        handles.into_iter().try_for_each(|handle| {
1345            handle.join().unwrap_or_else(|_| {
1346                Err(ParseError::ValidationError(
1347                    "CON-bin prefetch thread panicked".into(),
1348                ))
1349            })
1350        })
1351    })
1352}
1353
1354#[cfg(target_os = "linux")]
1355fn chunk_worker(
1356    map: &memmap2::MmapMut,
1357    start: usize,
1358    end: usize,
1359    window: usize,
1360    page: usize,
1361    op: ChunkOp<'_>,
1362) -> Result<(), ParseError> {
1363    let window = window.max(page);
1364    let pieces = piece_list(start, end, window);
1365    let fd = match op {
1366        ChunkOp::Willneed { path } | ChunkOp::Hybrid { path } => {
1367            Some(File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?)
1368        }
1369        ChunkOp::Populate => None,
1370    };
1371    match op {
1372        ChunkOp::Populate => {
1373            for (off, len) in pieces {
1374                populate_range(map, off, len)?;
1375            }
1376        }
1377        ChunkOp::Willneed { .. } => {
1378            let fd = fd.as_ref().expect("willneed opens a descriptor");
1379            for (off, len) in pieces {
1380                willneed(fd, off, len)?;
1381            }
1382        }
1383        ChunkOp::Hybrid { .. } => {
1384            let fd = fd.as_ref().expect("hybrid opens a descriptor");
1385            if let Some((off, len)) = pieces.first().copied() {
1386                willneed(fd, off, len)?;
1387            }
1388            for i in 0..pieces.len() {
1389                if let Some((off, len)) = pieces.get(i + 1).copied() {
1390                    willneed(fd, off, len)?;
1391                }
1392                let (off, len) = pieces[i];
1393                populate_range(map, off, len)?;
1394            }
1395        }
1396    }
1397    Ok(())
1398}
1399
1400#[cfg(target_os = "linux")]
1401fn piece_list(start: usize, end: usize, window: usize) -> Vec<(usize, usize)> {
1402    let mut pieces = Vec::new();
1403    let mut off = start;
1404    while off < end {
1405        let len = window.min(end - off);
1406        pieces.push((off, len));
1407        off += len;
1408    }
1409    pieces
1410}
1411
1412#[cfg(target_os = "linux")]
1413fn populate_range(map: &memmap2::MmapMut, off: usize, len: usize) -> Result<(), ParseError> {
1414    let page = page_size()?;
1415    wait_resident(map.as_ptr() as usize, off, len, page).map_err(ParseError::ValidationError)
1416}
1417
1418#[cfg(target_os = "linux")]
1419fn willneed(file: &File, off: usize, len: usize) -> Result<(), ParseError> {
1420    let rc = unsafe {
1421        libc::posix_fadvise(
1422            file.as_raw_fd(),
1423            off as libc::off_t,
1424            len as libc::off_t,
1425            libc::POSIX_FADV_WILLNEED,
1426        )
1427    };
1428    if rc != 0 {
1429        return Err(ParseError::ValidationError(format!(
1430            "posix_fadvise WILLNEED: {rc}"
1431        )));
1432    }
1433    Ok(())
1434}
1435
1436#[cfg(target_os = "linux")]
1437fn worker_ranges(len: usize, threads: usize, page: usize) -> Vec<(usize, usize)> {
1438    if len == 0 {
1439        return Vec::new();
1440    }
1441    let threads = threads.max(1);
1442    let workers = if len < page.saturating_mul(threads) {
1443        1
1444    } else {
1445        threads
1446    };
1447    if workers == 1 {
1448        return vec![(0, len)];
1449    }
1450    let chunk = (len / workers) & !(page - 1);
1451    let mut ranges = Vec::with_capacity(workers);
1452    let mut start = 0usize;
1453    for worker in 0..workers {
1454        let take = if worker + 1 == workers {
1455            len - start
1456        } else {
1457            chunk
1458        };
1459        ranges.push((start, start + take));
1460        start += take;
1461    }
1462    ranges
1463}
1464
1465#[cfg(target_os = "linux")]
1466fn advise_spans(
1467    map: &memmap2::MmapMut,
1468    advice: memmap2::Advice,
1469    threads: usize,
1470    page: usize,
1471) -> Result<(), ParseError> {
1472    let len = map.len();
1473    if len == 0 {
1474        return Ok(());
1475    }
1476    let threads = threads.max(1);
1477    let workers = if len < page.saturating_mul(threads) {
1478        1
1479    } else {
1480        threads
1481    };
1482    if workers == 1 {
1483        return map
1484            .advise(advice)
1485            .map_err(|err| ParseError::ValidationError(err.to_string()));
1486    }
1487    let chunk = (len / workers) & !(page - 1);
1488    std::thread::scope(|scope| {
1489        let mut start = 0usize;
1490        let mut handles = Vec::with_capacity(workers);
1491        for worker in 0..workers {
1492            let take = if worker + 1 == workers {
1493                len - start
1494            } else {
1495                chunk
1496            };
1497            let off = start;
1498            start += take;
1499            handles.push(scope.spawn(move || map.advise_range(advice, off, take)));
1500        }
1501        handles.into_iter().try_for_each(|handle| {
1502            handle
1503                .join()
1504                .unwrap_or_else(|_| Err(std::io::Error::other("CON-bin populate thread panicked")))
1505                .map_err(|err| ParseError::ValidationError(err.to_string()))
1506        })
1507    })
1508}
1509
1510pub fn read_header(path: &Path) -> Result<ConBinHeader, ParseError> {
1511    let mut file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1512    let mut bytes = [0u8; FIELD_BYTES];
1513    file.read_exact(&mut bytes)
1514        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1515    parse_fields(&bytes).map(|(header, _)| header)
1516}
1517
1518fn bytes_of<T>(values: &mut [T]) -> &mut [u8] {
1519    let len = std::mem::size_of_val(values);
1520    // SAFETY: `values` is a live slice. The byte view covers exactly those
1521    // elements and is not used after `values` is borrowed again.
1522    unsafe { std::slice::from_raw_parts_mut(values.as_mut_ptr().cast::<u8>(), len) }
1523}
1524
1525/// Copy a binary64 CON-bin into caller-owned columns. One thread issues the reads.
1526pub fn read_into(
1527    path: &Path,
1528    positions: &mut [f64],
1529    velocities: Option<&mut [f64]>,
1530) -> Result<ConBinHeader, ParseError> {
1531    read_into_threads(path, positions, velocities, 1)
1532}
1533
1534/// [`read_into`] with `threads` workers. Each worker reads a page-aligned span.
1535/// A span shorter than one page stays on one worker.
1536pub fn read_into_threads(
1537    path: &Path,
1538    positions: &mut [f64],
1539    velocities: Option<&mut [f64]>,
1540    threads: usize,
1541) -> Result<ConBinHeader, ParseError> {
1542    read_columns_into(path, positions, velocities, threads, false)
1543}
1544
1545/// Copy both binary64 columns into owned vectors.
1546///
1547/// Each vector is `with_capacity`, then `pread` fills `spare_capacity_mut`
1548/// and `set_len` publishes those slots. The byte view is not a `&mut [f64]`
1549/// over uninitialised memory. A missing velocity run is an error.
1550///
1551/// The header's frame and atom counts are not reserved until both columns
1552/// fit in the file. A count the file cannot hold is [`ParseError::IncompleteFrame`].
1553pub fn read_owned_f64(
1554    path: &Path,
1555    threads: usize,
1556) -> Result<(ConBinHeader, Vec<f64>, Vec<f64>), ParseError> {
1557    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1558    let mut raw = [0u8; FIELD_BYTES];
1559    (&file)
1560        .read_exact(&mut raw)
1561        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1562    let (header, offset) = parse_fields(&raw)?;
1563    if header.binary32 {
1564        return Err(ParseError::ValidationError(
1565            "CON-bin file is binary32; use read_into_f32".into(),
1566        ));
1567    }
1568    if !header.velocities {
1569        return Err(ParseError::ValidationError(
1570            "CON-bin file has no velocity run".into(),
1571        ));
1572    }
1573    let n = header.position_len()?;
1574    let column = n
1575        .checked_mul(std::mem::size_of::<f64>())
1576        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
1577    let file_len = file
1578        .metadata()
1579        .map_err(|err| ParseError::ValidationError(err.to_string()))?
1580        .len() as usize;
1581    let pos_off = checked_payload_offset(offset, file_len)?;
1582    let both = column
1583        .checked_mul(2)
1584        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
1585    let end = pos_off
1586        .checked_add(both)
1587        .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
1588    if end > file_len {
1589        return Err(ParseError::IncompleteFrame);
1590    }
1591    drop(file);
1592    let mut positions = Vec::<f64>::with_capacity(n);
1593    let mut velocities = Vec::<f64>::with_capacity(n);
1594    fill_owned_f64(path, &mut positions, &mut velocities, n, threads)?;
1595    Ok((header, positions, velocities))
1596}
1597
1598#[cfg(unix)]
1599fn spare_prefix_uninit(buf: &mut Vec<f64>, n: usize) -> &mut [std::mem::MaybeUninit<u8>] {
1600    let spare = buf.spare_capacity_mut();
1601    assert!(spare.len() >= n);
1602    let nbytes = n * std::mem::size_of::<f64>();
1603    let ptr = spare.as_mut_ptr().cast::<std::mem::MaybeUninit<u8>>();
1604    // SAFETY: `n` uninitialised f64 slots cover `nbytes` bytes. A
1605    // `MaybeUninit<u8>` slot may be uninitialised, so this slice does not
1606    // claim the bytes are initialised. `pread` writes through the raw
1607    // pointer, then `set_len` publishes the f64 slots.
1608    unsafe { std::slice::from_raw_parts_mut(ptr, nbytes) }
1609}
1610
1611fn fill_owned_f64(
1612    path: &Path,
1613    positions: &mut Vec<f64>,
1614    velocities: &mut Vec<f64>,
1615    n: usize,
1616    threads: usize,
1617) -> Result<(), ParseError> {
1618    #[cfg(not(unix))]
1619    {
1620        let _ = (path, positions, velocities, n, threads);
1621        return Err(ParseError::ValidationError(
1622            "CON-bin pread fill requires Unix".into(),
1623        ));
1624    }
1625    #[cfg(unix)]
1626    {
1627        let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1628        let mut raw = [0u8; FIELD_BYTES];
1629        (&file)
1630            .read_exact(&mut raw)
1631            .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1632        let (_header, offset) = parse_fields(&raw)?;
1633        let width = std::mem::size_of::<f64>();
1634        let expect = n.checked_mul(width).ok_or_else(|| {
1635            ParseError::InvalidCount("CON-bin column byte length overflows".into())
1636        })?;
1637        let page = page_size()?;
1638        let file_len = file
1639            .metadata()
1640            .map_err(|err| ParseError::ValidationError(err.to_string()))?
1641            .len() as usize;
1642        let pos_off = checked_payload_offset(offset, file_len)? as u64;
1643        let fd = file.as_raw_fd();
1644        {
1645            let bytes = spare_prefix_uninit(positions, n);
1646            pread_parallel_uninit(fd, bytes, pos_off, threads, page)?;
1647        }
1648        // SAFETY: `pread_parallel_uninit` wrote `n` little-endian f64 values or returned.
1649        unsafe { positions.set_len(n) };
1650        decode_le(positions);
1651        {
1652            let bytes = spare_prefix_uninit(velocities, n);
1653            pread_parallel_uninit(fd, bytes, pos_off + expect as u64, threads, page)?;
1654        }
1655        unsafe { velocities.set_len(n) };
1656        decode_le(velocities);
1657        Ok(())
1658    }
1659}
1660
1661/// Copy a binary32 CON-bin into caller-owned columns. One thread issues the reads.
1662pub fn read_into_f32(
1663    path: &Path,
1664    positions: &mut [f32],
1665    velocities: Option<&mut [f32]>,
1666) -> Result<ConBinHeader, ParseError> {
1667    read_into_f32_threads(path, positions, velocities, 1)
1668}
1669
1670/// [`read_into_f32`] with `threads` workers. The split is the same page rule
1671/// as [`read_into_threads`].
1672pub fn read_into_f32_threads(
1673    path: &Path,
1674    positions: &mut [f32],
1675    velocities: Option<&mut [f32]>,
1676    threads: usize,
1677) -> Result<ConBinHeader, ParseError> {
1678    read_columns_into(path, positions, velocities, threads, true)
1679}
1680
1681fn read_columns_into<T: StoreLe>(
1682    path: &Path,
1683    positions: &mut [T],
1684    velocities: Option<&mut [T]>,
1685    threads: usize,
1686    binary32: bool,
1687) -> Result<ConBinHeader, ParseError> {
1688    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
1689    let mut raw = [0u8; FIELD_BYTES];
1690    (&file)
1691        .read_exact(&mut raw)
1692        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
1693    let (header, offset) = parse_fields(&raw)?;
1694    if header.binary32 != binary32 {
1695        return Err(ParseError::ValidationError(if binary32 {
1696            "CON-bin file is binary64; use read_into".into()
1697        } else {
1698            "CON-bin file is binary32; use read_into_f32".into()
1699        }));
1700    }
1701    let n = header.position_len()?;
1702    let width = std::mem::size_of::<T>();
1703    let expect = n
1704        .checked_mul(width)
1705        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
1706    if positions.len() != n {
1707        return Err(ParseError::InvalidCount(format!(
1708            "position slice has {} values, the file has {n}",
1709            positions.len()
1710        )));
1711    }
1712    let page = page_size()?;
1713    let file_len = file
1714        .metadata()
1715        .map_err(|err| ParseError::ValidationError(err.to_string()))?
1716        .len() as usize;
1717    let pos_off = checked_payload_offset(offset, file_len)? as u64;
1718    let pos_bytes = bytes_of(positions);
1719    if pos_bytes.len() != expect {
1720        return Err(ParseError::InvalidCount(format!(
1721            "position slice has {} bytes, the file has {expect}",
1722            pos_bytes.len()
1723        )));
1724    }
1725    #[cfg(not(unix))]
1726    {
1727        let _ = (pos_bytes, pos_off, threads, page, velocities, header);
1728        return Err(ParseError::ValidationError(
1729            "CON-bin pread fill requires Unix".into(),
1730        ));
1731    }
1732    #[cfg(unix)]
1733    {
1734        let fd = file.as_raw_fd();
1735        // Sequential advice matches one pass over the payload. WILLNEED is not
1736        // used here: it starts a second readahead beside the reads themselves.
1737        // libc exposes posix_fadvise on Linux. macOS has posix_madvise instead.
1738        #[cfg(target_os = "linux")]
1739        unsafe {
1740            libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_SEQUENTIAL);
1741        }
1742        // Linux read returns at most MAX_RW_COUNT bytes (INT_MAX aligned down to
1743        // the page, include/linux/fs.h). `pread_all` continues until the span is full.
1744        pread_parallel(fd, pos_bytes, pos_off, threads, page)?;
1745        decode_le(positions);
1746        if header.velocities {
1747            let Some(vel) = velocities else {
1748                return Err(ParseError::InvalidCount(
1749                    "CON-bin has velocities and the caller passed no velocity slice".into(),
1750                ));
1751            };
1752            if vel.len() != n {
1753                return Err(ParseError::InvalidCount(format!(
1754                    "velocity slice has {} values, the file has {n}",
1755                    vel.len()
1756                )));
1757            }
1758            let vel_bytes = bytes_of(vel);
1759            pread_parallel(fd, vel_bytes, pos_off + expect as u64, threads, page)?;
1760            decode_le(vel);
1761        }
1762        Ok(header)
1763    }
1764}
1765
1766#[cfg(unix)]
1767fn pread_parallel(
1768    fd: i32,
1769    dest: &mut [u8],
1770    offset: u64,
1771    threads: usize,
1772    page: usize,
1773) -> Result<(), ParseError> {
1774    let threads = threads.max(1);
1775    let workers = if dest.len() < page.saturating_mul(threads) {
1776        1
1777    } else {
1778        threads
1779    };
1780    if workers == 1 {
1781        return pread_all(fd, dest, offset);
1782    }
1783    let chunk = (dest.len() / workers) & !(page - 1);
1784    std::thread::scope(|scope| {
1785        let mut rest = dest;
1786        let mut off = offset;
1787        let mut handles = Vec::with_capacity(workers);
1788        for worker in 0..workers {
1789            let take = if worker + 1 == workers {
1790                rest.len()
1791            } else {
1792                chunk
1793            };
1794            let (head, tail) = rest.split_at_mut(take);
1795            rest = tail;
1796            let this = off;
1797            off += take as u64;
1798            handles.push(scope.spawn(move || pread_all(fd, head, this)));
1799        }
1800        handles
1801            .into_iter()
1802            .try_for_each(|handle| handle.join().unwrap_or(Err(ParseError::IncompleteFrame)))
1803    })
1804}
1805
1806#[cfg(unix)]
1807fn pread_raw(fd: i32, ptr: *mut u8, len: usize, mut offset: u64) -> Result<(), ParseError> {
1808    let mut done = 0;
1809    while done < len {
1810        let n = unsafe { libc::pread(fd, ptr.add(done).cast(), len - done, offset as libc::off_t) };
1811        if n < 0 {
1812            let err = std::io::Error::last_os_error();
1813            // POSIX: EINTR means the call was interrupted before a transfer.
1814            // Restart the same offset. Rust's `read_at` does the same for
1815            // `ErrorKind::Interrupted`.
1816            if err.raw_os_error() == Some(libc::EINTR) {
1817                continue;
1818            }
1819            return Err(ParseError::ValidationError(err.to_string()));
1820        }
1821        if n == 0 {
1822            return Err(ParseError::IncompleteFrame);
1823        }
1824        done += n as usize;
1825        offset += n as u64;
1826    }
1827    Ok(())
1828}
1829
1830#[cfg(unix)]
1831fn pread_all(fd: i32, dest: &mut [u8], offset: u64) -> Result<(), ParseError> {
1832    pread_raw(fd, dest.as_mut_ptr(), dest.len(), offset)
1833}
1834
1835#[cfg(unix)]
1836fn pread_uninit(
1837    fd: i32,
1838    dest: &mut [std::mem::MaybeUninit<u8>],
1839    offset: u64,
1840) -> Result<(), ParseError> {
1841    // `as_mut_ptr` of `MaybeUninit<u8>` is the address `pread` may write.
1842    // The slice type does not require the bytes to be initialised.
1843    pread_raw(fd, dest.as_mut_ptr().cast::<u8>(), dest.len(), offset)
1844}
1845
1846#[cfg(unix)]
1847fn pread_parallel_uninit(
1848    fd: i32,
1849    dest: &mut [std::mem::MaybeUninit<u8>],
1850    offset: u64,
1851    threads: usize,
1852    page: usize,
1853) -> Result<(), ParseError> {
1854    let threads = threads.max(1);
1855    let workers = if dest.len() < page.saturating_mul(threads) {
1856        1
1857    } else {
1858        threads
1859    };
1860    if workers == 1 {
1861        return pread_uninit(fd, dest, offset);
1862    }
1863    let chunk = (dest.len() / workers) & !(page - 1);
1864    std::thread::scope(|scope| {
1865        let mut rest = dest;
1866        let mut off = offset;
1867        let mut handles = Vec::with_capacity(workers);
1868        for worker in 0..workers {
1869            let take = if worker + 1 == workers {
1870                rest.len()
1871            } else {
1872                chunk
1873            };
1874            let (head, tail) = rest.split_at_mut(take);
1875            rest = tail;
1876            let this = off;
1877            off += take as u64;
1878            handles.push(scope.spawn(move || pread_uninit(fd, head, this)));
1879        }
1880        handles
1881            .into_iter()
1882            .try_for_each(|handle| handle.join().unwrap_or(Err(ParseError::IncompleteFrame)))
1883    })
1884}
1885
1886mod sealed_number {
1887    pub trait Sealed {}
1888    impl Sealed for f64 {}
1889    impl Sealed for f32 {}
1890    impl Sealed for u64 {}
1891    impl Sealed for u8 {}
1892}
1893
1894trait StoreLe: Copy + sealed_number::Sealed {
1895    fn store_le(self, out: &mut Vec<u8>);
1896    fn load_le(self) -> Self;
1897}
1898
1899impl StoreLe for f64 {
1900    fn store_le(self, out: &mut Vec<u8>) {
1901        out.extend_from_slice(&self.to_le_bytes());
1902    }
1903    fn load_le(self) -> Self {
1904        f64::from_le_bytes(self.to_ne_bytes())
1905    }
1906}
1907
1908impl StoreLe for f32 {
1909    fn store_le(self, out: &mut Vec<u8>) {
1910        out.extend_from_slice(&self.to_le_bytes());
1911    }
1912    fn load_le(self) -> Self {
1913        f32::from_le_bytes(self.to_ne_bytes())
1914    }
1915}
1916
1917impl StoreLe for u64 {
1918    fn store_le(self, out: &mut Vec<u8>) {
1919        out.extend_from_slice(&self.to_le_bytes());
1920    }
1921    fn load_le(self) -> Self {
1922        u64::from_le_bytes(self.to_ne_bytes())
1923    }
1924}
1925
1926impl StoreLe for u8 {
1927    fn store_le(self, out: &mut Vec<u8>) {
1928        out.push(self);
1929    }
1930    fn load_le(self) -> Self {
1931        self
1932    }
1933}
1934
1935#[cfg(test)]
1936fn write_values<T: StoreLe>(file: &mut File, values: &[T]) -> Result<(), ParseError> {
1937    // A little-endian host already stores the file order. The byte view is
1938    // the values themselves, so the write does not build a second buffer.
1939    if cfg!(target_endian = "little") {
1940        let bytes = unsafe {
1941            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
1942        };
1943        return file
1944            .write_all(bytes)
1945            .map_err(|err| ParseError::ValidationError(err.to_string()));
1946    }
1947    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
1948    for value in values {
1949        value.store_le(&mut bytes);
1950    }
1951    file.write_all(&bytes)
1952        .map_err(|err| ParseError::ValidationError(err.to_string()))
1953}
1954
1955/// `pread` left little-endian file bytes in `values`. A little-endian host
1956/// already reads them as the numbers. A big-endian host swaps each one.
1957fn decode_le<T: StoreLe>(values: &mut [T]) {
1958    if cfg!(target_endian = "little") {
1959        return;
1960    }
1961    for value in values {
1962        *value = value.load_le();
1963    }
1964}
1965
1966thread_local! {
1967    /// One header page per thread. The padding stays zero, and each write
1968    /// fills the 40-byte prefix in place instead of allocating another page.
1969    static HEADER_PAGE: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
1970}
1971
1972fn header_page_bytes(header: &ConBinHeader, page: usize) -> Vec<u8> {
1973    let mut header_page = vec![0u8; page];
1974    let prefix = header_fields(header, page as u64);
1975    header_page[..FIELD_BYTES].copy_from_slice(&prefix);
1976    header_page
1977}
1978
1979/// Little-endian hosts already store values in file order. The slice is
1980/// that memory. It is not a second buffer.
1981#[cfg(target_endian = "little")]
1982fn view_bytes<T: StoreLe>(values: &[T]) -> &[u8] {
1983    // SAFETY: `T: StoreLe` is sealed to f64, f32, u64 and u8. Each is a
1984    // plain number with no padding. This function is compiled only on a
1985    // little-endian host, so those bytes are already the file order. The
1986    // slice borrows `values` and does not outlive it.
1987    unsafe {
1988        std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
1989    }
1990}
1991
1992#[cfg(target_endian = "big")]
1993fn le_bytes<T: StoreLe>(values: &[T]) -> Vec<u8> {
1994    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
1995    for value in values {
1996        value.store_le(&mut bytes);
1997    }
1998    bytes
1999}
2000
2001/// Preallocate `page + parts` and store the reused header plus every part
2002/// with one vectored write. A short write is resumed. Nothing is synced:
2003/// the caller still publishes by rename.
2004fn write_assembled(
2005    file: &mut File,
2006    header: &ConBinHeader,
2007    page: usize,
2008    parts: &[&[u8]],
2009) -> Result<(), ParseError> {
2010    let payload = parts
2011        .iter()
2012        .try_fold(0u64, |sum, part| sum.checked_add(part.len() as u64))
2013        .ok_or_else(|| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
2014    let total = (page as u64)
2015        .checked_add(payload)
2016        .ok_or_else(|| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
2017    preallocate(file, total)?;
2018    HEADER_PAGE.with(|slot| {
2019        let mut buf = slot.borrow_mut();
2020        if buf.len() != page {
2021            buf.clear();
2022            buf.resize(page, 0);
2023        }
2024        let prefix = header_fields(header, page as u64);
2025        buf[..FIELD_BYTES].copy_from_slice(&prefix);
2026        let mut iovecs = Vec::with_capacity(1 + parts.len());
2027        iovecs.push(IoSlice::new(buf.as_slice()));
2028        for part in parts {
2029            if !part.is_empty() {
2030                iovecs.push(IoSlice::new(part));
2031            }
2032        }
2033        let mut rest = iovecs.as_mut_slice();
2034        while !rest.is_empty() {
2035            match file.write_vectored(rest) {
2036                Ok(0) => {
2037                    return Err(ParseError::ValidationError(
2038                        "CON-bin write stored no bytes".into(),
2039                    ));
2040                }
2041                Ok(n) => IoSlice::advance_slices(&mut rest, n),
2042                Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
2043                Err(err) => return Err(ParseError::ValidationError(err.to_string())),
2044            }
2045        }
2046        Ok(())
2047    })
2048}
2049
2050fn publish_assembled(
2051    path: &Path,
2052    header: &ConBinHeader,
2053    page: usize,
2054    parts: &[&[u8]],
2055) -> Result<(), ParseError> {
2056    crate::writer::publish_new(
2057        path,
2058        |err| ParseError::ValidationError(err.to_string()),
2059        |file| write_assembled(file, header, page, parts),
2060    )
2061}
2062
2063#[cfg(test)]
2064fn write_header_page(
2065    file: &mut File,
2066    header: &ConBinHeader,
2067    page: usize,
2068) -> Result<(), ParseError> {
2069    file.write_all(&header_page_bytes(header, page))
2070        .map_err(|err| ParseError::ValidationError(err.to_string()))
2071}
2072
2073/// Store `values` in file order.
2074#[cfg(feature = "python")]
2075fn write_le<T: StoreLe>(file: &mut File, values: &[T]) -> Result<(), ParseError> {
2076    #[cfg(target_endian = "little")]
2077    let bytes = view_bytes(values);
2078    #[cfg(target_endian = "big")]
2079    let bytes = le_bytes(values);
2080    file.write_all(bytes.as_ref())
2081        .map_err(|err| ParseError::ValidationError(err.to_string()))
2082}
2083
2084#[cfg(all(feature = "python", not(all(unix, target_endian = "little"))))]
2085pub(crate) fn write_f64_le(file: &mut File, values: &[f64]) -> Result<(), ParseError> {
2086    write_le(file, values)
2087}
2088
2089/// Store the `len` doubles at `ptr` at the file position.
2090///
2091/// Only the kernel reads them; no Rust reference to them is formed, so
2092/// another thread may store into them meanwhile, as with
2093/// `ndarray.tofile`.
2094///
2095/// # Safety
2096///
2097/// `ptr` must stay valid for `len` doubles until this returns.
2098#[cfg(all(feature = "python", unix, target_endian = "little"))]
2099pub(crate) unsafe fn write_f64_raw(
2100    file: &File,
2101    ptr: *const f64,
2102    len: usize,
2103) -> Result<(), ParseError> {
2104    use std::os::fd::AsRawFd;
2105    let mut at = ptr.cast::<u8>();
2106    let mut left = len * std::mem::size_of::<f64>();
2107    while left > 0 {
2108        let stored = unsafe { libc::write(file.as_raw_fd(), at.cast(), left.min(1 << 30)) };
2109        if stored < 0 {
2110            let err = std::io::Error::last_os_error();
2111            if err.kind() == std::io::ErrorKind::Interrupted {
2112                continue;
2113            }
2114            return Err(ParseError::ValidationError(err.to_string()));
2115        }
2116        if stored == 0 {
2117            return Err(ParseError::ValidationError(
2118                std::io::Error::from(std::io::ErrorKind::WriteZero).to_string(),
2119            ));
2120        }
2121        at = unsafe { at.add(stored as usize) };
2122        left -= stored as usize;
2123    }
2124    Ok(())
2125}
2126
2127/// [`write_f64_columns`] with the binary64 columns handed over in runs.
2128///
2129/// The counts name the binary64 columns in payload order: positions,
2130/// then velocities, masses and cell when present. `emit(column, values,
2131/// file)` stores that range of that column at the file position, at most
2132/// `run` values at a time, so the caller decides how memory it does not
2133/// own reaches the file. The file matches [`write_f64_columns`] of the
2134/// same values.
2135#[cfg(feature = "python")]
2136#[allow(clippy::too_many_arguments)]
2137pub(crate) fn write_f64_columns_staged(
2138    path: &Path,
2139    n_frames: u64,
2140    n_atoms: u64,
2141    positions: usize,
2142    velocities: Option<usize>,
2143    masses: Option<usize>,
2144    cell: Option<usize>,
2145    atom_ids: Option<&[u64]>,
2146    fixed: Option<&[u8]>,
2147    run: usize,
2148    mut emit: impl FnMut(usize, std::ops::Range<usize>, &mut File) -> Result<(), ParseError>,
2149) -> Result<ConBinHeader, ParseError> {
2150    let header = f64_columns_header(
2151        n_frames,
2152        n_atoms,
2153        positions,
2154        velocities,
2155        masses,
2156        cell,
2157        atom_ids.map(<[u64]>::len),
2158        fixed.map(<[u8]>::len),
2159    )?;
2160    let page = page_size()?;
2161    let mut counts = vec![positions];
2162    counts.extend(velocities);
2163    counts.extend(masses);
2164    counts.extend(cell);
2165    let overflow = || ParseError::InvalidCount("CON-bin file length overflows".into());
2166    let values = counts
2167        .iter()
2168        .copied()
2169        .chain(atom_ids.map(<[u64]>::len))
2170        .try_fold(0u64, |sum, count| sum.checked_add(count as u64))
2171        .ok_or_else(overflow)?;
2172    let total = values
2173        .checked_mul(8)
2174        .and_then(|bytes| bytes.checked_add(fixed.map_or(0, <[u8]>::len) as u64))
2175        .and_then(|bytes| bytes.checked_add(page as u64))
2176        .ok_or_else(overflow)?;
2177    let run = run.max(1);
2178    crate::writer::publish_new(
2179        path,
2180        |err| ParseError::ValidationError(err.to_string()),
2181        |file| {
2182            preallocate(file, total)?;
2183            file.write_all(&header_page_bytes(&header, page))
2184                .map_err(|err| ParseError::ValidationError(err.to_string()))?;
2185            for (column, count) in counts.iter().copied().enumerate() {
2186                let mut at = 0;
2187                while at < count {
2188                    let end = (at + run).min(count);
2189                    emit(column, at..end, file)?;
2190                    at = end;
2191                }
2192            }
2193            if let Some(values) = atom_ids {
2194                write_le(file, values)?;
2195            }
2196            if let Some(values) = fixed {
2197                write_le(file, values)?;
2198            }
2199            Ok(())
2200        },
2201    )?;
2202    Ok(header)
2203}
2204
2205/// Write version 2 from columns already in memory.
2206///
2207/// Positions are required. Velocities, masses, the cell, atom ids and the
2208/// per-axis fixed mask are stored when the caller passes them. The payload
2209/// order is positions, velocities, masses, cell, atom ids, fixed masks.
2210fn column_len(name: &str, got: usize, want: usize) -> Result<(), ParseError> {
2211    if got == want {
2212        return Ok(());
2213    }
2214    Err(ParseError::InvalidCount(format!(
2215        "CON-bin {name} has {got} values, need {want}"
2216    )))
2217}
2218
2219/// Check the value counts of a version-2 binary64 write and build its header.
2220#[allow(clippy::too_many_arguments)]
2221fn f64_columns_header(
2222    n_frames: u64,
2223    n_atoms: u64,
2224    positions: usize,
2225    velocities: Option<usize>,
2226    masses: Option<usize>,
2227    cell: Option<usize>,
2228    atom_ids: Option<usize>,
2229    fixed: Option<usize>,
2230) -> Result<ConBinHeader, ParseError> {
2231    let frames = usize::try_from(n_frames)
2232        .map_err(|_| ParseError::InvalidCount("CON-bin frame count does not fit".into()))?;
2233    let atoms = usize::try_from(n_atoms)
2234        .map_err(|_| ParseError::InvalidCount("CON-bin atom count does not fit".into()))?;
2235    let n = frames
2236        .checked_mul(atoms)
2237        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
2238    let xyz = n
2239        .checked_mul(3)
2240        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
2241    let cells = frames
2242        .checked_mul(6)
2243        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
2244    column_len("positions", positions, xyz)?;
2245    if let Some(values) = velocities {
2246        column_len("velocities", values, xyz)?;
2247    }
2248    if let Some(values) = masses {
2249        column_len("masses", values, n)?;
2250    }
2251    if let Some(values) = cell {
2252        column_len("cell", values, cells)?;
2253    }
2254    if let Some(values) = atom_ids {
2255        column_len("atom ids", values, n)?;
2256    }
2257    if let Some(values) = fixed {
2258        column_len("fixed masks", values, n)?;
2259    }
2260    Ok(ConBinHeader {
2261        version: VERSION_2,
2262        n_frames,
2263        n_atoms,
2264        binary32: false,
2265        velocities: velocities.is_some(),
2266        forces: false,
2267        masses: masses.is_some(),
2268        fixed: fixed.is_some(),
2269        cell: cell.is_some(),
2270        atom_ids: atom_ids.is_some(),
2271    })
2272}
2273
2274#[allow(clippy::too_many_arguments)]
2275pub fn write_f64_columns(
2276    path: &Path,
2277    n_frames: u64,
2278    n_atoms: u64,
2279    positions: &[f64],
2280    velocities: Option<&[f64]>,
2281    masses: Option<&[f64]>,
2282    cell: Option<&[f64]>,
2283    atom_ids: Option<&[u64]>,
2284    fixed: Option<&[u8]>,
2285) -> Result<ConBinHeader, ParseError> {
2286    let header = f64_columns_header(
2287        n_frames,
2288        n_atoms,
2289        positions.len(),
2290        velocities.map(<[f64]>::len),
2291        masses.map(<[f64]>::len),
2292        cell.map(<[f64]>::len),
2293        atom_ids.map(<[u64]>::len),
2294        fixed.map(<[u8]>::len),
2295    )?;
2296    if let Some(values) = cell {
2297        crate::types::check_cell_rows(values)?;
2298    }
2299    let page = page_size()?;
2300    #[cfg(target_endian = "little")]
2301    {
2302        let mut parts = Vec::with_capacity(6);
2303        parts.push(view_bytes(positions));
2304        if let Some(values) = velocities {
2305            parts.push(view_bytes(values));
2306        }
2307        if let Some(values) = masses {
2308            parts.push(view_bytes(values));
2309        }
2310        if let Some(values) = cell {
2311            parts.push(view_bytes(values));
2312        }
2313        if let Some(values) = atom_ids {
2314            parts.push(view_bytes(values));
2315        }
2316        if let Some(values) = fixed {
2317            parts.push(view_bytes(values));
2318        }
2319        publish_assembled(path, &header, page, &parts)?;
2320    }
2321    #[cfg(target_endian = "big")]
2322    {
2323        let pos = le_bytes(positions);
2324        let vel = velocities.map(le_bytes);
2325        let mass = masses.map(le_bytes);
2326        let box_cell = cell.map(le_bytes);
2327        let ids = atom_ids.map(le_bytes);
2328        let masks = fixed.map(le_bytes);
2329        let mut parts = Vec::with_capacity(6);
2330        parts.push(pos.as_slice());
2331        if let Some(values) = vel.as_ref() {
2332            parts.push(values);
2333        }
2334        if let Some(values) = mass.as_ref() {
2335            parts.push(values);
2336        }
2337        if let Some(values) = box_cell.as_ref() {
2338            parts.push(values);
2339        }
2340        if let Some(values) = ids.as_ref() {
2341            parts.push(values);
2342        }
2343        if let Some(values) = masks.as_ref() {
2344            parts.push(values);
2345        }
2346        publish_assembled(path, &header, page, &parts)?;
2347    }
2348    Ok(header)
2349}
2350
2351/// Write one binary64 file whose columns come from `seed`.
2352///
2353/// The header page and both runs match what [`map_file`] and [`read_into`] read.
2354/// `seed` is mixed with each value index, so the same triple writes the same file.
2355/// The bytes are published by rename, the same way [`write_f64_columns`] is,
2356/// so a reader that still holds an older mapping keeps that inode.
2357pub fn write_uniform(
2358    path: &Path,
2359    frames: u64,
2360    atoms: u64,
2361    seed: u64,
2362) -> Result<ConBinHeader, ParseError> {
2363    let header = ConBinHeader {
2364        version: VERSION_2,
2365        n_frames: frames,
2366        n_atoms: atoms,
2367        binary32: false,
2368        velocities: true,
2369        forces: false,
2370        masses: false,
2371        fixed: false,
2372        cell: false,
2373        atom_ids: false,
2374    };
2375    let n = header.position_len()?;
2376    let page = page_size()?;
2377    let pos: Vec<f64> = (0..n).map(|i| mix_unit(seed, i as u64)).collect();
2378    let vel: Vec<f64> = (0..n)
2379        .map(|i| mix_unit(seed, (n as u64) + i as u64))
2380        .collect();
2381    #[cfg(target_endian = "little")]
2382    publish_assembled(path, &header, page, &[view_bytes(&pos), view_bytes(&vel)])?;
2383    #[cfg(target_endian = "big")]
2384    {
2385        let pos_le = le_bytes(&pos);
2386        let vel_le = le_bytes(&vel);
2387        publish_assembled(path, &header, page, &[pos_le.as_slice(), vel_le.as_slice()])?;
2388    }
2389    Ok(header)
2390}
2391
2392/// SplitMix64 finalizer, then a unit interval.
2393/// The multipliers and shift distances are the ones in Steele, Lea and Flood, 2014.
2394const SPLITMIX_MUL_1: u64 = 0x9E37_79B9_7F4A_7C15;
2395const SPLITMIX_MUL_2: u64 = 0xBF58_476D_1CE4_E5B9;
2396const SPLITMIX_MUL_3: u64 = 0x94D0_49BB_1331_11EB;
2397const SPLITMIX_SHIFT_1: u32 = 30;
2398const SPLITMIX_SHIFT_2: u32 = 27;
2399const SPLITMIX_SHIFT_3: u32 = 31;
2400const SPLITMIX_FLOAT_SHIFT: u32 = 11;
2401const SPLITMIX_FLOAT_BITS: u32 = 53;
2402
2403fn mix_unit(seed: u64, index: u64) -> f64 {
2404    let mut z = seed.wrapping_add(index).wrapping_mul(SPLITMIX_MUL_1);
2405    z = (z ^ (z >> SPLITMIX_SHIFT_1)).wrapping_mul(SPLITMIX_MUL_2);
2406    z = (z ^ (z >> SPLITMIX_SHIFT_2)).wrapping_mul(SPLITMIX_MUL_3);
2407    z ^= z >> SPLITMIX_SHIFT_3;
2408    (z >> SPLITMIX_FLOAT_SHIFT) as f64 / ((1u64 << SPLITMIX_FLOAT_BITS) as f64)
2409}
2410
2411/// Stream a CON text file into a CON-bin of the same frames.
2412///
2413/// The header occupies one host page, so the payload starts on a page
2414/// boundary. Positions of every frame are written as one run, then velocities.
2415///
2416/// ```
2417/// use readcon_core::conbin::{read_owned_f64, write_from_con};
2418/// use std::path::Path;
2419///
2420/// let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
2421/// let dir = tempfile::tempdir().unwrap();
2422/// let out = dir.path().join("tiny.bin");
2423/// let header = write_from_con(&src, &out, false).unwrap();
2424/// assert_eq!((header.n_frames, header.n_atoms), (1, 4));
2425/// let (again, positions, velocities) = read_owned_f64(&out, 1).unwrap();
2426/// assert_eq!(again.n_frames, 1);
2427/// assert_eq!(positions.len(), 12);
2428/// assert!((positions[0] - 0.6394).abs() < 1e-4);
2429/// assert_eq!(velocities.len(), 12);
2430/// ```
2431pub fn write_from_con(
2432    con_path: &Path,
2433    out_path: &Path,
2434    binary32: bool,
2435) -> Result<ConBinHeader, ParseError> {
2436    write_from_con_with_threads(con_path, out_path, binary32, 1)
2437}
2438
2439/// [`write_from_con`] using `threads` to parse equal-length frames.
2440///
2441/// A file that is not a sequence of equal-length frames stays on one
2442/// thread: the frame boundaries are only known by parsing it in order.
2443/// Equal-length frames are parsed on `threads` workers. Each worker then
2444/// `pwrite`s its own column chunks into a preallocated file, and the
2445/// publish is still one rename. A file that is not equal-length frames
2446/// stays on one thread. The output matches the one-thread writer.
2447///
2448/// Eight thousand copies of `cuh2.con` (114 MB of CON-bin) took 0.343 s,
2449/// 0.212 s, 0.138 s and 0.117 s at 1, 2, 4 and 8 threads. The speedup is
2450/// about 2.9 at 8 threads. Weak scaling still grows the file with the
2451/// worker count, so the wall time cannot stay flat.
2452pub fn write_from_con_with_threads(
2453    con_path: &Path,
2454    out_path: &Path,
2455    binary32: bool,
2456    threads: usize,
2457) -> Result<ConBinHeader, ParseError> {
2458    let text = std::fs::read_to_string(con_path)
2459        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
2460    let page = page_size()?;
2461    crate::writer::publish_new(
2462        out_path,
2463        |err| ParseError::ValidationError(err.to_string()),
2464        |file| write_conbin_body(file, &text, binary32, page, threads),
2465    )?;
2466    read_header(out_path)
2467}
2468
2469struct FrameColumns {
2470    n_frames: u64,
2471    n_atoms: u64,
2472    positions: Vec<f64>,
2473    velocities: Vec<f64>,
2474    forces: Vec<f64>,
2475    masses: Vec<f64>,
2476    fixed: Vec<u8>,
2477    cells: Vec<f64>,
2478    ids: Vec<u64>,
2479    any_force: bool,
2480    any_velocity: bool,
2481}
2482
2483fn equal_frame_span(text: &str) -> Option<usize> {
2484    let nl = text.find('\n')?;
2485    let marker = &text[..=nl];
2486    let rest = text.get(marker.len()..)?;
2487    let rel = rest.find(marker)?;
2488    let span = marker.len() + rel;
2489    if span < 32 || text.len() % span != 0 {
2490        return None;
2491    }
2492    let n = text.len() / span;
2493    if n < 2 {
2494        return None;
2495    }
2496    for index in 1..n {
2497        if !text[index * span..].starts_with(marker) {
2498            return None;
2499        }
2500    }
2501    Some(span)
2502}
2503
2504/// The columns of the frames in `text`. `first_frame` is the index of the
2505/// first of them in the whole file, so a failure names its global frame.
2506fn accumulate_frames(text: &str, first_frame: u64) -> Result<FrameColumns, ParseError> {
2507    let mut n_frames = 0u64;
2508    let mut n_atoms = 0u64;
2509    let mut positions = Vec::new();
2510    let mut velocities = Vec::new();
2511    let mut forces = Vec::new();
2512    let mut masses = Vec::new();
2513    let mut fixed = Vec::new();
2514    let mut cells = Vec::new();
2515    let mut ids = Vec::new();
2516    let mut any_force = false;
2517    let mut any_velocity = false;
2518    for frame in ConFrameIterator::new(text) {
2519        let frame = frame.map_err(|error| error.in_frame(first_frame + n_frames))?;
2520        let n = frame.atom_data.len();
2521        if n_frames == 0 {
2522            n_atoms = n as u64;
2523        } else if n as u64 != n_atoms {
2524            return Err(ParseError::InvalidCount(
2525                "CON-bin requires the same atom count in every frame".into(),
2526            ));
2527        }
2528        let xyz = n.saturating_mul(3);
2529        positions.reserve(xyz);
2530        velocities.reserve(xyz);
2531        forces.reserve(xyz);
2532        masses.reserve(n);
2533        fixed.reserve(n);
2534        ids.reserve(n);
2535        cells.reserve(6);
2536        let mut mass_at = 0usize;
2537        for (count, mass) in frame
2538            .header
2539            .natms_per_type
2540            .iter()
2541            .zip(frame.header.masses_per_type.iter())
2542        {
2543            for _ in 0..*count {
2544                masses.push(*mass);
2545                mass_at += 1;
2546            }
2547        }
2548        if mass_at < n {
2549            let fill = frame.header.masses_per_type.last().copied().unwrap_or(0.0);
2550            masses.extend(std::iter::repeat_n(fill, n - mass_at));
2551        } else if mass_at > n {
2552            masses.truncate(masses.len() - (mass_at - n));
2553        }
2554        cells.extend_from_slice(&frame.header.boxl);
2555        cells.extend_from_slice(&frame.header.angles);
2556        any_velocity |= frame.has_velocities();
2557        for (index, atom) in frame.atom_data.iter().enumerate() {
2558            positions.extend_from_slice(&frame.xyz_at(index));
2559            velocities.extend_from_slice(&atom.velocity().unwrap_or([0.0; 3]));
2560            if let Some(row) = atom.force() {
2561                any_force = true;
2562                forces.extend_from_slice(&row);
2563            } else {
2564                forces.extend_from_slice(&[0.0, 0.0, 0.0]);
2565            }
2566            let flags = atom.fixed();
2567            fixed.push(u8::from(flags[0]) | (u8::from(flags[1]) << 1) | (u8::from(flags[2]) << 2));
2568            ids.push(atom.atom_id);
2569        }
2570        n_frames += 1;
2571    }
2572    Ok(FrameColumns {
2573        n_frames,
2574        n_atoms,
2575        positions,
2576        velocities,
2577        forces,
2578        masses,
2579        fixed,
2580        cells,
2581        ids,
2582        any_force,
2583        any_velocity,
2584    })
2585}
2586
2587fn equal_parts(text: &str, threads: usize) -> Result<Option<Vec<(u64, FrameColumns)>>, ParseError> {
2588    let Some(span) = equal_frame_span(text) else {
2589        return Ok(None);
2590    };
2591    let n = text.len() / span;
2592    let threads = threads.max(1).min(n);
2593    if threads < 2 {
2594        return Ok(None);
2595    }
2596    let mut parts = Vec::with_capacity(threads);
2597    std::thread::scope(|scope| {
2598        let mut jobs = Vec::with_capacity(threads);
2599        for thread in 0..threads {
2600            let start = n * thread / threads;
2601            let end = n * (thread + 1) / threads;
2602            let chunk = &text[start * span..end * span];
2603            jobs.push(scope.spawn(move || (start as u64, accumulate_frames(chunk, start as u64))));
2604        }
2605        for job in jobs {
2606            parts.push(job.join().expect("frame parse"));
2607        }
2608    });
2609    let mut built = Vec::with_capacity(parts.len());
2610    for (begin, columns) in parts {
2611        built.push((begin, columns?));
2612    }
2613    Ok(Some(built))
2614}
2615
2616fn write_at(file: &File, mut bytes: &[u8], mut offset: u64) -> Result<(), ParseError> {
2617    while !bytes.is_empty() {
2618        #[cfg(unix)]
2619        let wrote = {
2620            use std::os::unix::fs::FileExt;
2621            file.write_at(bytes, offset)
2622                .map_err(|err| ParseError::ValidationError(err.to_string()))?
2623        };
2624        #[cfg(not(unix))]
2625        let wrote = {
2626            use std::os::windows::fs::FileExt;
2627            file.seek_write(bytes, offset)
2628                .map_err(|err| ParseError::ValidationError(err.to_string()))?
2629        };
2630        if wrote == 0 {
2631            return Err(ParseError::ValidationError(
2632                "positioned write stored no bytes".into(),
2633            ));
2634        }
2635        bytes = &bytes[wrote..];
2636        offset += wrote as u64;
2637    }
2638    Ok(())
2639}
2640
2641fn store_at<T: StoreLe>(file: &File, values: &[T], offset: u64) -> Result<(), ParseError> {
2642    if values.is_empty() {
2643        return Ok(());
2644    }
2645    if cfg!(target_endian = "little") {
2646        let bytes = unsafe {
2647            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
2648        };
2649        return write_at(file, bytes, offset);
2650    }
2651    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
2652    for value in values {
2653        value.store_le(&mut bytes);
2654    }
2655    write_at(file, &bytes, offset)
2656}
2657
2658fn store_f32_at(file: &File, values: &[f64], offset: u64) -> Result<(), ParseError> {
2659    let narrow: Vec<f32> = values.iter().map(|value| *value as f32).collect();
2660    store_at(file, &narrow, offset)
2661}
2662
2663fn preallocate(file: &File, len: u64) -> Result<(), ParseError> {
2664    // `allocate_len(0)` leaves the current length. An empty CON-bin is
2665    // truncated. Every other length uses the shared reserve: `fallocate`
2666    // on Linux and Android, `posix_fallocate` on FreeBSD, `F_PREALLOCATE`
2667    // on macOS, and `set_len` on Windows and when the filesystem rejects it.
2668    let result = if len == 0 {
2669        file.set_len(0)
2670    } else {
2671        crate::writer::allocate_len(file, len)
2672    };
2673    result.map_err(|err| ParseError::ValidationError(err.to_string()))
2674}
2675
2676fn write_parts_at(
2677    file: &File,
2678    parts: &[(u64, FrameColumns)],
2679    binary32: bool,
2680    page: usize,
2681) -> Result<(), ParseError> {
2682    let n_atoms = parts[0].1.n_atoms;
2683    let mut n_frames = 0u64;
2684    let mut any_force = false;
2685    for (begin, columns) in parts {
2686        if columns.n_atoms != n_atoms {
2687            return Err(ParseError::InvalidCount(
2688                "CON-bin requires the same atom count in every frame".into(),
2689            ));
2690        }
2691        if *begin != n_frames {
2692            return Err(ParseError::ValidationError(
2693                "CON-bin frame chunks are not in order".into(),
2694            ));
2695        }
2696        n_frames += columns.n_frames;
2697        any_force |= columns.any_force;
2698    }
2699    let elem = if binary32 { 4u64 } else { 8 };
2700    let xyz = n_frames * n_atoms * 3 * elem;
2701    let mut at = page as u64;
2702    let pos_at = at;
2703    at += xyz;
2704    let vel_at = at;
2705    at += xyz;
2706    let force_at = if any_force {
2707        let here = at;
2708        at += xyz;
2709        Some(here)
2710    } else {
2711        None
2712    };
2713    let mass_at = at;
2714    at += n_frames * n_atoms * elem;
2715    let cell_at = at;
2716    at += n_frames * 6 * elem;
2717    let id_at = at;
2718    at += n_frames * n_atoms * 8;
2719    let fix_at = at;
2720    at += n_frames * n_atoms;
2721    preallocate(file, at)?;
2722    let stride_xyz = n_atoms * 3 * elem;
2723    let stride_atom = n_atoms * elem;
2724    let mut failed: Option<ParseError> = None;
2725    std::thread::scope(|scope| {
2726        let mut jobs = Vec::with_capacity(parts.len());
2727        for (begin, columns) in parts {
2728            jobs.push(scope.spawn(move || -> Result<(), ParseError> {
2729                if binary32 {
2730                    check_cells_fit_binary32(&columns.cells, *begin)?;
2731                    store_f32_at(file, &columns.positions, pos_at + begin * stride_xyz)?;
2732                    store_f32_at(file, &columns.velocities, vel_at + begin * stride_xyz)?;
2733                    if let Some(force_at) = force_at {
2734                        store_f32_at(file, &columns.forces, force_at + begin * stride_xyz)?;
2735                    }
2736                    store_f32_at(file, &columns.masses, mass_at + begin * stride_atom)?;
2737                    store_f32_at(file, &columns.cells, cell_at + begin * 6 * elem)?;
2738                } else {
2739                    store_at(file, &columns.positions, pos_at + begin * stride_xyz)?;
2740                    store_at(file, &columns.velocities, vel_at + begin * stride_xyz)?;
2741                    if let Some(force_at) = force_at {
2742                        store_at(file, &columns.forces, force_at + begin * stride_xyz)?;
2743                    }
2744                    store_at(file, &columns.masses, mass_at + begin * stride_atom)?;
2745                    store_at(file, &columns.cells, cell_at + begin * 6 * elem)?;
2746                }
2747                store_at(file, &columns.ids, id_at + begin * n_atoms * 8)?;
2748                store_at(file, &columns.fixed, fix_at + begin * n_atoms)?;
2749                Ok(())
2750            }));
2751        }
2752        for job in jobs {
2753            if let Err(err) = job.join().expect("column write") {
2754                failed = Some(err);
2755            }
2756        }
2757    });
2758    if let Some(err) = failed {
2759        return Err(err);
2760    }
2761    let header = ConBinHeader {
2762        version: VERSION_2,
2763        n_frames,
2764        n_atoms,
2765        binary32,
2766        velocities: true,
2767        forces: any_force,
2768        masses: true,
2769        fixed: true,
2770        cell: true,
2771        atom_ids: true,
2772    };
2773    let page_bytes = header_page_bytes(&header, page);
2774    write_at(file, &page_bytes, 0)
2775}
2776
2777fn write_conbin_body(
2778    file: &mut File,
2779    text: &str,
2780    binary32: bool,
2781    page: usize,
2782    threads: usize,
2783) -> Result<(), ParseError> {
2784    if threads > 1 {
2785        if let Some(parts) = equal_parts(text, threads)? {
2786            return write_parts_at(file, &parts, binary32, page);
2787        }
2788    }
2789    let built = accumulate_frames(text, 0)?;
2790    let header = ConBinHeader {
2791        version: VERSION_2,
2792        n_frames: built.n_frames,
2793        n_atoms: built.n_atoms,
2794        binary32,
2795        velocities: true,
2796        forces: built.any_force,
2797        masses: true,
2798        fixed: true,
2799        cell: true,
2800        atom_ids: true,
2801    };
2802    emit_built(file, &header, page, binary32, &built)
2803}
2804
2805/// A cell that is finite in binary64 can still be infinite in binary32. The
2806/// file would store that infinity, so the write is refused and names the
2807/// frame (`first_frame` plus the row) and the field.
2808fn check_cells_fit_binary32(cells: &[f64], first_frame: u64) -> Result<(), ParseError> {
2809    if cells.iter().all(|v| (*v as f32).is_finite()) {
2810        return Ok(());
2811    }
2812    for (row_index, row) in cells.chunks(6).enumerate() {
2813        if let Some((index, value)) = row
2814            .iter()
2815            .enumerate()
2816            .find(|(_, v)| !(**v as f32).is_finite())
2817        {
2818            return Err(ParseError::non_finite_cell(
2819                &format!("cell[{index}]"),
2820                format!("{value} (infinite in binary32)"),
2821            )
2822            .in_frame(first_frame + row_index as u64));
2823        }
2824    }
2825    Ok(())
2826}
2827
2828fn emit_built(
2829    file: &mut File,
2830    header: &ConBinHeader,
2831    page: usize,
2832    binary32: bool,
2833    built: &FrameColumns,
2834) -> Result<(), ParseError> {
2835    let _ = built.any_velocity;
2836    #[cfg(target_endian = "little")]
2837    {
2838        if binary32 {
2839            check_cells_fit_binary32(&built.cells, 0)?;
2840            let pos32: Vec<f32> = built.positions.iter().map(|v| *v as f32).collect();
2841            let vel32: Vec<f32> = built.velocities.iter().map(|v| *v as f32).collect();
2842            let force32 = if built.any_force {
2843                Some(built.forces.iter().map(|v| *v as f32).collect::<Vec<f32>>())
2844            } else {
2845                None
2846            };
2847            let mass32: Vec<f32> = built.masses.iter().map(|v| *v as f32).collect();
2848            let cell32: Vec<f32> = built.cells.iter().map(|v| *v as f32).collect();
2849            let mut parts = Vec::with_capacity(7);
2850            parts.push(view_bytes(&pos32));
2851            parts.push(view_bytes(&vel32));
2852            if let Some(values) = force32.as_ref() {
2853                parts.push(view_bytes(values));
2854            }
2855            parts.push(view_bytes(&mass32));
2856            parts.push(view_bytes(&cell32));
2857            parts.push(view_bytes(&built.ids));
2858            parts.push(view_bytes(&built.fixed));
2859            write_assembled(file, header, page, &parts)
2860        } else {
2861            let mut parts = Vec::with_capacity(7);
2862            parts.push(view_bytes(&built.positions));
2863            parts.push(view_bytes(&built.velocities));
2864            if built.any_force {
2865                parts.push(view_bytes(&built.forces));
2866            }
2867            parts.push(view_bytes(&built.masses));
2868            parts.push(view_bytes(&built.cells));
2869            parts.push(view_bytes(&built.ids));
2870            parts.push(view_bytes(&built.fixed));
2871            write_assembled(file, header, page, &parts)
2872        }
2873    }
2874    #[cfg(target_endian = "big")]
2875    {
2876        let mut owned = Vec::with_capacity(7);
2877        if binary32 {
2878            check_cells_fit_binary32(&built.cells, 0)?;
2879            let pos32: Vec<f32> = built.positions.iter().map(|v| *v as f32).collect();
2880            let vel32: Vec<f32> = built.velocities.iter().map(|v| *v as f32).collect();
2881            let force32: Vec<f32> = built.forces.iter().map(|v| *v as f32).collect();
2882            let mass32: Vec<f32> = built.masses.iter().map(|v| *v as f32).collect();
2883            let cell32: Vec<f32> = built.cells.iter().map(|v| *v as f32).collect();
2884            owned.push(le_bytes(&pos32));
2885            owned.push(le_bytes(&vel32));
2886            if built.any_force {
2887                owned.push(le_bytes(&force32));
2888            }
2889            owned.push(le_bytes(&mass32));
2890            owned.push(le_bytes(&cell32));
2891        } else {
2892            owned.push(le_bytes(&built.positions));
2893            owned.push(le_bytes(&built.velocities));
2894            if built.any_force {
2895                owned.push(le_bytes(&built.forces));
2896            }
2897            owned.push(le_bytes(&built.masses));
2898            owned.push(le_bytes(&built.cells));
2899        }
2900        owned.push(le_bytes(&built.ids));
2901        owned.push(le_bytes(&built.fixed));
2902        let parts: Vec<&[u8]> = owned.iter().map(|bytes| bytes.as_slice()).collect();
2903        write_assembled(file, header, page, &parts)
2904    }
2905}
2906
2907#[cfg(test)]
2908mod tests {
2909    use super::*;
2910
2911    #[cfg(target_endian = "little")]
2912    #[test]
2913    fn view_bytes_matches_the_number_encoding() {
2914        let values = [1.5f64, -0.25];
2915        let mut expect = Vec::new();
2916        for value in values {
2917            expect.extend_from_slice(&value.to_le_bytes());
2918        }
2919        assert_eq!(view_bytes(&values), expect.as_slice());
2920    }
2921
2922    fn reject_short(label: &str, needle: &str, want: &str) {
2923        let dir = tempfile::tempdir().unwrap();
2924        let path = dir.path().join("short.bin");
2925        let positions = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
2926        let err = match label {
2927            "positions" => {
2928                write_f64_columns(&path, 1, 2, &[0.0, 1.0, 2.0], None, None, None, None, None)
2929            }
2930            "velocities" => write_f64_columns(
2931                &path,
2932                1,
2933                2,
2934                &positions,
2935                Some(&[0.0, 1.0, 2.0]),
2936                None,
2937                None,
2938                None,
2939                None,
2940            ),
2941            "masses" => write_f64_columns(
2942                &path,
2943                1,
2944                2,
2945                &positions,
2946                None,
2947                Some(&[63.5]),
2948                None,
2949                None,
2950                None,
2951            ),
2952            "cell" => write_f64_columns(
2953                &path,
2954                1,
2955                2,
2956                &positions,
2957                None,
2958                None,
2959                Some(&[1.0, 1.0, 1.0]),
2960                None,
2961                None,
2962            ),
2963            "atom ids" => {
2964                write_f64_columns(&path, 1, 2, &positions, None, None, None, Some(&[0]), None)
2965            }
2966            "fixed masks" => {
2967                write_f64_columns(&path, 1, 2, &positions, None, None, None, None, Some(&[0]))
2968            }
2969            _ => panic!("unknown column {label}"),
2970        }
2971        .expect_err(label);
2972        let message = err.to_string();
2973        assert!(
2974            message.contains(needle) && message.contains(want),
2975            "{message}"
2976        );
2977        assert!(!path.exists(), "a rejected column must not publish a file");
2978    }
2979
2980    #[test]
2981    fn a_short_positions_column_is_rejected_before_publish() {
2982        reject_short("positions", "positions", "need 6");
2983    }
2984
2985    #[test]
2986    fn a_short_velocities_column_is_rejected_before_publish() {
2987        reject_short("velocities", "velocities", "need 6");
2988    }
2989
2990    #[test]
2991    fn a_short_masses_column_is_rejected_before_publish() {
2992        reject_short("masses", "masses", "need 2");
2993    }
2994
2995    #[test]
2996    fn a_short_cell_column_is_rejected_before_publish() {
2997        reject_short("cell", "cell", "need 6");
2998    }
2999
3000    #[test]
3001    fn a_short_atom_id_column_is_rejected_before_publish() {
3002        reject_short("atom ids", "atom ids", "need 2");
3003    }
3004
3005    #[test]
3006    fn a_short_fixed_mask_column_is_rejected_before_publish() {
3007        reject_short("fixed masks", "fixed masks", "need 2");
3008    }
3009
3010    fn write_known(path: &Path, frames: usize, atoms: usize) {
3011        let page = page_size().unwrap();
3012        let mut file = File::create(path).unwrap();
3013        let header = ConBinHeader::version1(frames as u64, atoms as u64, false, true);
3014        write_header_page(&mut file, &header, page).unwrap();
3015        let n = frames * atoms * 3;
3016        let pos: Vec<f64> = (0..n).map(|i| i as f64 * 0.25).collect();
3017        let vel: Vec<f64> = (0..n).map(|i| i as f64 * -0.5).collect();
3018        write_values(&mut file, &pos).unwrap();
3019        write_values(&mut file, &vel).unwrap();
3020    }
3021
3022    #[test]
3023    fn wide_columns_are_read_by_several_workers() {
3024        let dir = tempfile::tempdir().unwrap();
3025        let path = dir.path().join("wide-workers.conbin");
3026        write_known(&path, 2, 2048);
3027        let (header, pos, vel) = read_owned_f64(&path, 4).unwrap();
3028        let n = header.position_len().unwrap();
3029        let mut again_pos = vec![0.0; n];
3030        let mut again_vel = vec![0.0; n];
3031        read_into_threads(&path, &mut again_pos, Some(&mut again_vel), 4).unwrap();
3032        assert_eq!(pos, again_pos);
3033        assert_eq!(vel, again_vel);
3034        assert_eq!(pos[0], 0.0);
3035        assert_eq!(vel[1], -0.5);
3036    }
3037
3038    /// Four atoms per frame, one shared header line, coordinates that move.
3039    ///
3040    /// Fixed widths keep `equal_frame_span` able to split the file. A test
3041    /// that repeats one frame still passes if the chunks are written backwards.
3042    fn distinct_frames(n: usize) -> String {
3043        let mut text = String::new();
3044        for frame in 0..n {
3045            text.push_str(
3046                "distinct\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n4\n63.546\nCu\nCoordinates of Component 1\n",
3047            );
3048            for atom in 0..4 {
3049                text.push_str(&format!(
3050                    "{:10.4} {:10.4} {:10.4} 0 {:3}\n",
3051                    frame as f64 + atom as f64 * 0.25,
3052                    0.5,
3053                    1.5,
3054                    atom
3055                ));
3056            }
3057        }
3058        text
3059    }
3060
3061    fn positions_in_part_order(text: &str, threads: usize) -> Vec<f64> {
3062        let parts = equal_parts(text, threads).unwrap().unwrap();
3063        let mut out = Vec::new();
3064        for (_, columns) in parts {
3065            out.extend(columns.positions);
3066        }
3067        out
3068    }
3069
3070    /// The bug the identical-copy test missed: later chunks labeled as earlier frames.
3071    fn positions_if_chunks_are_reversed(text: &str, threads: usize) -> Vec<f64> {
3072        let span = equal_frame_span(text).unwrap();
3073        let n = text.len() / span;
3074        let threads = threads.max(1).min(n);
3075        let mut chunks = Vec::with_capacity(threads);
3076        for thread in 0..threads {
3077            let start = n * thread / threads;
3078            let end = n * (thread + 1) / threads;
3079            chunks.push(accumulate_frames(&text[start * span..end * span], 0).unwrap());
3080        }
3081        chunks.reverse();
3082        let mut out = Vec::new();
3083        for columns in chunks {
3084            out.extend(columns.positions);
3085        }
3086        out
3087    }
3088
3089    #[test]
3090    fn repeated_frames_on_several_threads_match_one_thread() {
3091        let text = distinct_frames(8);
3092        let serial_positions = accumulate_frames(&text, 0).unwrap().positions;
3093        assert_eq!(positions_in_part_order(&text, 4), serial_positions);
3094        assert_ne!(
3095            positions_if_chunks_are_reversed(&text, 4),
3096            serial_positions,
3097            "reversed chunks of identical frames would still match"
3098        );
3099        let dir = tempfile::tempdir().unwrap();
3100        let input = dir.path().join("in.con");
3101        std::fs::write(&input, &text).unwrap();
3102        for binary32 in [false, true] {
3103            let one = dir.path().join(format!("one-{binary32}.conbin"));
3104            write_from_con_with_threads(&input, &one, binary32, 1).unwrap();
3105            let serial = std::fs::read(&one).unwrap();
3106            for threads in [2usize, 4, 8] {
3107                let many = dir.path().join(format!("t{threads}-{binary32}.conbin"));
3108                write_from_con_with_threads(&input, &many, binary32, threads).unwrap();
3109                assert_eq!(
3110                    std::fs::read(&many).unwrap(),
3111                    serial,
3112                    "threads {threads} binary32 {binary32}"
3113                );
3114            }
3115        }
3116    }
3117
3118    #[test]
3119    fn column_writer_publishes_every_optional_run() {
3120        let dir = tempfile::tempdir().unwrap();
3121        let path = dir.path().join("columns.conbin");
3122        let header = write_f64_columns(
3123            &path,
3124            1,
3125            2,
3126            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
3127            Some(&[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]),
3128            Some(&[63.5, 1.0]),
3129            Some(&[10.0, 10.0, 10.0, 90.0, 90.0, 90.0]),
3130            Some(&[7, 8]),
3131            Some(&[0b001, 0b100]),
3132        )
3133        .unwrap();
3134        assert!(
3135            header.velocities && header.masses && header.cell && header.atom_ids && header.fixed
3136        );
3137        let again = read_header(&path).unwrap();
3138        assert_eq!(again.n_atoms, 2);
3139        assert!(again.masses && again.atom_ids);
3140        let mapped = map_file(&path, 1).unwrap();
3141        assert_eq!(
3142            mapped.positions_f64().unwrap(),
3143            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
3144        );
3145    }
3146
3147    #[test]
3148    fn f64_columns_round_trip_matches_the_bytes() {
3149        let dir = tempfile::tempdir().unwrap();
3150        let path = dir.path().join("columns.conbin");
3151        let positions = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
3152        let velocities = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5];
3153        let masses = [12.0, 16.0];
3154        let cell = [10.0, 11.0, 12.0, 90.0, 90.0, 90.0];
3155        let ids = [3u64, 4];
3156        let fixed = [0b001u8, 0b110];
3157        let header = write_f64_columns(
3158            &path,
3159            1,
3160            2,
3161            &positions,
3162            Some(&velocities),
3163            Some(&masses),
3164            Some(&cell),
3165            Some(&ids),
3166            Some(&fixed),
3167        )
3168        .unwrap();
3169        let bytes = std::fs::read(&path).unwrap();
3170        let copy = dir.path().join("copy.conbin");
3171        write_f64_columns(
3172            &copy,
3173            1,
3174            2,
3175            &positions,
3176            Some(&velocities),
3177            Some(&masses),
3178            Some(&cell),
3179            Some(&ids),
3180            Some(&fixed),
3181        )
3182        .unwrap();
3183        assert_eq!(std::fs::read(&copy).unwrap(), bytes);
3184
3185        let page = page_size().unwrap();
3186        let mut expect = vec![0u8; page];
3187        expect[..FIELD_BYTES].copy_from_slice(&header_fields(&header, page as u64));
3188        for value in positions {
3189            expect.extend_from_slice(&value.to_le_bytes());
3190        }
3191        for value in velocities {
3192            expect.extend_from_slice(&value.to_le_bytes());
3193        }
3194        for value in masses {
3195            expect.extend_from_slice(&value.to_le_bytes());
3196        }
3197        for value in cell {
3198            expect.extend_from_slice(&value.to_le_bytes());
3199        }
3200        for value in ids {
3201            expect.extend_from_slice(&value.to_le_bytes());
3202        }
3203        expect.extend_from_slice(&fixed);
3204        assert_eq!(bytes, expect);
3205
3206        let mapped = map_file(&path, 1).unwrap();
3207        assert_eq!(mapped.positions_f64().unwrap(), &positions);
3208        assert_eq!(mapped.velocities_f64().unwrap(), &velocities);
3209        assert_eq!(mapped.masses_f64().unwrap().unwrap(), &masses);
3210        assert_eq!(mapped.cell_f64().unwrap().unwrap(), &cell);
3211        assert_eq!(mapped.atom_ids().unwrap().unwrap(), &ids);
3212        assert_eq!(mapped.fixed_masks().unwrap().unwrap(), &fixed);
3213
3214        let bare = dir.path().join("positions.conbin");
3215        write_f64_columns(&bare, 1, 1, &[9.0, 8.0, 7.0], None, None, None, None, None).unwrap();
3216        let bare_bytes = std::fs::read(&bare).unwrap();
3217        assert_eq!(bare_bytes.len(), page + 24);
3218        assert!(bare_bytes[FIELD_BYTES..page].iter().all(|byte| *byte == 0));
3219        let mut coords = Vec::new();
3220        coords.extend_from_slice(&9.0f64.to_le_bytes());
3221        coords.extend_from_slice(&8.0f64.to_le_bytes());
3222        coords.extend_from_slice(&7.0f64.to_le_bytes());
3223        assert_eq!(&bare_bytes[page..], coords.as_slice());
3224    }
3225
3226    #[test]
3227    fn write_from_con_is_byte_identical() {
3228        let dir = tempfile::tempdir().unwrap();
3229        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
3230        let first = dir.path().join("a.conbin");
3231        let second = dir.path().join("b.conbin");
3232        let header = write_from_con(&src, &first, false).unwrap();
3233        write_from_con(&src, &second, false).unwrap();
3234        let bytes = std::fs::read(&first).unwrap();
3235        assert_eq!(std::fs::read(&second).unwrap(), bytes);
3236        let page = page_size().unwrap();
3237        assert!(bytes.len() > page);
3238        assert_eq!(&bytes[..8], MAGIC);
3239        assert!(bytes[FIELD_BYTES..page].iter().all(|byte| *byte == 0));
3240        let (_again, positions, velocities) = read_owned_f64(&first, 1).unwrap();
3241        assert_eq!(positions.len(), header.position_len().unwrap());
3242        assert_eq!(velocities.len(), positions.len());
3243        let mapped = map_file(&first, 1).unwrap();
3244        assert_eq!(mapped.positions_f64().unwrap(), positions.as_slice());
3245        assert_eq!(mapped.velocities_f64().unwrap(), velocities.as_slice());
3246    }
3247
3248    #[test]
3249    fn every_prefetch_reads_the_same_columns() {
3250        let dir = tempfile::tempdir().unwrap();
3251        let path = dir.path().join("wide.conbin");
3252        write_known(&path, 2, 64);
3253        let span = map_file_with(&path, 2, Prefetch::Span).unwrap();
3254        let expect_pos = span.positions_f64().unwrap().to_vec();
3255        let expect_vel = span.velocities_f64().unwrap().to_vec();
3256        assert_eq!(expect_pos.len(), 2 * 64 * 3);
3257        for mode in [
3258            Prefetch::ChunkPopulate,
3259            Prefetch::ChunkWillneed,
3260            Prefetch::Hybrid,
3261        ] {
3262            let mapped = map_file_with(&path, 2, mode).unwrap();
3263            assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
3264            assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
3265        }
3266        let expect = expect_pos.iter().sum::<f64>() + expect_vel.iter().sum::<f64>();
3267        assert_eq!(sum_split_streams(&path, 2).unwrap(), expect);
3268        assert_eq!(sum_mapped(&path, 2).unwrap(), expect);
3269    }
3270
3271    #[test]
3272    fn a_rename_publish_is_not_read_through_the_previous_mapping() {
3273        let dir = tempfile::tempdir().unwrap();
3274        let path = dir.path().join("republish.conbin");
3275        write_uniform(&path, 1, 4, 1).unwrap();
3276        let first = map_file(&path, 1).unwrap();
3277        let first_pos = first.positions_f64().unwrap().to_vec();
3278        write_uniform(&path, 1, 4, 99).unwrap();
3279        let second = map_file(&path, 1).unwrap();
3280        let second_pos = second.positions_f64().unwrap().to_vec();
3281        assert_ne!(first_pos, second_pos);
3282        assert_eq!(first.positions_f64().unwrap(), first_pos.as_slice());
3283        let (_header, owned, _velocities) = read_owned_f64(&path, 1).unwrap();
3284        assert_eq!(owned, second_pos);
3285    }
3286
3287    #[cfg(target_os = "linux")]
3288    #[test]
3289    fn worker_span_shares_the_queue() {
3290        let limits = QueueLimits {
3291            page: 4096,
3292            logical_block: 512,
3293            max_request: 1280 * 1024,
3294            nr_requests: 256,
3295            read_ahead: 128 * 1024,
3296            nr_hw_queues: 1,
3297            rotational: true,
3298        };
3299        assert_eq!(limits.worker_span(8), 32 * 1280 * 1024);
3300        assert_eq!(limits.worker_span(1), 256 * 1280 * 1024);
3301        // /dev/shm is tmpfs, so it has no block queue. The sum must still run.
3302        let dir = std::path::PathBuf::from(format!("/dev/shm/conbin-sum-{}", std::process::id()));
3303        let _ = std::fs::remove_dir_all(&dir);
3304        std::fs::create_dir_all(&dir).unwrap();
3305        let path = dir.join("known.conbin");
3306        write_known(&path, 4, 8);
3307        let mapped = map_file(&path, 1).unwrap();
3308        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
3309            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
3310        let got = sum_mapped(&path, 2).unwrap();
3311        let got_split = sum_split_streams(&path, 2).unwrap();
3312        assert_eq!(got, expect, "parallel sum {got} serial sum {expect}");
3313        assert_eq!(
3314            got_split, expect,
3315            "split sum {got_split} serial sum {expect}"
3316        );
3317        let _ = std::fs::remove_dir_all(&dir);
3318        let short = QueueLimits {
3319            nr_requests: 2,
3320            read_ahead: 4096,
3321            ..limits
3322        };
3323        assert_eq!(short.worker_span(8), 1280 * 1024);
3324        let shm = std::path::PathBuf::from(format!("/dev/shm/conbin-queue-{}", std::process::id()));
3325        let _ = std::fs::remove_dir_all(&shm);
3326        std::fs::create_dir_all(&shm).unwrap();
3327        let qpath = shm.join("known.conbin");
3328        write_known(&qpath, 1, 1);
3329        let got = QueueLimits::of(&qpath).unwrap();
3330        assert!(got.page.is_power_of_two());
3331        assert_eq!(got.max_request, got.page);
3332        assert_eq!(got.nr_requests, 1);
3333        assert!(!got.rotational);
3334        let _ = std::fs::remove_dir_all(&shm);
3335    }
3336
3337    #[test]
3338    fn mapped_runs_match_the_pread_fill() {
3339        let _scratch = tempfile::tempdir().unwrap();
3340        let dir = _scratch.path();
3341        let path = dir.join("known.conbin");
3342        write_known(&path, 4, 3);
3343        let mapped = map_file(&path, 2).unwrap();
3344        let pos = mapped.positions_f64().unwrap();
3345        let vel = mapped.velocities_f64().unwrap();
3346        assert_eq!(pos.len(), 4 * 3 * 3);
3347        assert_eq!(pos[0], 0.0);
3348        assert_eq!(pos[1], 0.25);
3349        assert_eq!(vel[1], -0.5);
3350        let mut got_pos = vec![0.0; pos.len()];
3351        let mut got_vel = vec![0.0; vel.len()];
3352        read_into_threads(&path, &mut got_pos, Some(&mut got_vel), 2).unwrap();
3353        assert_eq!(got_pos, pos);
3354        assert_eq!(got_vel, vel);
3355        let _ = std::fs::remove_dir_all(dir);
3356    }
3357
3358    struct HookGuard {
3359        slot: &'static std::thread::LocalKey<std::cell::Cell<bool>>,
3360    }
3361
3362    impl HookGuard {
3363        fn arm(slot: &'static std::thread::LocalKey<std::cell::Cell<bool>>) -> Self {
3364            slot.with(|flag| flag.set(true));
3365            Self { slot }
3366        }
3367    }
3368
3369    impl Drop for HookGuard {
3370        fn drop(&mut self) {
3371            self.slot.with(|flag| flag.set(false));
3372        }
3373    }
3374
3375    #[test]
3376    fn populate_failure_still_reads_the_same_values() {
3377        let _scratch = tempfile::tempdir().unwrap();
3378        let dir = _scratch.path();
3379        let path = dir.join("known.conbin");
3380        write_known(&path, 4, 3);
3381        let plain = map_file(&path, 2).unwrap();
3382        let expect_pos = plain.positions_f64().unwrap().to_vec();
3383        let expect_vel = plain.velocities_f64().unwrap().to_vec();
3384        drop(plain);
3385        let _guard = HookGuard::arm(&POPULATE_FAILS);
3386        let mapped = map_file(&path, 2).unwrap();
3387        assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
3388        assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
3389        let mut got_pos = vec![0.0; expect_pos.len()];
3390        let mut got_vel = vec![0.0; expect_vel.len()];
3391        read_into_threads(&path, &mut got_pos, Some(&mut got_vel), 2).unwrap();
3392        assert_eq!(got_pos, expect_pos);
3393        assert_eq!(got_vel, expect_vel);
3394        let _ = std::fs::remove_dir_all(dir);
3395    }
3396
3397    #[test]
3398    fn mmap_failure_still_reads_the_same_values() {
3399        let _scratch = tempfile::tempdir().unwrap();
3400        let dir = _scratch.path();
3401        let path = dir.join("known.conbin");
3402        write_known(&path, 4, 3);
3403        let plain = map_file(&path, 1).unwrap();
3404        let expect_pos = plain.positions_f64().unwrap().to_vec();
3405        let expect_vel = plain.velocities_f64().unwrap().to_vec();
3406        drop(plain);
3407        let _guard = HookGuard::arm(&MAP_FAILS);
3408        let mapped = map_file(&path, 1).unwrap();
3409        assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
3410        assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
3411        let _ = std::fs::remove_dir_all(dir);
3412    }
3413
3414    #[test]
3415    fn writer_stores_one_known_value_little_endian() {
3416        let _scratch = tempfile::tempdir().unwrap();
3417        let dir = _scratch.path();
3418        let path = dir.join("one.conbin");
3419        // Second position is 0.25. Its little-endian bytes are fixed.
3420        write_known(&path, 1, 1);
3421        let known = 0.25f64;
3422        let bytes = std::fs::read(&path).unwrap();
3423        let at = page_size().unwrap() + std::mem::size_of::<f64>();
3424        assert_eq!(&bytes[at..at + 8], known.to_le_bytes().as_slice());
3425        let mapped = map_file(&path, 1).unwrap();
3426        assert_eq!(mapped.positions_f64().unwrap()[1], known);
3427        let mut got = vec![0.0; mapped.header.position_len().unwrap()];
3428        let mut vel = vec![0.0; got.len()];
3429        read_into_threads(&path, &mut got, Some(&mut vel), 1).unwrap();
3430        assert_eq!(got[1], known);
3431        let _ = std::fs::remove_dir_all(dir);
3432    }
3433
3434    #[test]
3435    fn write_from_con_round_trips_text() {
3436        let _scratch = tempfile::tempdir().unwrap();
3437        let dir = _scratch.path();
3438        let con = dir.join("two.con");
3439        std::fs::write(
3440            &con,
3441            include_str!("../resources/test/tiny_cuh2.con").repeat(2),
3442        )
3443        .unwrap();
3444        let bin = dir.join("two.conbin");
3445        let header = write_from_con(&con, &bin, false).unwrap();
3446        assert_eq!(header.n_frames, 2);
3447        assert_eq!(header.n_atoms, 4);
3448        let mapped = map_file(&bin, 1).unwrap();
3449        let pos = mapped.positions_f64().unwrap();
3450        assert_eq!(pos.len(), 2 * 4 * 3);
3451        assert!(pos[0].is_finite());
3452        assert_eq!(mapped.header.version, 2);
3453        assert!(mapped.header.masses && mapped.header.cell && mapped.header.fixed);
3454        assert_eq!(mapped.masses_f64().unwrap().unwrap().len(), 2 * 4);
3455        assert_eq!(mapped.cell_f64().unwrap().unwrap().len(), 2 * 6);
3456        assert_eq!(mapped.fixed_masks().unwrap().unwrap().len(), 2 * 4);
3457        assert_eq!(mapped.atom_ids().unwrap().unwrap().len(), 2 * 4);
3458        let _ = std::fs::remove_dir_all(dir);
3459    }
3460
3461    #[test]
3462    fn a_store_copies_the_page_and_leaves_the_file() {
3463        let _scratch = tempfile::tempdir().unwrap();
3464        let dir = _scratch.path();
3465        let path = dir.join("known.conbin");
3466        write_known(&path, 2, 4);
3467        let before = std::fs::read(&path).unwrap();
3468        let mut mapped = map_file(&path, 1).unwrap();
3469        {
3470            let pos = mapped.positions_f64_mut().unwrap();
3471            let original = pos[0];
3472            pos[0] = original + 1.0;
3473            assert_eq!(pos[0], original + 1.0);
3474        }
3475        let after = std::fs::read(&path).unwrap();
3476        assert_eq!(before, after);
3477        let reread = map_file(&path, 1).unwrap();
3478        assert_eq!(reread.positions_f64().unwrap()[0], 0.0);
3479        let _ = std::fs::remove_dir_all(dir);
3480    }
3481
3482    #[test]
3483    fn a_4k_offset_opens_on_a_16k_or_64k_host() {
3484        // The stored offset is 4096, and the file is shorter than a 16 KiB
3485        // or 64 KiB page. The reader keeps 4096. It does not replace that
3486        // offset with the host page.
3487        let header = ConBinHeader::version1(1, 1, false, true);
3488        let mut bytes = header_fields(&header, 4096).to_vec();
3489        bytes.resize(4096 + 48, 0);
3490        bytes[4096..4096 + 8].copy_from_slice(&1.25f64.to_le_bytes());
3491        bytes[4096 + 24..4096 + 32].copy_from_slice(&(-2.5f64).to_le_bytes());
3492        assert!(bytes.len() < 16 * 1024);
3493        assert!(bytes.len() < 64 * 1024);
3494        let off = checked_payload_offset(4096, bytes.len()).unwrap();
3495        assert_eq!(off, 4096);
3496        assert_ne!(off, 16 * 1024);
3497        assert_ne!(off, 64 * 1024);
3498        let _scratch = tempfile::tempdir().unwrap();
3499        let dir = _scratch.path();
3500        let path = dir.join("known.conbin");
3501        std::fs::write(&path, &bytes).unwrap();
3502        let mapped = map_file(&path, 1).unwrap();
3503        assert_eq!(mapped.payload_off, 4096);
3504        assert_eq!(mapped.positions_f64().unwrap()[0], 1.25);
3505        assert_eq!(mapped.velocities_f64().unwrap()[0], -2.5);
3506        let _ = std::fs::remove_dir_all(dir);
3507    }
3508
3509    fn write_typed(path: &Path, binary32: bool, velocities: bool) {
3510        let header = ConBinHeader::version1(1, 1, binary32, velocities);
3511        let mut bytes = header_fields(&header, 64).to_vec();
3512        bytes.resize(64 + 48, 0);
3513        std::fs::write(path, bytes).unwrap();
3514    }
3515
3516    #[test]
3517    fn sum_mapped_rejects_binary32_and_a_missing_velocity_run() {
3518        let _scratch = tempfile::tempdir().unwrap();
3519        let dir = _scratch.path();
3520        let binary32 = dir.join("f32.conbin");
3521        write_typed(&binary32, true, true);
3522        let err = sum_mapped(&binary32, 1).unwrap_err();
3523        assert!(err.to_string().contains("binary32"), "{err}");
3524        let bare = dir.join("nov.conbin");
3525        write_typed(&bare, false, false);
3526        let err = sum_mapped(&bare, 1).unwrap_err();
3527        assert!(err.to_string().contains("no velocity"), "{err}");
3528        let err = read_owned_f64(&bare, 1).unwrap_err();
3529        assert!(err.to_string().contains("no velocity"), "{err}");
3530        let known = dir.join("known.conbin");
3531        write_known(&known, 1, 2);
3532        let (_header, pos, vel) = read_owned_f64(&known, 1).unwrap();
3533        let mapped = map_file(&known, 1).unwrap();
3534        assert_eq!(pos.as_slice(), mapped.positions_f64().unwrap());
3535        assert_eq!(vel.as_slice(), mapped.velocities_f64().unwrap());
3536        let _ = std::fs::remove_dir_all(dir);
3537    }
3538
3539    /// A real disk for the readahead check. `POSIX_FADV_DONTNEED` does not
3540    /// drop tmpfs pages, so a tmpfs directory cannot host that test.
3541    #[cfg(target_os = "linux")]
3542    fn disk_dir() -> Option<tempfile::TempDir> {
3543        for rel in ["target", "build"] {
3544            let base = Path::new(rel);
3545            if std::fs::create_dir_all(base).is_err() || dir_is_tmpfs(base) {
3546                continue;
3547            }
3548            if let Ok(dir) = tempfile::tempdir_in(base) {
3549                return Some(dir);
3550            }
3551        }
3552        None
3553    }
3554
3555    #[cfg(target_os = "linux")]
3556    fn dir_is_tmpfs(path: &Path) -> bool {
3557        let text = path.to_string_lossy();
3558        let Ok(c) = std::ffi::CString::new(text.as_bytes()) else {
3559            return false;
3560        };
3561        let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
3562        let rc = unsafe { libc::statfs(c.as_ptr(), &mut stat) };
3563        // include/uapi/linux/magic.h TMPFS_MAGIC
3564        rc == 0 && stat.f_type == 0x01021994
3565    }
3566
3567    #[cfg(target_os = "linux")]
3568    #[test]
3569    fn a_cold_multi_megabyte_file_uses_the_readahead_stream() {
3570        let Some(tmp) = disk_dir() else {
3571            eprintln!("skip: target and build are tmpfs, so the readahead check cannot drop pages");
3572            return;
3573        };
3574        let dir = tmp.path();
3575        let path = dir.join("cold.conbin");
3576        // Larger than the kernel readahead window, so `MADV_SEQUENTIAL`
3577        // cannot make every page resident before the stream starts.
3578        write_known(&path, 8, 65536);
3579        let file = File::open(&path).unwrap();
3580        file.sync_all().unwrap();
3581        drop(file);
3582        let file = File::open(&path).unwrap();
3583        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
3584        assert_eq!(rc, 0);
3585        drop(file);
3586        let got = sum_mapped(&path, 2).unwrap();
3587        let file = File::open(&path).unwrap();
3588        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
3589        assert_eq!(rc, 0);
3590        drop(file);
3591        let split = sum_split_streams(&path, 2).unwrap();
3592        let mapped = map_file(&path, 1).unwrap();
3593        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
3594            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
3595        assert_eq!(got, expect);
3596        assert_eq!(split, expect);
3597    }
3598
3599    #[cfg(target_os = "linux")]
3600    #[test]
3601    fn sum_mapped_streams_when_pages_are_not_resident() {
3602        let Some(tmp) = disk_dir() else {
3603            eprintln!("skip: target and build are tmpfs, so the readahead check cannot drop pages");
3604            return;
3605        };
3606        let dir = tmp.path();
3607        let path = dir.join("known.conbin");
3608        write_known(&path, 2, 32);
3609        let file = File::open(&path).unwrap();
3610        file.sync_all().unwrap();
3611        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
3612        assert_eq!(rc, 0);
3613        let len = file.metadata().unwrap().len() as usize;
3614        let ptr = unsafe {
3615            libc::mmap(
3616                std::ptr::null_mut(),
3617                len,
3618                libc::PROT_READ,
3619                libc::MAP_PRIVATE,
3620                file.as_raw_fd(),
3621                0,
3622            )
3623        };
3624        assert_ne!(ptr, libc::MAP_FAILED);
3625        let page = page_size().unwrap();
3626        let pages = len.div_ceil(page);
3627        let mut vec = vec![0u8; pages];
3628        let rc = unsafe { libc::mincore(ptr, len, vec.as_mut_ptr()) };
3629        assert_eq!(rc, 0);
3630        assert!(
3631            vec.iter().any(|byte| byte & 1 == 0),
3632            "every page stayed resident"
3633        );
3634        unsafe { libc::munmap(ptr, len) };
3635        let got = sum_mapped(&path, 2).unwrap();
3636        let mapped = map_file(&path, 1).unwrap();
3637        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
3638            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
3639        assert_eq!(got, expect, "{got} {expect}");
3640        let _ = std::fs::remove_dir_all(dir);
3641    }
3642
3643    /// Fills both columns with `pread` into spare capacity.
3644    /// Miri runs this with `-Zmiri-disable-isolation`.
3645    /// Miri does not model file-backed mmap, `mincore`, `readahead`
3646    /// or `MADV_POPULATE_READ`.
3647    #[cfg(unix)]
3648    #[test]
3649    fn read_owned_f64_fills_spare_capacity_by_pread() {
3650        let dir = tempfile::tempdir().unwrap();
3651        let path = dir.path().join("known.conbin");
3652        write_known(&path, 2, 8);
3653        for threads in [1usize, 2] {
3654            let (header, pos, vel) = read_owned_f64(&path, threads).unwrap();
3655            let n = header.position_len().unwrap();
3656            assert_eq!(pos.len(), n);
3657            assert_eq!(vel.len(), n);
3658            let mut raw = Vec::new();
3659            std::io::Read::read_to_end(&mut File::open(&path).unwrap(), &mut raw).unwrap();
3660            let off = raw.len() - 2 * n * 8;
3661            let want: Vec<f64> = raw[off..]
3662                .as_chunks::<8>()
3663                .0
3664                .iter()
3665                .map(|chunk| f64::from_le_bytes(*chunk))
3666                .collect();
3667            assert_eq!(pos.as_slice(), &want[..n]);
3668            assert_eq!(vel.as_slice(), &want[n..]);
3669        }
3670    }
3671
3672    #[cfg(target_os = "linux")]
3673    #[test]
3674    fn populate_followup_touches_only_after_einval() {
3675        assert!(populate_followup(libc::EINVAL).is_ok());
3676        for code in [libc::EFAULT, libc::EIO, libc::EHWPOISON, libc::ENOMEM] {
3677            assert_eq!(populate_followup(code).unwrap_err(), code);
3678        }
3679    }
3680
3681    #[cfg(target_os = "linux")]
3682    #[test]
3683    fn wait_resident_rejects_an_unaligned_address() {
3684        let page = page_size().unwrap();
3685        let ptr = unsafe {
3686            libc::mmap(
3687                std::ptr::null_mut(),
3688                page,
3689                libc::PROT_READ | libc::PROT_WRITE,
3690                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
3691                -1,
3692                0,
3693            )
3694        };
3695        assert_ne!(ptr, libc::MAP_FAILED);
3696        let err = wait_resident(ptr as usize + 1, 0, 1, page).unwrap_err();
3697        assert!(err.contains("page-aligned"), "{err}");
3698        unsafe { libc::munmap(ptr, page) };
3699    }
3700
3701    #[cfg(target_os = "linux")]
3702    #[test]
3703    fn wait_resident_returns_an_unmapped_populate_error() {
3704        let page = page_size().unwrap();
3705        // The hole sits between two mappings this test still owns, so a
3706        // parallel test's mmap is unlikely to land on it. A hit is retried:
3707        // the address is only unmapped until something else claims it.
3708        for _ in 0..64 {
3709            let ptr = unsafe {
3710                libc::mmap(
3711                    std::ptr::null_mut(),
3712                    page * 3,
3713                    libc::PROT_NONE,
3714                    libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
3715                    -1,
3716                    0,
3717                )
3718            };
3719            assert_ne!(ptr, libc::MAP_FAILED);
3720            let hole = unsafe { (ptr as *mut u8).add(page) as *mut libc::c_void };
3721            unsafe { libc::munmap(hole, page) };
3722            let result = wait_resident(hole as usize, 0, page, page);
3723            unsafe { libc::munmap(ptr, page) };
3724            unsafe { libc::munmap((ptr as *mut u8).add(page * 2) as *mut libc::c_void, page) };
3725            if let Err(err) = result {
3726                assert!(err.contains("os error"), "{err}");
3727                return;
3728            }
3729        }
3730        panic!("madvise on an unmapped page returned success");
3731    }
3732}