fastmash 0.7.1

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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use crate::numeric_contract::{Raw80, Value80};
use crate::portable_numerics::NumericFailure;

pub(super) const ARENA_BYTES: usize = 131_072;
const ARENA_CELLS: usize = ARENA_BYTES / size_of::<u64>();
pub(super) const CACHE_ENDPOINTS: usize = 10;
pub(super) const WORK_ENDPOINTS: usize = 48;
pub(super) const STORED_SLOTS: usize = CACHE_ENDPOINTS + WORK_ENDPOINTS;

const CACHE_MAG_BASE: usize = 0;
const CACHE_DESC_BASE: usize = 90;
const WORK_MAG_BASE: usize = 2_048;
const WORK_DESC_BASE: usize = 2_480;
const EXACT_MAG_BASE: usize = 2_528;
const EXACT_DESC_BASE: usize = 2_579;
const SCALAR_BASE: usize = 2_582;
const PRIMITIVE_BASE: usize = 2_048;
const PRIMITIVE_CELLS: usize = 8;

const MIN_EXP: i32 = -3_100_000;
const MAX_EXP: i32 = 100_000;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Slot9(pub(super) u8);

impl Slot9 {
    pub(super) const fn cache(interval: u8, endpoint: u8) -> Self {
        Self(interval * 2 + endpoint)
    }

    pub(super) const fn work(register: u8, endpoint: u8) -> Self {
        Self(CACHE_ENDPOINTS as u8 + register * 2 + endpoint)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Slot17(pub(super) u8);

impl Slot17 {
    pub(super) const X0: Self = Self(0);
    pub(super) const X1: Self = Self(1);
    pub(super) const X2: Self = Self(2);
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Desc {
    pub(super) sign: bool,
    pub(super) len: u8,
    pub(super) exp: i32,
}

impl Desc {
    pub(super) const fn zero(sign: bool) -> Self {
        Self {
            sign,
            len: 0,
            exp: 0,
        }
    }
}

pub(super) struct Arena {
    cells: Vec<u64>,
}

#[derive(Clone, Copy)]
pub(super) struct PrimitiveCell(u8);

impl PrimitiveCell {
    pub(super) const V0: Self = Self(0);
    pub(super) const V1: Self = Self(1);
    pub(super) const V2: Self = Self(2);
    pub(super) const V3: Self = Self(3);
    pub(super) const V4: Self = Self(4);
    // Only the bit-serial square root, the tests' reference, uses these.
    #[cfg(test)]
    pub(super) const V5: Self = Self(5);
    #[cfg(test)]
    pub(super) const V6: Self = Self(6);
    #[cfg(test)]
    pub(super) const V7: Self = Self(7);
}

pub(super) struct PrimitiveCells<'a> {
    arena: &'a mut Arena,
}

impl PrimitiveCells<'_> {
    pub(super) fn get(&self, cell: PrimitiveCell) -> Result<u64, NumericFailure> {
        self.arena
            .cells()
            .get(PRIMITIVE_BASE + usize::from(cell.0))
            .copied()
            .ok_or(NumericFailure::Invariant)
    }

    pub(super) fn set(&mut self, cell: PrimitiveCell, value: u64) -> Result<(), NumericFailure> {
        *self
            .arena
            .cells_mut()
            .get_mut(PRIMITIVE_BASE + usize::from(cell.0))
            .ok_or(NumericFailure::Invariant)? = value;
        Ok(())
    }
}

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

    fn new_with(cell_count: usize) -> Result<Self, NumericFailure> {
        let mut cells = Vec::new();
        cells
            .try_reserve_exact(cell_count)
            .map_err(|_| NumericFailure::Allocation)?;
        cells.resize(cell_count, 0);
        Ok(Self { cells })
    }

    fn cells(&self) -> &[u64] {
        &self.cells
    }

    fn cells_mut(&mut self) -> &mut [u64] {
        &mut self.cells
    }

    fn slot9_offset(slot: Slot9) -> Result<usize, NumericFailure> {
        let index = usize::from(slot.0);
        if index < CACHE_ENDPOINTS {
            Ok(CACHE_MAG_BASE + index * 9)
        } else if index < STORED_SLOTS {
            Ok(WORK_MAG_BASE + (index - CACHE_ENDPOINTS) * 9)
        } else {
            Err(NumericFailure::Invariant)
        }
    }

    fn slot9_desc(slot: Slot9) -> Result<usize, NumericFailure> {
        let index = usize::from(slot.0);
        if index < CACHE_ENDPOINTS {
            Ok(CACHE_DESC_BASE + index)
        } else if index < STORED_SLOTS {
            Ok(WORK_DESC_BASE + index - CACHE_ENDPOINTS)
        } else {
            Err(NumericFailure::Invariant)
        }
    }

