Skip to main content

tparquet_core/
lib.rs

1//! The PCODEC Parquet compression codec: the page payload of `spec/FORMAT.md`.
2//!
3//! [`compress`] turns the bytes Parquet would compress into a payload; [`decompress`] turns a
4//! payload back into exactly those bytes. Decoding never needs the column type: the payload
5//! says how it was written. The type hint given to [`compress`] only affects the ratio.
6
7mod decimal;
8mod varint;
9
10use decimal::Float;
11use pco::ChunkConfig;
12use pco::FULL_BATCH_N;
13use pco::data_types::Number;
14use pco::standalone::{DecompressorItem, FileDecompressor, simple_compress};
15use std::fmt;
16
17/// `CompressionCodec` value of PCODEC in the Parquet footer.
18pub const CODEC_ID: i32 = 20547;
19/// Payload format version this crate writes and reads.
20pub const FORMAT_VERSION: u8 = 1;
21/// Footer key-value pair writers add to files with PCODEC columns.
22pub const KV_KEY: &str = "parquet.pcodec.version";
23/// Value of [`KV_KEY`].
24pub const KV_VALUE: &str = "1";
25/// pcodec compression level used when none is given.
26pub const DEFAULT_LEVEL: u8 = 8;
27/// Highest pcodec compression level.
28pub const MAX_LEVEL: u8 = 12;
29/// ZSTD level of the fallback mode.
30const ZSTD_LEVEL: i32 = 3;
31
32/// The Parquet physical types PCODEC models, with their Parquet `Type` values.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[repr(u8)]
35pub enum PhysicalType {
36    Int32 = 1,
37    Int64 = 2,
38    Float = 4,
39    Double = 5,
40}
41
42impl PhysicalType {
43    /// From a Parquet `Type` value; `None` for types PCODEC does not model.
44    pub fn from_parquet(t: i32) -> Option<Self> {
45        match t {
46            1 => Some(Self::Int32),
47            2 => Some(Self::Int64),
48            4 => Some(Self::Float),
49            5 => Some(Self::Double),
50            _ => None,
51        }
52    }
53
54    /// Bytes per value in Parquet `PLAIN` encoding.
55    pub fn width(self) -> usize {
56        match self {
57            Self::Int32 | Self::Float => 4,
58            Self::Int64 | Self::Double => 8,
59        }
60    }
61
62    fn from_dtype(b: u8) -> Result<Self, Error> {
63        Self::from_parquet(i32::from(b)).ok_or(Error::UnknownDtype(b))
64    }
65}
66
67/// How a payload was written (spec section 4).
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum Mode {
71    Raw = 0,
72    Pco = 1,
73    Decimal = 2,
74    Zstd = 3,
75}
76
77impl Mode {
78    fn from_byte(b: u8) -> Result<Self, Error> {
79        match b {
80            0 => Ok(Self::Raw),
81            1 => Ok(Self::Pco),
82            2 => Ok(Self::Decimal),
83            3 => Ok(Self::Zstd),
84            _ => Err(Error::UnknownMode(b)),
85        }
86    }
87}
88
89/// Encoder settings.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Options {
92    /// pcodec compression level, 0..=12.
93    pub level: u8,
94    /// The column's physical type; without it the encoder can only use ZSTD or RAW.
95    pub hint: Option<PhysicalType>,
96    /// Try DECIMAL for float columns.
97    pub decimal: bool,
98}
99
100impl Default for Options {
101    fn default() -> Self {
102        Self { level: DEFAULT_LEVEL, hint: None, decimal: true }
103    }
104}
105
106impl Options {
107    /// Default options for a column of type `t`.
108    pub fn with_hint(t: PhysicalType) -> Self {
109        Self { hint: Some(t), ..Self::default() }
110    }
111}
112
113/// Why a payload could not be decoded (or an option was refused).
114#[derive(Debug, Clone, PartialEq, Eq)]
115#[non_exhaustive]
116pub enum Error {
117    Truncated,
118    UnsupportedVersion(u8),
119    UnknownMode(u8),
120    UnknownDtype(u8),
121    BadExponent(u8),
122    BadException,
123    SizeMismatch {
124        expected: usize,
125        actual: usize,
126    },
127    NotMultipleOfWidth {
128        len: usize,
129        width: usize,
130    },
131    InvalidLevel(u8),
132    /// The expected size given to [`decompress`] cannot be allocated.
133    AllocationFailed(usize),
134    /// Bytes after the pcodec file, which must run to the end of the payload.
135    TrailingBytes(usize),
136    Pco(String),
137    Zstd(String),
138}
139
140impl fmt::Display for Error {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str("pcodec payload: ")?;
143        match self {
144            Self::Truncated => f.write_str("truncated"),
145            Self::UnsupportedVersion(v) => write!(f, "unsupported version {v}"),
146            Self::UnknownMode(m) => write!(f, "unknown mode {m}"),
147            Self::UnknownDtype(d) => write!(f, "unknown dtype {d}"),
148            Self::BadExponent(e) => write!(f, "exponent {e} above 18"),
149            Self::BadException => f.write_str("exception count or position out of range"),
150            Self::SizeMismatch { expected, actual } => write!(f, "decodes to {actual} bytes, expected {expected}"),
151            Self::NotMultipleOfWidth { len, width } => {
152                write!(f, "expected size {len} is not a multiple of the value width {width}")
153            }
154            Self::InvalidLevel(l) => write!(f, "compression level {l} above {MAX_LEVEL}"),
155            Self::AllocationFailed(n) => write!(f, "cannot allocate the expected size of {n} bytes"),
156            Self::TrailingBytes(n) => write!(f, "{n} bytes after the pcodec file"),
157            Self::Pco(e) => write!(f, "pcodec: {e}"),
158            Self::Zstd(e) => write!(f, "zstd: {e}"),
159        }
160    }
161}
162
163impl std::error::Error for Error {}
164
165// ---------------------------------------------------------------- encode
166
167/// Encodes `src` as a payload.
168pub fn compress(src: &[u8], opts: &Options) -> Result<Vec<u8>, Error> {
169    if opts.level > MAX_LEVEL {
170        return Err(Error::InvalidLevel(opts.level));
171    }
172    let raw = || [&[FORMAT_VERSION, Mode::Raw as u8][..], src].concat();
173    if src.is_empty() {
174        return Ok(raw());
175    }
176    let cfg = ChunkConfig::default().with_compression_level(usize::from(opts.level));
177    let best = match opts.hint.filter(|t| src.len().is_multiple_of(t.width())) {
178        Some(PhysicalType::Int32) => pco_payload(PhysicalType::Int32, &values(src, i32::from_le_bytes), &cfg)?,
179        Some(PhysicalType::Int64) => pco_payload(PhysicalType::Int64, &values(src, i64::from_le_bytes), &cfg)?,
180        Some(PhysicalType::Float) => float_payload(PhysicalType::Float, &values(src, f32::from_le_bytes), opts, &cfg)?,
181        Some(PhysicalType::Double) => {
182            float_payload(PhysicalType::Double, &values(src, f64::from_le_bytes), opts, &cfg)?
183        }
184        None => {
185            let mut p = vec![FORMAT_VERSION, Mode::Zstd as u8];
186            p.extend(zstd::bulk::compress(src, ZSTD_LEVEL).map_err(|e| Error::Zstd(e.to_string()))?);
187            p
188        }
189    };
190    Ok(if best.len() < src.len() + 2 { best } else { raw() })
191}
192
193fn values<T, const W: usize>(src: &[u8], f: fn([u8; W]) -> T) -> Vec<T> {
194    src.as_chunks::<W>().0.iter().map(|c| f(*c)).collect()
195}
196
197fn pco_bytes<T: Number>(v: &[T], cfg: &ChunkConfig) -> Result<Vec<u8>, Error> {
198    simple_compress(v, cfg).map_err(|e| Error::Pco(e.to_string()))
199}
200
201fn pco_payload<T: Number>(t: PhysicalType, v: &[T], cfg: &ChunkConfig) -> Result<Vec<u8>, Error> {
202    let mut p = vec![FORMAT_VERSION, Mode::Pco as u8, t as u8];
203    p.extend(pco_bytes(v, cfg)?);
204    Ok(p)
205}
206
207fn float_payload<F: Float + Plain>(
208    t: PhysicalType,
209    v: &[F],
210    opts: &Options,
211    cfg: &ChunkConfig,
212) -> Result<Vec<u8>, Error> {
213    let plain = pco_payload(t, v, cfg)?;
214    if !opts.decimal {
215        return Ok(plain);
216    }
217    let Some(e) = decimal::exponent(v) else { return Ok(plain) };
218    let Some((qs, exc)) = decimal::split(v, e) else { return Ok(plain) };
219    let mut p = vec![FORMAT_VERSION, Mode::Decimal as u8, t as u8, e];
220    varint::put(&mut p, exc.len() as u64);
221    let mut next = 0;
222    for &i in &exc {
223        varint::put(&mut p, (i - next) as u64);
224        next = i + 1;
225    }
226    for &i in &exc {
227        let at = p.len();
228        p.resize(at + size_of::<F>(), 0);
229        v[i].put(&mut p[at..]);
230    }
231    p.extend(pco_bytes(&qs, cfg)?);
232    Ok(if p.len() < plain.len() { p } else { plain })
233}
234
235/// pcodec numbers this crate writes as Parquet `PLAIN` bytes.
236trait Plain: Number {
237    /// writes the value's little-endian bytes into `out`, which is exactly its width
238    fn put(self, out: &mut [u8]);
239    /// appends the value's little-endian bytes to `out`
240    fn append(self, out: &mut Vec<u8>);
241}
242
243macro_rules! plain {
244    ($($t:ty),*) => {$(
245        impl Plain for $t {
246            fn put(self, out: &mut [u8]) {
247                out.copy_from_slice(&self.to_le_bytes());
248            }
249            fn append(self, out: &mut Vec<u8>) {
250                out.extend_from_slice(&self.to_le_bytes());
251            }
252        }
253    )*};
254}
255plain!(i32, i64, f32, f64);
256
257// ---------------------------------------------------------------- decode
258
259/// The mode of a payload, after checking its version.
260pub fn mode_of(payload: &[u8]) -> Result<Mode, Error> {
261    match payload {
262        [] | [_] => Err(Error::Truncated),
263        [v, ..] if *v != FORMAT_VERSION => Err(Error::UnsupportedVersion(*v)),
264        [_, m, ..] => Mode::from_byte(*m),
265    }
266}
267
268/// Decodes a payload that must produce exactly `expected_len` bytes.
269///
270/// `expected_len` is untrusted too (a page header): see [`decompress_append`].
271pub fn decompress(payload: &[u8], expected_len: usize) -> Result<Vec<u8>, Error> {
272    let mut out = Vec::new();
273    decompress_append(payload, &mut out, expected_len)?;
274    Ok(out)
275}
276
277/// Decodes a payload that must produce exactly `expected_len` bytes, appending them to `out`.
278/// On an error `out` is left as it was (its capacity may have grown).
279///
280/// `expected_len` is untrusted too (a page header): nothing proportional to it is allocated or
281/// written before the payload shows it can produce that many bytes. A RAW body must have that
282/// length, a ZSTD body must be long enough to hold that many bytes (each Zstandard block costs
283/// at least 4 bytes and decodes to at most 128 KiB), and PCO and DECIMAL output grows as the
284/// numbers are decoded. Memory that cannot be allocated is [`Error::AllocationFailed`].
285pub fn decompress_append(payload: &[u8], out: &mut Vec<u8>, expected_len: usize) -> Result<(), Error> {
286    let start = out.len();
287    let r = append(payload, &mut Tail { out, start, expected_len }, expected_len);
288    if r.is_err() {
289        out.truncate(start);
290    }
291    r
292}
293
294/// Decodes a payload into `dst`, which it must fill exactly.
295pub fn decompress_into(payload: &[u8], dst: &mut [u8]) -> Result<(), Error> {
296    let mode = mode_of(payload)?;
297    let body = &payload[2..];
298    match mode {
299        Mode::Raw => {
300            check(dst.len(), body.len())?;
301            dst.copy_from_slice(body);
302            Ok(())
303        }
304        Mode::Zstd => zstd_into(body, dst),
305        Mode::Pco | Mode::Decimal => numbers(mode, body, dst, dst.len()),
306    }
307}
308
309/// [`decompress_append`] into `out`, which [`decompress_append`] restores on an error
310fn append(payload: &[u8], out: &mut Tail<'_>, len: usize) -> Result<(), Error> {
311    let mode = mode_of(payload)?;
312    let body = &payload[2..];
313    match mode {
314        Mode::Raw => {
315            check(len, body.len())?;
316            out.reserve(len)?;
317            out.out.extend_from_slice(body);
318            Ok(())
319        }
320        Mode::Zstd => {
321            // RFC 8878 3.1.1.2: a block that decodes to anything is a 3 byte header and at
322            // least one byte, and decodes to at most 128 KiB
323            if len > (body.len() / 4).saturating_mul(ZSTD_BLOCK_MAX) {
324                return Err(Error::Truncated);
325            }
326            out.reserve(len)?;
327            let at = out.out.len();
328            out.out.resize(at + len, 0);
329            zstd_into(body, &mut out.out[at..])
330        }
331        Mode::Pco | Mode::Decimal => numbers(mode, body, out, len),
332    }
333}
334
335/// the most one Zstandard block decodes to (RFC 8878 3.1.1.2, `Block_Maximum_Size`)
336const ZSTD_BLOCK_MAX: usize = 128 << 10;
337
338/// The PCO and DECIMAL bodies (spec 4.2, 4.3), decoded into `len` bytes of `dst`.
339fn numbers<S: Sink + ?Sized>(mode: Mode, body: &[u8], dst: &mut S, len: usize) -> Result<(), Error> {
340    if mode == Mode::Pco {
341        let (&dtype, body) = body.split_first().ok_or(Error::Truncated)?;
342        return match PhysicalType::from_dtype(dtype)? {
343            PhysicalType::Int32 => pco_into::<i32, S>(body, dst, len),
344            PhysicalType::Int64 => pco_into::<i64, S>(body, dst, len),
345            PhysicalType::Float => pco_into::<f32, S>(body, dst, len),
346            PhysicalType::Double => pco_into::<f64, S>(body, dst, len),
347        };
348    }
349    let [dtype, e, ..] = *body else { return Err(Error::Truncated) };
350    let t = PhysicalType::from_dtype(dtype)?;
351    if e > decimal::MAX_EXPONENT {
352        return Err(Error::BadExponent(e));
353    }
354    let body = &body[2..];
355    match t {
356        PhysicalType::Float => decimal_into::<f32, S>(body, e, dst, len),
357        PhysicalType::Double => decimal_into::<f64, S>(body, e, dst, len),
358        PhysicalType::Int32 | PhysicalType::Int64 => Err(Error::UnknownDtype(dtype)),
359    }
360}
361
362/// Where decoded numbers go: the caller's slice ([`decompress_into`]), or the end of a `Vec`
363/// that grows as the numbers are decoded ([`decompress_append`]).
364trait Sink {
365    /// writes numbers `i..i + nums.len()`; they arrive in order, from 0, and never beyond the
366    /// expected size
367    fn put<T: Plain>(&mut self, i: usize, nums: impl ExactSizeIterator<Item = T>) -> Result<(), Error>;
368    /// the bytes written so far
369    fn written(&mut self) -> &mut [u8];
370}
371
372impl Sink for [u8] {
373    fn put<T: Plain>(&mut self, i: usize, nums: impl ExactSizeIterator<Item = T>) -> Result<(), Error> {
374        let width = size_of::<T>();
375        for (out, v) in self[i * width..].chunks_exact_mut(width).zip(nums) {
376            v.put(out);
377        }
378        Ok(())
379    }
380    fn written(&mut self) -> &mut [u8] {
381        self
382    }
383}
384
385/// the end of a `Vec`, from its length `start` when decoding started
386struct Tail<'a> {
387    out: &'a mut Vec<u8>,
388    start: usize,
389    expected_len: usize,
390}
391
392impl Tail<'_> {
393    fn reserve(&mut self, additional: usize) -> Result<(), Error> {
394        self.out.try_reserve(additional).map_err(|_| Error::AllocationFailed(self.expected_len))
395    }
396}
397
398impl Sink for Tail<'_> {
399    fn put<T: Plain>(&mut self, _: usize, nums: impl ExactSizeIterator<Item = T>) -> Result<(), Error> {
400        self.reserve(nums.len() * size_of::<T>())?;
401        for v in nums {
402            v.append(self.out);
403        }
404        Ok(())
405    }
406    fn written(&mut self) -> &mut [u8] {
407        &mut self.out[self.start..]
408    }
409}
410
411/// Zstandard frames into exactly `dst`, decoded in one pass straight into it: the frames'
412/// declared window sizes cost no memory, and output past `dst.len()` is never produced
413fn zstd_into(body: &[u8], dst: &mut [u8]) -> Result<(), Error> {
414    use zstd::zstd_safe::{self, zstd_sys::ZSTD_ErrorCode};
415    if body.is_empty() {
416        // no frame at all (spec 4.4: one frame or several)
417        return Err(Error::Truncated);
418    }
419    // zstd's error codes are the negated ZSTD_ErrorCode values (zstd_errors.h)
420    let too_small = (ZSTD_ErrorCode::ZSTD_error_dstSize_tooSmall as usize).wrapping_neg();
421    match zstd_safe::decompress(dst, body) {
422        Ok(n) => check(dst.len(), n),
423        // the frames hold more than the page: at least one byte more
424        Err(code) if code == too_small => Err(Error::SizeMismatch { expected: dst.len(), actual: dst.len() + 1 }),
425        Err(code) => Err(Error::Zstd(zstd_safe::get_error_name(code).to_string())),
426    }
427}
428
429fn check(expected: usize, actual: usize) -> Result<(), Error> {
430    if expected == actual { Ok(()) } else { Err(Error::SizeMismatch { expected, actual }) }
431}
432
433/// `len / width`, refusing a length that is not whole values
434fn count(len: usize, width: usize) -> Result<usize, Error> {
435    if len.is_multiple_of(width) { Ok(len / width) } else { Err(Error::NotMultipleOfWidth { len, width }) }
436}
437
438fn pco_error(e: pco::errors::PcoError) -> Error {
439    Error::Pco(e.to_string())
440}
441
442/// Decodes the pcodec file `src`, which must hold exactly `n` numbers and run to the end of
443/// `src`, one batch at a time:
444/// `put(i, batch)` receives numbers `i..i + batch.len()`. Nothing proportional to `n` or to
445/// what the chunk headers claim is allocated; size errors count `width` bytes per number.
446fn pco_batches<T: Number>(
447    src: &[u8],
448    n: usize,
449    width: usize,
450    mut put: impl FnMut(usize, &[T]) -> Result<(), Error>,
451) -> Result<(), Error> {
452    let (file, mut src) = FileDecompressor::new(src).map_err(pco_error)?;
453    let mut batch = [T::default(); FULL_BATCH_N];
454    let mut done = 0;
455    loop {
456        let mut chunk = match file.chunk_decompressor::<T, _>(src).map_err(pco_error)? {
457            DecompressorItem::Chunk(chunk) => chunk,
458            DecompressorItem::EndOfData([]) => break,
459            DecompressorItem::EndOfData(rest) => return Err(Error::TrailingBytes(rest.len())),
460        };
461        let end = done + chunk.n();
462        if end > n {
463            // more numbers than the page has room for, refused before they are decoded
464            return Err(Error::SizeMismatch { expected: n * width, actual: end * width });
465        }
466        loop {
467            let progress = chunk.read(&mut batch).map_err(pco_error)?;
468            put(done, &batch[..progress.n_processed])?;
469            done += progress.n_processed;
470            if progress.finished {
471                break;
472            }
473        }
474        src = chunk.into_src();
475    }
476    check(n * width, done * width)
477}
478
479fn pco_into<T: Plain, S: Sink + ?Sized>(src: &[u8], dst: &mut S, len: usize) -> Result<(), Error> {
480    let width = size_of::<T>();
481    let n = count(len, width)?;
482    pco_batches::<T>(src, n, width, |i, nums| dst.put(i, nums.iter().copied()))
483}
484
485fn decimal_into<F: Float + Plain, S: Sink + ?Sized>(
486    mut body: &[u8],
487    e: u8,
488    dst: &mut S,
489    len: usize,
490) -> Result<(), Error> {
491    let width = size_of::<F>();
492    let n = count(len, width)?;
493    let k = varint::get(&mut body)?;
494    if k > n as u64 {
495        return Err(Error::BadException);
496    }
497    // the positions are checked here and read again once the values are written, so that an
498    // exception count the payload does not back costs no allocation
499    let deltas = body;
500    let mut next: u64 = 0;
501    for _ in 0..k {
502        let p = next.checked_add(varint::get(&mut body)?).ok_or(Error::BadException)?;
503        if p >= n as u64 {
504            return Err(Error::BadException);
505        }
506        next = p + 1;
507    }
508    // k <= n, so this is at most len
509    let (exc, pco) = body.split_at_checked(k as usize * width).ok_or(Error::Truncated)?;
510    pco_batches::<i64>(pco, n, width, |i, qs| dst.put(i, qs.iter().map(|q| F::decode(*q, e))))?;
511    let dst = dst.written();
512    let (mut deltas, mut next) = (deltas, 0);
513    for bits in exc.chunks_exact(width) {
514        // checked above: each delta is a valid varint and every position is below n
515        let p = next + varint::get(&mut deltas)? as usize;
516        dst[p * width..(p + 1) * width].copy_from_slice(bits);
517        next = p + 1;
518    }
519    Ok(())
520}