fastmash 0.6.0

Fast command-line statistics on text data, compatible with GNU datamash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Software arithmetic for the `portable-binary80-v4` numerical contract.
//!
//! V4 retains V3 arithmetic. Its updated CLI collation can change the order
//! in which Groups consume the shared seeded random stream.
//!
//! The command uses this module for its remaining wider arithmetic. Its
//! checked interface is the numerical seam; the fixed-limb substrate and
//! certificate machine are internal.

#![forbid(unsafe_code)]
#![cfg_attr(
    not(test),
    expect(
        dead_code,
        reason = "independent primitive paths remain covered by numerical fixtures"
    )
)]

mod arena;
mod dyadic;
mod limb;
mod machine;
mod primitive;

use crate::numeric_contract::{Value80, ValueClass};
use arena::Arena;
use std::cmp::Ordering;

pub(crate) const PROFILE: &str = "portable-binary80-v4";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ValueAdmissionFailure {
    SignalingNan,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NumericFailure {
    UnsupportedDomain,
    Capacity,
    Allocation,
    Invariant,
    TableIdentity,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct ArithmeticValue(Value80);

impl From<ArithmeticValue> for Value80 {
    fn from(value: ArithmeticValue) -> Self {
        value.0
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Comparison {
    Less,
    Equal,
    Greater,
    Unordered,
}

impl TryFrom<Value80> for ArithmeticValue {
    type Error = ValueAdmissionFailure;

    fn try_from(value: Value80) -> Result<Self, Self::Error> {
        // Only the all-ones exponent encodes a NaN; every other value is admitted
        // without classification, the hot path for arithmetic results.
        if value.exponent() != 0x7fff {
            return Ok(Self(value));
        }
        if matches!(value.classify(), ValueClass::Nan { quiet: false, .. }) {
            Err(ValueAdmissionFailure::SignalingNan)
        } else {
            Ok(Self(value))
        }
    }
}

/// Restricted owner for exact square root without transcendental cache setup.
/// Retains the checked arena allocation and primitive cleanup rules.
pub(crate) struct SquareRoot {
    arena: Arena,
}

impl SquareRoot {
    pub fn new() -> Result<Self, NumericFailure> {
        Self::new_with(Arena::new)
    }

    fn new_with(allocate: fn() -> Result<Arena, NumericFailure>) -> Result<Self, NumericFailure> {
        Ok(Self { arena: allocate()? })
    }

    pub fn sqrt(&mut self, value: ArithmeticValue) -> Result<Value80, NumericFailure> {
        square_root(&mut self.arena, value)
    }
}

fn square_root(arena: &mut Arena, value: ArithmeticValue) -> Result<Value80, NumericFailure> {
    if let Some(value) = first_nan(value.0, None) {
        return Ok(value);
    }
    match value.0.classify() {
        ValueClass::Zero => Ok(value.0),
        ValueClass::Infinity if value.0.is_negative() => Arena::canonical_nan(),
        ValueClass::Infinity => Ok(value.0),
        ValueClass::Subnormal | ValueClass::Normal if value.0.is_negative() => {
            Arena::canonical_nan()
        }
        ValueClass::Subnormal | ValueClass::Normal => arena.sqrt_finite(value.0),
        ValueClass::Nan { .. } => Ok(value.0.quiet_nan()),
    }
}

pub(crate) struct PortableNumerics {
    arena: Arena,
}

impl PortableNumerics {
    pub fn new() -> Result<Self, NumericFailure> {
        let mut arena = Arena::new()?;
        arena.initialize_cache()?;
        arena.reset_disposable()?;
        Ok(Self { arena })
    }

    pub const fn profile() -> &'static str {
        PROFILE
    }

    pub fn add(
        &mut self,
        left: ArithmeticValue,
        right: ArithmeticValue,
    ) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(left.0, Some(right.0)) {
            return Ok(value);
        }
        match (left.0.classify(), right.0.classify()) {
            (ValueClass::Infinity, ValueClass::Infinity)
                if left.0.is_negative() != right.0.is_negative() =>
            {
                Arena::canonical_nan()
            }
            (ValueClass::Infinity, _) => Ok(left.0),
            (_, ValueClass::Infinity) => Ok(right.0),
            (ValueClass::Zero, ValueClass::Zero)
                if left.0.is_negative() && right.0.is_negative() =>
            {
                signed_zero(true)
            }
            (ValueClass::Zero, ValueClass::Zero) => signed_zero(false),
            _ => {
                let result = self.arena.add_finite(left.0, right.0);
                self.finish_call(result)
            }
        }
    }

    pub fn divide(
        &mut self,
        left: ArithmeticValue,
        right: ArithmeticValue,
    ) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(left.0, Some(right.0)) {
            return Ok(value);
        }
        let sign = left.0.is_negative() ^ right.0.is_negative();
        match (left.0.classify(), right.0.classify()) {
            (ValueClass::Zero, ValueClass::Zero) | (ValueClass::Infinity, ValueClass::Infinity) => {
                Arena::canonical_nan()
            }
            (ValueClass::Infinity, _) | (_, ValueClass::Zero) => Arena::infinity(sign),
            (ValueClass::Zero, _) | (_, ValueClass::Infinity) => signed_zero(sign),
            _ => {
                let result = self.arena.divide_finite(left.0, right.0);
                self.finish_call(result)
            }
        }
    }

    pub fn subtract(
        &mut self,
        left: ArithmeticValue,
        right: ArithmeticValue,
    ) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(left.0, Some(right.0)) {
            return Ok(value);
        }
        match (left.0.classify(), right.0.classify()) {
            (ValueClass::Infinity, ValueClass::Infinity)
                if left.0.is_negative() == right.0.is_negative() =>
            {
                Arena::canonical_nan()
            }
            (ValueClass::Infinity, _) => Ok(left.0),
            (_, ValueClass::Infinity) => flip_sign(right.0),
            (ValueClass::Zero, ValueClass::Zero) => {
                signed_zero(left.0.is_negative() && !right.0.is_negative())
            }
            (_, ValueClass::Zero) => Ok(left.0),
            (ValueClass::Zero, _) => flip_sign(right.0),
            _ => self.arena.subtract_finite(left.0, right.0),
        }
    }

    pub fn multiply(
        &mut self,
        left: ArithmeticValue,
        right: ArithmeticValue,
    ) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(left.0, Some(right.0)) {
            return Ok(value);
        }
        let sign = left.0.is_negative() ^ right.0.is_negative();
        match (left.0.classify(), right.0.classify()) {
            (ValueClass::Zero, ValueClass::Infinity) | (ValueClass::Infinity, ValueClass::Zero) => {
                Arena::canonical_nan()
            }
            (ValueClass::Infinity, _) | (_, ValueClass::Infinity) => Arena::infinity(sign),
            (ValueClass::Zero, _) | (_, ValueClass::Zero) => signed_zero(sign),
            _ => self.arena.multiply_finite(left.0, right.0),
        }
    }

    pub fn sqrt(&mut self, value: ArithmeticValue) -> Result<Value80, NumericFailure> {
        square_root(&mut self.arena, value)
    }

    pub fn log(&mut self, value: ArithmeticValue) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(value.0, None) {
            return Ok(value);
        }
        match value.0.classify() {
            ValueClass::Zero => Arena::infinity(true),
            ValueClass::Subnormal => Err(NumericFailure::UnsupportedDomain),
            ValueClass::Infinity if value.0.is_negative() => Arena::canonical_nan(),
            ValueClass::Infinity => Ok(value.0),
            ValueClass::Normal if value.0.is_negative() => Arena::canonical_nan(),
            ValueClass::Normal => {
                let result = self.arena.log_finite(value.0);
                self.finish_call(result)
            }
            ValueClass::Nan { .. } => Ok(value.0.quiet_nan()),
        }
    }

    pub fn exp(&mut self, value: ArithmeticValue) -> Result<Value80, NumericFailure> {
        if let Some(value) = first_nan(value.0, None) {
            return Ok(value);
        }
        match value.0.classify() {
            ValueClass::Infinity if value.0.is_negative() => signed_zero(false),
            ValueClass::Infinity => Ok(value.0),
            ValueClass::Zero | ValueClass::Subnormal | ValueClass::Normal => {
                let result = self.arena.exp_finite(value.0);
                self.finish_call(result)
            }
            ValueClass::Nan { .. } => Ok(value.0.quiet_nan()),
        }
    }

    fn finish_call(
        &mut self,
        result: Result<Value80, NumericFailure>,
    ) -> Result<Value80, NumericFailure> {
        self.arena.release_call_state()?;
        result
    }
}