    fn slot17_offset(slot: Slot17) -> Result<usize, NumericFailure> {
        (slot.0 < 3)
            .then_some(EXACT_MAG_BASE + usize::from(slot.0) * 17)
            .ok_or(NumericFailure::Invariant)
    }

    fn slot17_desc(slot: Slot17) -> Result<usize, NumericFailure> {
        (slot.0 < 3)
            .then_some(EXACT_DESC_BASE + usize::from(slot.0))
            .ok_or(NumericFailure::Invariant)
    }

    fn decode(raw: u64, width: u8) -> Result<Desc, NumericFailure> {
        let len = (raw & 0x1f) as u8;
        let sign = raw & 0x20 != 0;
        let normalized = raw & 0x40 != 0;
        let exp = (raw >> 32) as u32 as i32;
        if len > width
            || !(MIN_EXP..=MAX_EXP).contains(&exp)
            || (len == 0 && (exp != 0 || normalized))
            || (len != 0 && !normalized)
        {
            return Err(NumericFailure::Invariant);
        }
        Ok(Desc { sign, len, exp })
    }

    fn encode(desc: Desc, width: u8) -> Result<u64, NumericFailure> {
        if desc.len > width
            || !(MIN_EXP..=MAX_EXP).contains(&desc.exp)
            || (desc.len == 0 && desc.exp != 0)
        {
            return Err(NumericFailure::Invariant);
        }
        Ok((u64::from(desc.exp as u32) << 32)
            | u64::from(desc.len)
            | (u64::from(desc.sign) << 5)
            | (u64::from(desc.len != 0) << 6))
    }

    #[inline(always)]
    pub(super) fn desc9(&self, slot: Slot9) -> Result<Desc, NumericFailure> {
        let desc = Self::decode(
            *self
                .cells()
                .get(Self::slot9_desc(slot)?)
                .ok_or(NumericFailure::Invariant)?,
            9,
        )?;
        if desc.len != 0 {
            let last = self.limb9(slot, usize::from(desc.len) - 1)?;
            if last == 0 {
                return Err(NumericFailure::Invariant);
            }
        }
        Ok(desc)
    }

    #[inline(always)]
    pub(super) fn desc17(&self, slot: Slot17) -> Result<Desc, NumericFailure> {
        let desc = Self::decode(
            *self
                .cells()
                .get(Self::slot17_desc(slot)?)
                .ok_or(NumericFailure::Invariant)?,
            17,
        )?;
        if desc.len != 0 {
            let last = self.limb17(slot, usize::from(desc.len) - 1)?;
            if last == 0 {
                return Err(NumericFailure::Invariant);
            }
        }
        Ok(desc)
    }

    pub(super) fn set_desc9(&mut self, slot: Slot9, desc: Desc) -> Result<(), NumericFailure> {
        let index = Self::slot9_desc(slot)?;
        *self
            .cells_mut()
            .get_mut(index)
            .ok_or(NumericFailure::Invariant)? = Self::encode(desc, 9)?;
        Ok(())
    }

    pub(super) fn set_desc17(&mut self, slot: Slot17, desc: Desc) -> Result<(), NumericFailure> {
        let index = Self::slot17_desc(slot)?;
        *self
            .cells_mut()
            .get_mut(index)
            .ok_or(NumericFailure::Invariant)? = Self::encode(desc, 17)?;
        Ok(())
    }

    pub(super) fn limb9(&self, slot: Slot9, index: usize) -> Result<u64, NumericFailure> {
        if index >= 9 {
            return Err(NumericFailure::Invariant);
        }
        Ok(*self
            .cells()
            .get(Self::slot9_offset(slot)? + index)
            .ok_or(NumericFailure::Invariant)?)
    }

    pub(super) fn set_limb9(
        &mut self,
        slot: Slot9,
        index: usize,
        value: u64,
    ) -> Result<(), NumericFailure> {
        if index >= 9 {
            return Err(NumericFailure::Invariant);
        }
        let offset = Self::slot9_offset(slot)? + index;
        *self
            .cells_mut()
            .get_mut(offset)
            .ok_or(NumericFailure::Invariant)? = value;
        Ok(())
    }

    pub(super) fn limb17(&self, slot: Slot17, index: usize) -> Result<u64, NumericFailure> {
        if index >= 17 {
            return Err(NumericFailure::Invariant);
        }
        Ok(*self
            .cells()
            .get(Self::slot17_offset(slot)? + index)
            .ok_or(NumericFailure::Invariant)?)
    }

