//! Reads bulletformat positions straight from zstd-compressed files (linrock's //! `*.bullet.bin.zst`), so the data never has to be unpacked to disk: training //! needs ~30 MB/s of compressed input, which even an HDD gives easily. //! //! Files are read one after the other and the list repeats forever, like bullet's //! `DirectSequentialDataLoader`; each file must already be shuffled. use std::{ fs::File, io::{BufReader, Read}, }; use bullet_lib::game::formats::bulletformat::ChessBoard; use bullet_trainer::reader::DataReader; #[derive(Clone)] pub struct ZstdBulletReader { paths: Vec, } impl ZstdBulletReader { pub fn new(paths: &[&str]) -> Self { for path in paths { assert!(std::path::Path::new(path).exists(), "data file not found: {path}"); } Self { paths: paths.iter().map(|p| p.to_string()).collect() } } } /// Reads until `buf` is full or the stream ends; returns the bytes read. fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> usize { let mut filled = 0; while filled < buf.len() { match reader.read(&mut buf[filled..]) { Ok(0) => break, Ok(n) => filled += n, Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} Err(e) => panic!("reading training data: {e}"), } } filled } impl DataReader for ZstdBulletReader { fn read_chunks bool>(&self, mut skip: usize, mut f: F) { const SIZE: usize = size_of::(); const CAP: usize = (64 << 20) / SIZE; let mut buf = vec![ChessBoard::default(); CAP]; loop { for path in &self.paths { let file = BufReader::with_capacity(4 << 20, File::open(path).unwrap()); let mut decoder = zstd::stream::read::Decoder::with_buffer(file).unwrap(); loop { // ChessBoard is plain bytes (bulletformat's 32-byte record). let bytes = unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr().cast::(), CAP * SIZE) }; let n = read_full(&mut decoder, bytes); if n == 0 { break; } assert_eq!(n % SIZE, 0, "{path} is not a whole number of positions"); let mut chunk = &buf[..n / SIZE]; if skip > 0 { let s = skip.min(chunk.len()); skip -= s; chunk = &chunk[s..]; } if !chunk.is_empty() && f(chunk) { return; } } } } } }