fn first_nan(left: Value80, right: Option<Value80>) -> Option<Value80> {
    [Some(left), right].into_iter().flatten().find_map(|value| {
        matches!(value.classify(), ValueClass::Nan { .. }).then(|| value.quiet_nan())
    })
}

fn signed_zero(sign: bool) -> Result<Value80, NumericFailure> {
    Ok(Value80::signed_zero(sign))
}

fn flip_sign(value: Value80) -> Result<Value80, NumericFailure> {
    Ok(value.with_sign(!value.is_negative()))
}

pub(crate) fn promote_u64(value: u64) -> Value80 {
    Value80::exact_u64(value)
}

pub(crate) fn clear_sign(value: ArithmeticValue) -> ArithmeticValue {
    ArithmeticValue(value.0.with_sign(false))
}

pub(crate) fn compare(left: ArithmeticValue, right: ArithmeticValue) -> Comparison {
    if matches!(left.0.classify(), ValueClass::Nan { .. })
        || matches!(right.0.classify(), ValueClass::Nan { .. })
    {
        return Comparison::Unordered;
    }
    if matches!(left.0.classify(), ValueClass::Zero)
        && matches!(right.0.classify(), ValueClass::Zero)
    {
        return Comparison::Equal;
    }
    if left.0.same_bits(right.0) {
        return Comparison::Equal;
    }
    if left.0.is_negative() != right.0.is_negative() {
        return if left.0.is_negative() {
            Comparison::Less
        } else {
            Comparison::Greater
        };
    }
    let magnitude =
        (left.0.exponent(), left.0.significand()).cmp(&(right.0.exponent(), right.0.significand()));
    let magnitude = if left.0.is_negative() {
        magnitude.reverse()
    } else {
        magnitude
    };
    match magnitude {
        Ordering::Less => Comparison::Less,
        Ordering::Equal => Comparison::Equal,
        Ordering::Greater => Comparison::Greater,
    }
}

