Skip to main content

zu_encoding/
alp.rs

1//! ALP for doubles (encoding id 6), the Afroozeh and Boncz adaptive
2//! lossless floating-point scheme: a double that is really a decimal,
3//! like a price or a coordinate, becomes `round(d * 10^e / 10^f)`, an
4//! integer that frame-of-reference packs to a fraction of eight bytes.
5//! Values the transform cannot reproduce bit-exactly ride as patched
6//! exceptions, so NaN, infinities, negative zero and genuine
7//! full-mantissa doubles all survive.
8//!
9//! The exponent pair is chosen on a sample: every legal `(e, f)` combo
10//! is scored by the packed width of the digits it produces plus the
11//! exceptions it fails on, and the smallest estimate wins. Decode is
12//! two multiplies per value after the digit stream unpacks, which is
13//! what keeps it on the 1 GB/s floor. Decode streams the digit chunks
14//! straight into the output, so scratch stays one MiniBlock chunk of
15//! 1024 values no matter how large the container is.
16//!
17//! Layout: `count: u32 LE`, `e: u8`, `f: u8`, `exc_count: u32 LE`,
18//! `positions_len: u32 LE`, positions container, exception bit patterns
19//! (8 bytes LE each), then the zigzagged digits container.
20
21use zu_common::{Result, ZuError};
22
23use crate::for_bitpack;
24
25/// 10^0 through 10^18, the largest power exact in an f64 kept small
26/// enough that digit magnitudes stay far from the 2^53 integer edge.
27const MAX_EXPONENT: usize = 18;
28
29fn pow10() -> [f64; MAX_EXPONENT + 1] {
30    let mut p = [1.0; MAX_EXPONENT + 1];
31    let mut i = 1;
32    while i <= MAX_EXPONENT {
33        p[i] = p[i - 1] * 10.0;
34        i += 1;
35    }
36    p
37}
38
39fn inv_pow10() -> [f64; MAX_EXPONENT + 1] {
40    let mut p = [1.0; MAX_EXPONENT + 1];
41    let mut i = 1;
42    while i <= MAX_EXPONENT {
43        p[i] = 10.0_f64.powi(-(i as i32));
44        i += 1;
45    }
46    p
47}
48
49/// Digits stay well inside the exactly-representable integer range so
50/// the verification multiply cannot lose bits to rounding.
51const MAX_DIGITS: f64 = (1u64 << 51) as f64;
52
53#[inline]
54fn zigzag(v: i64) -> u64 {
55    ((v << 1) ^ (v >> 63)) as u64
56}
57
58#[inline]
59fn unzigzag(v: u64) -> i64 {
60    ((v >> 1) as i64) ^ -((v & 1) as i64)
61}
62
63/// The transform for one value under `(e, f)`: the digits if the value
64/// decodes back bit-exactly, otherwise None.
65#[inline]
66fn digits_for(d: f64, e: usize, f: usize, pow: &[f64], inv: &[f64]) -> Option<i64> {
67    let scaled = d * pow[e] * inv[f];
68    if !(-MAX_DIGITS..=MAX_DIGITS).contains(&scaled) {
69        return None;
70    }
71    let digits = scaled.round() as i64;
72    let decoded = (digits as f64) * pow[f] * inv[e];
73    (decoded.to_bits() == d.to_bits()).then_some(digits)
74}
75
76/// Scores every `(e, f)` pair on an evenly spaced sample and returns
77/// the winner: estimated packed bits per value plus the exception tax.
78fn choose_exponents(values: &[f64], pow: &[f64], inv: &[f64]) -> (usize, usize) {
79    let step = (values.len() / 1024).max(1);
80    let sample: Vec<f64> = values.iter().step_by(step).copied().collect();
81    let mut best = (0usize, 0usize);
82    let mut best_score = u64::MAX;
83    for e in 0..=MAX_EXPONENT {
84        for f in 0..=e {
85            let mut lo = i64::MAX;
86            let mut hi = i64::MIN;
87            let mut exceptions = 0u64;
88            for &d in &sample {
89                match digits_for(d, e, f, pow, inv) {
90                    Some(digits) => {
91                        lo = lo.min(digits);
92                        hi = hi.max(digits);
93                    }
94                    None => exceptions += 1,
95                }
96            }
97            let width = if lo > hi {
98                64
99            } else {
100                u64::from(crate::bits_needed((hi as i128 - lo as i128) as u64))
101            };
102            let score = sample.len() as u64 * width + exceptions * 96;
103            if score < best_score {
104                best_score = score;
105                best = (e, f);
106            }
107        }
108    }
109    best
110}
111
112/// Encodes `values` into `out`, returning the encoded byte length.
113pub fn encode(values: &[f64], out: &mut Vec<u8>) -> usize {
114    let start = out.len();
115    let pow = pow10();
116    let inv = inv_pow10();
117    let (e, f) = choose_exponents(values, &pow, &inv);
118    let mut digits = Vec::with_capacity(values.len());
119    let mut positions = Vec::new();
120    let mut patterns = Vec::new();
121    for (i, &d) in values.iter().enumerate() {
122        match digits_for(d, e, f, &pow, &inv) {
123            Some(dig) => digits.push(zigzag(dig)),
124            None => {
125                // Exceptions still occupy a slot in the digit stream so
126                // positions stay aligned; zero packs for free.
127                digits.push(0);
128                positions.push(i as u64);
129                patterns.push(d.to_bits());
130            }
131        }
132    }
133    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
134    out.push(e as u8);
135    out.push(f as u8);
136    out.extend_from_slice(&(positions.len() as u32).to_le_bytes());
137    let mut positions_buf = Vec::new();
138    for_bitpack::encode(&positions, &mut positions_buf);
139    out.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
140    out.extend_from_slice(&positions_buf);
141    for &p in &patterns {
142        out.extend_from_slice(&p.to_le_bytes());
143    }
144    for_bitpack::encode(&digits, out);
145    out.len() - start
146}
147
148/// Decodes an encoded buffer, appending at most `max_values` values to
149/// `out`. Every count is a claim checked against the caller ceiling and
150/// the streams, and a rejected payload leaves `out` untouched.
151pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<f64>) -> Result<()> {
152    let corrupt = |detail: &str| ZuError::Corrupt {
153        what: "alp",
154        detail: detail.to_string(),
155    };
156    let header = bytes.get(..14).ok_or_else(|| corrupt("truncated header"))?;
157    let count = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
158    let e = header[4] as usize;
159    let f = header[5] as usize;
160    let exc_count = u32::from_le_bytes(header[6..10].try_into().unwrap()) as usize;
161    let positions_len = u32::from_le_bytes(header[10..14].try_into().unwrap()) as usize;
162    if count > max_values {
163        return Err(corrupt("count above the caller ceiling"));
164    }
165    if e > MAX_EXPONENT || f > e {
166        return Err(corrupt("exponent pair outside the table"));
167    }
168    if exc_count > count {
169        return Err(corrupt("more exceptions than values"));
170    }
171    let positions_bytes = bytes
172        .get(14..14 + positions_len)
173        .ok_or_else(|| corrupt("truncated positions"))?;
174    let patterns_end = 14 + positions_len + exc_count * 8;
175    let patterns_bytes = bytes
176        .get(14 + positions_len..patterns_end)
177        .ok_or_else(|| corrupt("truncated exception patterns"))?;
178    let digits_bytes = bytes
179        .get(patterns_end..)
180        .ok_or_else(|| corrupt("truncated digits"))?;
181    let mut positions = Vec::new();
182    for_bitpack::decode(positions_bytes, exc_count, &mut positions)?;
183    if positions.len() != exc_count {
184        return Err(corrupt("position stream length mismatch"));
185    }
186    if positions.iter().any(|&p| p >= count as u64) {
187        return Err(corrupt("position past the value count"));
188    }
189    let pow = pow10();
190    let inv = inv_pow10();
191    let scale_f = pow[f];
192    let scale_e = inv[e];
193    let base = out.len();
194    let decoded = for_bitpack::decode_chunks(digits_bytes, count, |min, scratch, take| {
195        out.extend(
196            scratch[..take]
197                .iter()
198                .map(|&v| (unzigzag(min.wrapping_add(v)) as f64) * scale_f * scale_e),
199        );
200    });
201    match decoded {
202        Ok(n) if n == count => {}
203        Ok(_) => {
204            out.truncate(base);
205            return Err(corrupt("digit stream length mismatch"));
206        }
207        Err(e) => {
208            out.truncate(base);
209            return Err(e);
210        }
211    }
212    for (&pos, chunk) in positions.iter().zip(patterns_bytes.as_chunks::<8>().0) {
213        out[base + pos as usize] = f64::from_bits(u64::from_le_bytes(*chunk));
214    }
215    Ok(())
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    fn coords() -> Vec<f64> {
223        // Five-decimal-digit coordinates, the shape ALP is for. Seven
224        // digits over the full degree range packs to 33 bits and sits
225        // exactly at the 2x boundary; the bench on real check-ins is
226        // where that case is measured.
227        let mut rng = 0x9E3779B97F4A7C15u64;
228        (0..10_000)
229            .map(|_| {
230                rng ^= rng << 13;
231                rng ^= rng >> 7;
232                rng ^= rng << 17;
233                let hundred_micro = (rng % 36_000_000) as i64 - 9_000_000;
234                hundred_micro as f64 / 1e5
235            })
236            .collect()
237    }
238
239    #[test]
240    fn roundtrip_compresses_decimals() {
241        let values = coords();
242        let mut buf = Vec::new();
243        let len = encode(&values, &mut buf);
244        assert!(
245            len * 2 < values.len() * 8,
246            "seven-digit decimals should at least halve, got {len} from {}",
247            values.len() * 8
248        );
249        let mut out = Vec::new();
250        decode(&buf, values.len(), &mut out).unwrap();
251        assert_eq!(
252            values.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
253            out.iter().map(|v| v.to_bits()).collect::<Vec<_>>()
254        );
255    }
256
257    #[test]
258    fn roundtrip_hostile_values_ride_as_exceptions() {
259        let values = [
260            0.0,
261            -0.0,
262            f64::NAN,
263            f64::INFINITY,
264            f64::NEG_INFINITY,
265            f64::MIN_POSITIVE / 2.0,
266            std::f64::consts::PI,
267            1e300,
268            -273.15,
269            2.5,
270        ];
271        let mut buf = Vec::new();
272        encode(&values, &mut buf);
273        let mut out = Vec::new();
274        decode(&buf, values.len(), &mut out).unwrap();
275        assert_eq!(
276            values.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
277            out.iter().map(|v| v.to_bits()).collect::<Vec<_>>()
278        );
279    }
280
281    #[test]
282    fn roundtrip_edges() {
283        for values in [vec![], vec![42.5f64], vec![-0.001; 300]] {
284            let mut buf = Vec::new();
285            encode(&values, &mut buf);
286            let mut out = Vec::new();
287            decode(&buf, values.len(), &mut out).unwrap();
288            assert_eq!(
289                values.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
290                out.iter().map(|v| v.to_bits()).collect::<Vec<_>>()
291            );
292        }
293    }
294
295    #[test]
296    fn corrupt_and_hostile() {
297        let mut out = vec![9.0f64];
298        assert!(decode(&[1, 2, 3], 16, &mut out).is_err());
299        // A flood claim dies on the ceiling before anything materializes.
300        let mut buf = u32::MAX.to_le_bytes().to_vec();
301        buf.extend_from_slice(&[0; 10]);
302        assert!(decode(&buf, 1 << 20, &mut out).is_err());
303        // Exponent pairs outside the table are rejected.
304        for (e, f) in [(19u8, 0u8), (5, 6)] {
305            let mut buf = 1u32.to_le_bytes().to_vec();
306            buf.push(e);
307            buf.push(f);
308            buf.extend_from_slice(&0u32.to_le_bytes());
309            buf.extend_from_slice(&0u32.to_le_bytes());
310            assert!(decode(&buf, 16, &mut out).is_err());
311        }
312        // An exception position past the count is rejected.
313        let mut buf = 1u32.to_le_bytes().to_vec();
314        buf.extend_from_slice(&[0, 0]);
315        buf.extend_from_slice(&1u32.to_le_bytes());
316        let mut positions_buf = Vec::new();
317        for_bitpack::encode(&[5], &mut positions_buf);
318        buf.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
319        buf.extend_from_slice(&positions_buf);
320        buf.extend_from_slice(&7.5f64.to_bits().to_le_bytes());
321        for_bitpack::encode(&[0], &mut buf);
322        assert!(decode(&buf, 16, &mut out).is_err());
323        assert_eq!(out, [9.0], "a rejected payload must not touch out");
324    }
325}