grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
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
// Project:   grippo
// File:      src/kernel/hex.rs
// Purpose:   Hex digits decoded 32 or 64 a step, and by a table loop
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Hex text to bytes, upper and lower case alike.
//!
//! A vector step finds each digit's value by two range checks, `c - '0'`
//! under 10 or `(c | 0x20) - 'a'` under 6, then joins each pair. SSSE3 takes
//! 32 digits a step and AVX2 64, picked at run time, joining pairs with a
//! multiply-add and narrowing with `packus`. NEON takes 32, split into high
//! and low digits by `vld2q_u8`. A 256-entry table takes the last digits, a
//! step with a byte that isn't a digit, and every CPU with no vector tier.

/// A byte that isn't a hex digit, in [`VALUE`].
const OUTSIDE: u8 = 0xFF;

/// Each byte's digit value, or [`OUTSIDE`].
#[allow(
    clippy::cast_possible_truncation,
    reason = "a digit's value is below 16"
)]
static VALUE: [u8; 256] = {
    let mut table = [OUTSIDE; 256];
    let mut i = 0;
    while i < 10 {
        table[b'0' as usize + i] = i as u8;
        i += 1;
    }
    let mut i = 0;
    while i < 6 {
        table[b'a' as usize + i] = 10 + i as u8;
        table[b'A' as usize + i] = 10 + i as u8;
        i += 1;
    }
    table
};

/// Why hex text didn't decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
    /// The text breaks the encoding at `offset`.
    Malformed {
        /// Byte offset into the text.
        offset: usize,
        /// What is wrong there.
        reason: &'static str,
    },
    /// The decoded bytes would pass the cap.
    Limit,
}

/// Appends `text` decoded to `out`. Fails when it isn't an even number of hex
/// digits, or when `out` would grow by more than `cap` bytes, and then leaves
/// `out` as it was.
///
/// # Errors
///
/// [`Failure`] as above.
pub fn decode(text: &[u8], out: &mut Vec<u8>, cap: usize) -> Result<(), Failure> {
    if !text.len().is_multiple_of(2) {
        return Err(Failure::Malformed {
            offset: text.len(),
            reason: "an odd number of hex digits",
        });
    }
    let len = text.len() / 2;
    if len > cap {
        return Err(Failure::Limit);
    }
    let start = out.len();
    out.resize(start + len, 0);
    let dst = &mut out[start..];
    let done = vector_steps(text, dst);
    let result = by_table(&text[done..], &mut dst[done / 2..], done);
    if result.is_err() {
        out.truncate(start);
    }
    result
}

/// The table loop over `text`, which starts `base` bytes into the caller's,
/// into `dst`, half its length.
pub(super) fn by_table(text: &[u8], dst: &mut [u8], base: usize) -> Result<(), Failure> {
    for (i, (&[hi, lo], byte)) in text.as_chunks::<2>().0.iter().zip(dst).enumerate() {
        let (hi, lo) = (VALUE[usize::from(hi)], VALUE[usize::from(lo)]);
        if hi == OUTSIDE || lo == OUTSIDE {
            let offset = base + 2 * i + usize::from(hi != OUTSIDE);
            return Err(Failure::Malformed {
                offset,
                reason: "not a hex digit",
            });
        }
        *byte = hi << 4 | lo;
    }
    Ok(())
}

/// Decodes whole vector steps of `text` into `dst`, half its length. Returns
/// the digits it took: it stops at a step with a byte that isn't a digit. 0 on
/// a CPU with no tier.
fn vector_steps(text: &[u8], dst: &mut [u8]) -> usize {
    #[cfg(target_arch = "x86_64")]
    {
        x86::steps(text, dst)
    }
    #[cfg(all(
        target_arch = "aarch64",
        target_endian = "little",
        target_feature = "neon"
    ))]
    {
        neon::steps(text, dst)
    }
    #[cfg(not(any(
        target_arch = "x86_64",
        all(
            target_arch = "aarch64",
            target_endian = "little",
            target_feature = "neon"
        )
    )))]
    {
        let _ = (text, dst);
        0
    }
}