pub(crate) fn compare_magnitude(left: ArithmeticValue, right: ArithmeticValue) -> Comparison {
    compare(clear_sign(left), clear_sign(right))
}

#[inline]
pub(crate) fn sample_order(left: ArithmeticValue, right: ArithmeticValue) -> Ordering {
    match compare(left, right) {
        Comparison::Less => Ordering::Less,
        Comparison::Greater => Ordering::Greater,
        Comparison::Equal | Comparison::Unordered => Ordering::Equal,
    }
}

pub(crate) fn percentile_position(n: usize, percent: u8) -> (usize, ArithmeticValue) {
    debug_assert!((2..=65_536).contains(&n));
    debug_assert!((1..=99).contains(&percent));

    let (fraction_significand, fraction_power) = round_positive_binary64(u128::from(percent), 100);
    let product = fraction_significand * (n - 1) as u128;
    let bits = 128 - product.leading_zeros();
    let mut shift = bits.saturating_sub(53);
    let mut rounded = product >> shift;
    if shift != 0 {
        let remainder = product & ((1_u128 << shift) - 1);
        let halfway = 1_u128 << (shift - 1);
        if remainder > halfway || (remainder == halfway && rounded & 1 != 0) {
            rounded += 1;
        }
    }
    if rounded == 1_u128 << 53 {
        rounded >>= 1;
        shift += 1;
    }
    let power = fraction_power + shift as i32;
    let (index, fraction) = if power >= 0 {
        ((rounded << power) as usize, 0_u128)
    } else {
        let fractional_bits = (-power) as u32;
        let index = (rounded >> fractional_bits) as usize;
        let mask = (1_u128 << fractional_bits) - 1;
        (index, rounded & mask)
    };
    let value = if fraction == 0 {
        Value80::signed_zero(false)
    } else {
        let top = 127 - fraction.leading_zeros();
        let significand = (fraction << (63 - top)) as u64;
        let quantum = power - (63 - top) as i32;
        let exponent = (quantum + 16_446) as u16;
        // The admitted percentile bounds prove these fields are already in
        // the normal range; the representation owner enforces canonicality.
        Value80::canonical_normal(false, exponent, significand)
    };
    (index, ArithmeticValue(value))
}

fn round_positive_binary64(numerator: u128, denominator: u128) -> (u128, i32) {
    let mut exponent = -1_i32;
    while exponent > -7 && (numerator << (-exponent)) < denominator {
        exponent -= 1;
    }
    let scaled = numerator << (52 - exponent);
    let mut quotient = scaled / denominator;
    let remainder = scaled % denominator;
    if remainder * 2 > denominator || (remainder * 2 == denominator && quotient & 1 != 0) {
        quotient += 1;
    }
    if quotient == 1_u128 << 53 {
        quotient >>= 1;
        exponent += 1;
    }
    (quotient, exponent - 52)
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod v3_tests;