    pub(super) fn set_limb17(
        &mut self,
        slot: Slot17,
        index: usize,
        value: u64,
    ) -> Result<(), NumericFailure> {
        if index >= 17 {
            return Err(NumericFailure::Invariant);
        }
        let offset = Self::slot17_offset(slot)? + index;
        *self
            .cells_mut()
            .get_mut(offset)
            .ok_or(NumericFailure::Invariant)? = value;
        Ok(())
    }

    pub(super) fn scalar(&self, index: usize) -> Result<u64, NumericFailure> {
        if index >= 6 {
            return Err(NumericFailure::Invariant);
        }
        Ok(*self
            .cells()
            .get(SCALAR_BASE + index)
            .ok_or(NumericFailure::Invariant)?)
    }

    pub(super) fn set_scalar(&mut self, index: usize, value: u64) -> Result<(), NumericFailure> {
        if index >= 6 {
            return Err(NumericFailure::Invariant);
        }
        *self
            .cells_mut()
            .get_mut(SCALAR_BASE + index)
            .ok_or(NumericFailure::Invariant)? = value;
        Ok(())
    }

    pub(super) fn clear9(&mut self, slot: Slot9, sign: bool) -> Result<(), NumericFailure> {
        let offset = Self::slot9_offset(slot)?;
        self.cells_mut()
            .get_mut(offset..offset + 9)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        self.set_desc9(slot, Desc::zero(sign))
    }

    pub(super) fn clear17(&mut self, slot: Slot17) -> Result<(), NumericFailure> {
        let offset = Self::slot17_offset(slot)?;
        self.cells_mut()
            .get_mut(offset..offset + 17)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        self.set_desc17(slot, Desc::zero(false))
    }

    pub(super) fn reset_disposable(&mut self) -> Result<(), NumericFailure> {
        self.cells_mut()
            .get_mut(2_048..2_408)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        self.cells_mut()
            .get_mut(2_480..2_520)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        self.cells_mut()
            .get_mut(2_528..2_588)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        Ok(())
    }

    pub(super) fn release_call_state(&mut self) -> Result<(), NumericFailure> {
        self.cells_mut()
            .get_mut(2_528..2_582)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        self.cells_mut()
            .get_mut(2_585..2_588)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        Ok(())
    }

    pub(super) fn exact_scope<T>(
        &mut self,
        operation: impl FnOnce(&mut Self) -> Result<T, NumericFailure>,
    ) -> Result<T, NumericFailure> {
        let result = operation(self);
        self.cells_mut()
            .get_mut(2_528..2_582)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        result
    }

    pub(super) fn primitive_value_scope(
        &mut self,
        operation: impl FnOnce(&mut PrimitiveCells<'_>) -> Result<Raw80, NumericFailure>,
    ) -> Result<Value80, NumericFailure> {
        self.reset_disposable()?;
        if !self
            .cells()
            .get(2_048..2_408)
            .ok_or(NumericFailure::Invariant)?
            .iter()
            .chain(
                self.cells()
                    .get(2_480..2_520)
                    .ok_or(NumericFailure::Invariant)?,
            )
            .chain(
                self.cells()
                    .get(2_528..2_588)
                    .ok_or(NumericFailure::Invariant)?,
            )
            .all(|cell| *cell == 0)
        {
            return Err(NumericFailure::Invariant);
        }
        let result = operation(&mut PrimitiveCells { arena: self })
            .and_then(|raw| Value80::from_raw(raw).map_err(|_| NumericFailure::Invariant));
        self.cells_mut()
            .get_mut(PRIMITIVE_BASE..PRIMITIVE_BASE + PRIMITIVE_CELLS)
            .ok_or(NumericFailure::Invariant)?
            .fill(0);
        result
    }

    #[cfg(test)]
    pub(super) fn allocation_failure() -> Result<Self, NumericFailure> {
        Self::new_with(usize::MAX)
    }

    #[cfg(test)]
    pub(super) fn cache_snapshot_for_test(&self) -> [u64; 2_048] {
        let mut snapshot = [0; 2_048];
        snapshot.copy_from_slice(&self.cells()[..2_048]);
        snapshot
    }

    #[cfg(test)]
    pub(super) fn primitive_cells_clear_for_test(&self) -> bool {
        self.cells()[PRIMITIVE_BASE..PRIMITIVE_BASE + PRIMITIVE_CELLS]
            .iter()
            .all(|cell| *cell == 0)
    }

    #[cfg(test)]
    pub(super) fn inject_primitive_invariant_for_test(
        &mut self,
    ) -> Result<Value80, NumericFailure> {
        self.primitive_value_scope(|scratch| {
            scratch.set(PrimitiveCell::V7, 1)?;
            Err(NumericFailure::Invariant)
        })
    }
}