/// Runs `step` over each whole `IN`-digit block of `text`, writing `IN / 2`
/// bytes a block into `dst`. Returns the digits taken. Inlined, so `step`
/// inlines into the vector tier's loop.
#[cfg(any(
    target_arch = "x86_64",
    all(
        target_arch = "aarch64",
        target_endian = "little",
        target_feature = "neon"
    )
))]
#[allow(
    clippy::inline_always,
    reason = "a step can inline only into a caller that has its target features"
)]
#[inline(always)]
fn blocks<const IN: usize, const OUT: usize>(
    text: &[u8],
    dst: &mut [u8],
    mut step: impl FnMut(&[u8; IN], &mut [u8; OUT]) -> bool,
) -> usize {
    let mut taken = 0;
    while let Some(block) = text.get(taken..).and_then(<[u8]>::first_chunk::<IN>)
        && let Some(out) = dst
            .get_mut(taken / 2..)
            .and_then(<[u8]>::first_chunk_mut::<OUT>)
        && step(block, out)
    {
        taken += IN;
    }
    taken
}

#[cfg(target_arch = "x86_64")]
pub(super) mod x86 {
    use std::arch::x86_64::{
        __m128i, __m256i, _mm_add_epi8, _mm_and_si128, _mm_cmpeq_epi8, _mm_maddubs_epi16,
        _mm_min_epu8, _mm_movemask_epi8, _mm_or_si128, _mm_packus_epi16, _mm_set1_epi8,
        _mm_set1_epi16, _mm_storeu_si128, _mm_sub_epi8, _mm256_add_epi8, _mm256_and_si256,
        _mm256_cmpeq_epi8, _mm256_maddubs_epi16, _mm256_min_epu8, _mm256_movemask_epi8,
        _mm256_or_si256, _mm256_packus_epi16, _mm256_permute4x64_epi64, _mm256_set1_epi8,
        _mm256_set1_epi16, _mm256_storeu_si256, _mm256_sub_epi8,
    };

    use super::blocks;
    use crate::kernel::x86::{load16, load32};

    /// The AVX2 or SSSE3 steps, whichever this CPU has.
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only after its feature is detected"
    )]
    pub(in crate::kernel) fn steps(text: &[u8], dst: &mut [u8]) -> usize {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: this CPU has AVX2, by the check on the line above.
            return unsafe { avx2(text, dst) };
        }
        if is_x86_feature_detected!("ssse3") {
            // SAFETY: this CPU has SSSE3, by the check on the line above.
            return unsafe { ssse3(text, dst) };
        }
        0
    }

    /// 64 digits to 32 bytes a step, then 32 to 16.
    #[target_feature(enable = "avx2")]
    pub(in crate::kernel) fn avx2(text: &[u8], dst: &mut [u8]) -> usize {
        let zero = _mm256_set1_epi8(b'0'.cast_signed());
        let a = _mm256_set1_epi8(b'a'.cast_signed());
        let case = _mm256_set1_epi8(0x20);
        let nine = _mm256_set1_epi8(9);
        let five = _mm256_set1_epi8(5);
        let ten = _mm256_set1_epi8(10);
        let pair = _mm256_set1_epi16(0x0110);
        // Each digit's value, and 0xFF in each lane that holds a digit.
        let value = |text: __m256i| {
            let digit = _mm256_sub_epi8(text, zero);
            let letter = _mm256_sub_epi8(_mm256_or_si256(text, case), a);
            let is_digit = _mm256_cmpeq_epi8(_mm256_min_epu8(digit, nine), digit);
            let is_letter = _mm256_cmpeq_epi8(_mm256_min_epu8(letter, five), letter);
            let value = _mm256_or_si256(
                _mm256_and_si256(is_digit, digit),
                _mm256_and_si256(is_letter, _mm256_add_epi8(letter, ten)),
            );
            (value, _mm256_or_si256(is_digit, is_letter))
        };
        let taken = blocks::<64, 32>(text, dst, |block, out| {
            let (first, second) = block.split_at(32);
            let (Some(first), Some(second)) = (first.first_chunk(), second.first_chunk()) else {
                return false;
            };
            let (x, x_ok) = value(load32(first));
            let (y, y_ok) = value(load32(second));
            if _mm256_movemask_epi8(_mm256_and_si256(x_ok, y_ok)) != -1 {
                return false;
            }
            // Each pair to `high * 16 + low` in a 16-bit lane, narrowed to bytes.
            // packus works within 128-bit halves, so the quarters are put back
            // in order after.
            let packed =
                _mm256_packus_epi16(_mm256_maddubs_epi16(x, pair), _mm256_maddubs_epi16(y, pair));
            store32(out, _mm256_permute4x64_epi64::<0b11_01_10_00>(packed));
            true
        });
        let (rest_text, rest_dst) = (
            text.get(taken..).unwrap_or_default(),
            dst.get_mut(taken / 2..).unwrap_or_default(),
        );
        taken + ssse3(rest_text, rest_dst)
    }

    /// 32 digits to 16 bytes a step.
    #[target_feature(enable = "ssse3")]
    pub(in crate::kernel) fn ssse3(text: &[u8], dst: &mut [u8]) -> usize {
        let zero = _mm_set1_epi8(b'0'.cast_signed());
        let a = _mm_set1_epi8(b'a'.cast_signed());
        let case = _mm_set1_epi8(0x20);
        let nine = _mm_set1_epi8(9);
        let five = _mm_set1_epi8(5);
        let ten = _mm_set1_epi8(10);
        let pair = _mm_set1_epi16(0x0110);
        let value = |text: __m128i| {
            let digit = _mm_sub_epi8(text, zero);
            let letter = _mm_sub_epi8(_mm_or_si128(text, case), a);
            let is_digit = _mm_cmpeq_epi8(_mm_min_epu8(digit, nine), digit);
            let is_letter = _mm_cmpeq_epi8(_mm_min_epu8(letter, five), letter);
            let value = _mm_or_si128(
                _mm_and_si128(is_digit, digit),
                _mm_and_si128(is_letter, _mm_add_epi8(letter, ten)),
            );
            (value, _mm_or_si128(is_digit, is_letter))
        };
        blocks::<32, 16>(text, dst, |block, out| {
            let (first, second) = block.split_at(16);
            let (Some(first), Some(second)) = (first.first_chunk(), second.first_chunk()) else {
                return false;
            };
            let (x, x_ok) = value(load16(first));
            let (y, y_ok) = value(load16(second));
            if _mm_movemask_epi8(_mm_and_si128(x_ok, y_ok)) != 0xFFFF {
                return false;
            }
            let packed = _mm_packus_epi16(_mm_maddubs_epi16(x, pair), _mm_maddubs_epi16(y, pair));
            store16(out, packed);
            true
        })
    }

    #[allow(
        unsafe_code,
        reason = "an unaligned vector store has no safe form that compiles to one store"
    )]
    #[inline]
    #[target_feature(enable = "sse2")]
    fn store16(dst: &mut [u8; 16], bytes: __m128i) {
        // SAFETY: `dst` is 16 writable bytes, and this store needs no
        // alignment.
        unsafe { _mm_storeu_si128(std::ptr::from_mut(dst).cast(), bytes) }
    }

    #[allow(
        unsafe_code,
        reason = "an unaligned vector store has no safe form that compiles to one store"
    )]
    #[inline]
    #[target_feature(enable = "avx")]
    fn store32(dst: &mut [u8; 32], bytes: __m256i) {
        // SAFETY: `dst` is 32 writable bytes, and this store needs no
        // alignment.
        unsafe { _mm256_storeu_si256(std::ptr::from_mut(dst).cast(), bytes) }
    }

    /// One tier's steps, for the tests.
    #[cfg(test)]
    pub(in crate::kernel) type Tier = fn(&[u8], &mut [u8]) -> usize;

    /// Each vector tier this CPU can run, by name, for the tests.
    #[cfg(test)]
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only after its feature is detected"
    )]
    pub(in crate::kernel) fn tiers() -> Vec<(&'static str, Tier)> {
        let mut tiers: Vec<(&'static str, Tier)> = Vec::new();
        if is_x86_feature_detected!("avx2") {
            // SAFETY: this CPU has AVX2, by the check on the line above.
            tiers.push(("avx2", |t, d| unsafe { avx2(t, d) }));
        }
        if is_x86_feature_detected!("ssse3") {
            // SAFETY: this CPU has SSSE3, by the check on the line above.
            tiers.push(("ssse3", |t, d| unsafe { ssse3(t, d) }));
        }
        tiers
    }
}

/// The same steps on aarch64, where NEON is part of the base instruction set.
#[cfg(all(
    target_arch = "aarch64",
    target_endian = "little",
    target_feature = "neon"
))]
pub(super) mod neon {
    use std::arch::aarch64::{
        uint8x16_t, uint8x16x2_t, vaddq_u8, vandq_u8, vbslq_u8, vcltq_u8, vdupq_n_u8, vld2q_u8,
        vminvq_u8, vorrq_u8, vshlq_n_u8, vst1q_u8, vsubq_u8,
    };

    use super::blocks;

    /// [`whole_steps`], from a caller that has NEON only by this build's
    /// `cfg`.
    #[allow(
        unsafe_code,
        reason = "a #[target_feature] function is called only where its feature is compiled in"
    )]
    pub(in crate::kernel) fn steps(text: &[u8], dst: &mut [u8]) -> usize {
        // SAFETY: this module builds only with `target_feature = "neon"`, so
        // every CPU this binary runs on has NEON.
        unsafe { whole_steps(text, dst) }
    }

    /// 32 digits to 16 bytes a step.
    #[target_feature(enable = "neon")]
    fn whole_steps(text: &[u8], dst: &mut [u8]) -> usize {
        let zero = vdupq_n_u8(b'0');
        let a = vdupq_n_u8(b'a');
        let case = vdupq_n_u8(0x20);
        let six = vdupq_n_u8(6);
        let ten = vdupq_n_u8(10);
        // Each digit's value, and 0xFF in each lane that holds a digit.
        let value = |text: uint8x16_t| {
            let digit = vsubq_u8(text, zero);
            let letter = vsubq_u8(vorrq_u8(text, case), a);
            let is_digit = vcltq_u8(digit, ten);
            let is_letter = vcltq_u8(letter, six);
            let value = vbslq_u8(is_digit, digit, vaddq_u8(letter, ten));
            (value, vorrq_u8(is_digit, is_letter))
        };
        blocks::<32, 16>(text, dst, |block, out| {
            let pairs = load2(block);
            let (hi, hi_ok) = value(pairs.0);
            let (lo, lo_ok) = value(pairs.1);
            if vminvq_u8(vandq_u8(hi_ok, lo_ok)) != 0xFF {
                return false;
            }
            store(out, vorrq_u8(vshlq_n_u8::<4>(hi), lo));
            true
        })
    }

    #[allow(
        unsafe_code,
        reason = "a vector load from a pointer has no safe form that compiles to one load"
    )]
    #[inline]
    #[target_feature(enable = "neon")]
    fn load2(bytes: &[u8; 32]) -> uint8x16x2_t {
        // SAFETY: `bytes` is 32 readable bytes, and this load needs no
        // alignment.
        unsafe { vld2q_u8(bytes.as_ptr()) }
    }

    #[allow(
        unsafe_code,
        reason = "a vector store to a pointer has no safe form that compiles to one store"
    )]
    #[inline]
    #[target_feature(enable = "neon")]
    fn store(dst: &mut [u8; 16], bytes: uint8x16_t) {
        // SAFETY: `dst` is 16 writable bytes, and this store needs no
        // alignment.
        unsafe { vst1q_u8(dst.as_mut_ptr(), bytes) }
    }

    /// One tier's steps, for the tests.
    #[cfg(test)]
    pub(in crate::kernel) type Tier = fn(&[u8], &mut [u8]) -> usize;

    /// The vector tier, by name, for the tests.
    #[cfg(test)]
    pub(in crate::kernel) fn tiers() -> Vec<(&'static str, Tier)> {
        vec![("neon", steps)]
    }
}