hyperlane-plugin-negotiate 23.3.1

A response negotiation plugin for the Hyperlane framework, answering with the content coding the client accepts and with 304 Not Modified while a validator still matches.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use super::*;

/// Computes the exact 64-bit XXH3 digest of `data` without heap allocation for any input length.
///
/// # Arguments
///
/// - `&[u8]` - Input payload bytes.
///
/// # Returns
///
/// - `u64` - Bit-exact 64-bit XXH3 digest matching `XxHash3_64`.
#[inline]
pub(crate) fn xxhash3_64_oneshot(data: &[u8]) -> u64 {
    let len: usize = data.len();
    if len <= XXH3_SHORT_LIMIT {
        let mut hasher: XxHash3_64 = XxHash3_64::default();
        hasher.write(data);
        return hasher.finish();
    }
    if len <= XXH3_MID_LIMIT {
        let mut acc: u64 = (len as u64).wrapping_mul(XXH3_PRIME64_1);
        let nb_rounds: usize = len / 16;
        let mut i: usize = 0;
        while i < 8 {
            acc = acc.wrapping_add(xxh3_mix16b(&data[i * 16..], &XXH3_DEFAULT_SECRET[i * 16..]));
            i += 1;
        }
        acc = xxh3_avalanche(acc);
        let mut j: usize = 8;
        while j < nb_rounds {
            acc = acc.wrapping_add(xxh3_mix16b(
                &data[j * 16..],
                &XXH3_DEFAULT_SECRET[(j - 8) * 16 + 3..],
            ));
            j += 1;
        }
        acc = acc.wrapping_add(xxh3_mix16b(&data[len - 16..], &XXH3_DEFAULT_SECRET[119..]));
        return xxh3_avalanche(acc);
    }
    xxh3_hash_long(data)
}

/// Checks whether a status carries no body a content coding could apply to.
///
/// # Arguments
///
/// - `usize` - The status code of the response.
///
/// # Returns
///
/// - `bool` - Whether the status is bodyless.
#[inline(always)]
pub(crate) fn has_no_body(status_code: usize) -> bool {
    matches!(status_code, 100..=199)
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code()
}

/// Inspects all response headers in a single length-dispatched pass to decide compression eligibility and `Vary` action.
///
/// # Arguments
///
/// - `&Response` - The outgoing response to inspect.
///
/// # Returns
///
/// - `u8` - One of `COMPRESS_STATE_SKIP`, `COMPRESS_STATE_SET_VARY`, `COMPRESS_STATE_ADD_VARY`, or `COMPRESS_STATE_VARY_OK`.
#[inline]
pub(crate) fn inspect_response_for_compress(response: &Response) -> u8 {
    let headers: &ResponseHeaders = response.get_headers();
    if headers.is_empty() {
        return COMPRESS_STATE_SET_VARY;
    }
    let mut has_vary: bool = false;
    let mut vary_declared: bool = false;
    for (key, values) in headers {
        match key.len() {
            len if len == CONTENT_ENCODING.len() && key.eq_ignore_ascii_case(CONTENT_ENCODING) => {
                return COMPRESS_STATE_SKIP;
            }
            len if len == CACHE_CONTROL.len() && key.eq_ignore_ascii_case(CACHE_CONTROL) => {
                if values.iter().any(|value: &String| {
                    value.split(COMMA).any(|directive: &str| {
                        directive
                            .trim()
                            .eq_ignore_ascii_case(CACHE_CONTROL_NO_TRANSFORM)
                    })
                }) {
                    return COMPRESS_STATE_SKIP;
                }
            }
            len if len == CONTENT_TYPE.len() && key.eq_ignore_ascii_case(CONTENT_TYPE) => {
                if values.iter().any(|value: &String| {
                    value
                        .split(MEDIA_TYPE_PARAM_DELIMITER)
                        .next()
                        .is_some_and(|media: &str| {
                            media.trim().eq_ignore_ascii_case(TEXT_EVENT_STREAM)
                        })
                }) {
                    return COMPRESS_STATE_SKIP;
                }
            }
            len if len == VARY.len() && key.eq_ignore_ascii_case(VARY) => {
                has_vary = true;
                if !vary_declared
                    && values.iter().any(|value: &String| {
                        value.split(COMMA).any(|token: &str| {
                            let trimmed: &str = token.trim();
                            trimmed.eq_ignore_ascii_case(VARY_ACCEPT_ENCODING)
                                || trimmed == VARY_WILDCARD
                        })
                    })
                {
                    vary_declared = true;
                }
            }
            _ => {}
        }
    }
    if vary_declared {
        COMPRESS_STATE_VARY_OK
    } else if has_vary {
        COMPRESS_STATE_ADD_VARY
    } else {
        COMPRESS_STATE_SET_VARY
    }
}

/// Scans a semicolon-free `Accept-Encoding` token list and updates `best` in place, returning `true` on immediate `br`/`*` match.
///
/// # Arguments
///
/// - `&str` - Semicolon-free `Accept-Encoding` header value.
/// - `&mut Option<Compress>` - Running best supported content coding.
///
/// # Returns
///
/// - `bool` - `true` when highest-priority `Compress::Br` was matched and scanning can stop immediately.
#[inline(always)]
pub(crate) fn scan_accept_encoding_tokens(value: &str, best: &mut Option<Compress>) -> bool {
    for token in value.split(COMMA) {
        let trimmed: &str = token.trim();
        match trimmed.len() {
            1 if trimmed.as_bytes()[0] == BYTE_STAR => {
                *best = Some(Compress::Br);
                return true;
            }
            2 if trimmed.eq_ignore_ascii_case(CODING_BR) => {
                *best = Some(Compress::Br);
                return true;
            }
            4 if trimmed.eq_ignore_ascii_case(CODING_GZIP) => {
                *best = Some(Compress::Gzip);
            }
            6 if trimmed.eq_ignore_ascii_case(CODING_X_GZIP) => {
                *best = Some(Compress::Gzip);
            }
            7 if best.is_none() && trimmed.eq_ignore_ascii_case(CODING_DEFLATE) => {
                *best = Some(Compress::Deflate);
            }
            _ => {}
        }
    }
    false
}

/// Fast-path `Accept-Encoding` parser that avoids quality-value float parsing when no `;` is present.
///
/// # Arguments
///
/// - `&str` - Raw `Accept-Encoding` header value.
///
/// # Returns
///
/// - `Option<Compress>` - Best supported content coding, or `None`.
#[inline]
pub(crate) fn parse_accept_encoding_fast(value: &str) -> Option<Compress> {
    if value.as_bytes().contains(&BYTE_SEMICOLON) {
        return Compress::from_accept_encoding(value);
    }
    let mut best: Option<Compress> = None;
    let _: bool = scan_accept_encoding_tokens(value, &mut best);
    best
}

/// Parses a list of `Accept-Encoding` values directly without copying when no quality-value parameters are present.
///
/// # Arguments
///
/// - `&VecDeque<String>` - Values stored under the `accept-encoding` key.
///
/// # Returns
///
/// - `Option<Compress>` - Best supported content coding, or `None`.
#[inline]
pub(crate) fn parse_accept_encoding_values(values: &VecDeque<String>) -> Option<Compress> {
    if values.len() == 1 {
        return values
            .front()
            .and_then(|val: &String| parse_accept_encoding_fast(val));
    }
    if values.is_empty() {
        return None;
    }
    if !values
        .iter()
        .any(|val: &String| val.as_bytes().contains(&BYTE_SEMICOLON))
    {
        let mut best: Option<Compress> = None;
        for val in values {
            if scan_accept_encoding_tokens(val, &mut best) {
                return best;
            }
        }
        return best;
    }
    let mut stack_buf: [u8; STACK_ACCEPT_ENCODING_CAP] = [0u8; STACK_ACCEPT_ENCODING_CAP];
    let mut pos: usize = 0;
    let mut fits: bool = true;
    for (idx, value) in values.iter().enumerate() {
        let need: usize = value.len() + usize::from(idx > 0);
        if pos + need > STACK_ACCEPT_ENCODING_CAP {
            fits = false;
            break;
        }
        if idx > 0 {
            stack_buf[pos] = BYTE_COMMA;
            pos += 1;
        }
        stack_buf[pos..pos + value.len()].copy_from_slice(value.as_bytes());
        pos += value.len();
    }
    if fits {
        return from_utf8(&stack_buf[..pos])
            .ok()
            .and_then(Compress::from_accept_encoding);
    }
    let total_len: usize = values
        .iter()
        .map(|val: &String| val.len())
        .sum::<usize>()
        .saturating_add(values.len());
    let mut joined: String = String::with_capacity(total_len);
    for (idx, value) in values.iter().enumerate() {
        if idx > 0 {
            joined.push_str(COMMA);
        }
        joined.push_str(value);
    }
    Compress::from_accept_encoding(&joined)
}

/// Reports whether `bytes` is a syntactically valid strong RFC 9110 entity-tag (`"<etagc*>"`).
///
/// # Arguments
///
/// - `&[u8]` - Candidate response entity-tag bytes.
///
/// # Returns
///
/// - `bool` - `true` iff `bytes` matches `parse_entity_tag` as a complete strong entity-tag.
#[inline(always)]
fn is_valid_strong_etag(bytes: &[u8]) -> bool {
    let len: usize = bytes.len();
    if len < 2 || bytes[0] != BYTE_QUOTE || bytes[len - 1] != BYTE_QUOTE {
        return false;
    }
    for &byte in &bytes[1..len - 1] {
        if byte == BYTE_QUOTE || byte <= BYTE_CTL_LIMIT || byte == BYTE_DEL {
            return false;
        }
    }
    true
}

/// Trims leading and trailing HTTP optional whitespace (`SP` / `HTAB`) from `value`.
///
/// # Arguments
///
/// - `&str` - Raw header field value.
///
/// # Returns
///
/// - `&str` - Subslice stripped of HTTP optional whitespace only.
#[inline(always)]
fn trim_http_ows(value: &str) -> &str {
    let bytes: &[u8] = value.as_bytes();
    let mut start: usize = 0;
    let mut end: usize = bytes.len();
    while start < end && (bytes[start] == BYTE_SPACE || bytes[start] == BYTE_TAB) {
        start += 1;
    }
    while end > start && (bytes[end - 1] == BYTE_SPACE || bytes[end - 1] == BYTE_TAB) {
        end -= 1;
    }
    &value[start..end]
}

/// Evaluates `If-None-Match` against `etag` with a zero-allocation fast path for exact single-value matches.
///
/// # Arguments
///
/// - `&Request` - Incoming HTTP request.
/// - `&str` - Candidate response entity-tag.
///
/// # Returns
///
/// - `bool` - `true` when `If-None-Match` matches `etag`.
#[inline]
pub(crate) fn matches_if_none_match_fast(request: &Request, etag: &str) -> bool {
    let headers: &RequestHeaders = request.get_headers();
    if is_valid_strong_etag(etag.as_bytes())
        && let Some(values) = headers.get(IF_NONE_MATCH)
        && values.len() == 1
        && let Some(first) = values.front()
    {
        let trimmed: &str = trim_http_ows(first);
        if trimmed == VARY_WILDCARD || trimmed == etag {
            return true;
        }
    }
    request.matches_if_none_match(etag)
}

/// Reads a little-endian `u64` from `slice` starting at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice with at least `offset + 8` bytes.
/// - `usize` - Starting byte offset.
///
/// # Returns
///
/// - `u64` - Decoded little-endian 64-bit word.
#[inline(always)]
fn read_le_u64(slice: &[u8], offset: usize) -> u64 {
    let mut bytes: [u8; 8] = [0u8; 8];
    bytes.copy_from_slice(&slice[offset..offset + 8]);
    u64::from_le_bytes(bytes)
}

/// Computes the 128-bit product of `lhs` and `rhs` folded by XOR into 64 bits.
///
/// # Arguments
///
/// - `u64` - First 64-bit factor.
/// - `u64` - Second 64-bit factor.
///
/// # Returns
///
/// - `u64` - Folded 64-bit product.
#[inline(always)]
fn xxh3_mul128_fold64(lhs: u64, rhs: u64) -> u64 {
    let prod: u128 = (lhs as u128).wrapping_mul(rhs as u128);
    (prod as u64) ^ ((prod >> 64) as u64)
}

/// Applies the XXH3 64-bit finalization avalanche to `h`.
///
/// # Arguments
///
/// - `u64` - Input 64-bit accumulator.
///
/// # Returns
///
/// - `u64` - Avalanched 64-bit digest.
#[inline(always)]
fn xxh3_avalanche(mut h: u64) -> u64 {
    h ^= h >> 37;
    h = h.wrapping_mul(XXH3_PRIME_MX1);
    h ^ (h >> 32)
}

/// Mixes a 16-byte input chunk against a 16-byte secret window per XXH3.
///
/// # Arguments
///
/// - `&[u8]` - Input slice of at least 16 bytes.
/// - `&[u8]` - Secret slice of at least 16 bytes.
///
/// # Returns
///
/// - `u64` - Folded 64-bit mix output.
#[inline(always)]
fn xxh3_mix16b(input: &[u8], secret: &[u8]) -> u64 {
    let lo: u64 = read_le_u64(input, 0) ^ read_le_u64(secret, 0);
    let hi: u64 = read_le_u64(input, 8) ^ read_le_u64(secret, 8);
    xxh3_mul128_fold64(lo, hi)
}

/// Accumulates one 128-bit lane pair of an XXH3 64-byte stripe using ARM64 NEON intrinsics.
///
/// # Arguments
///
/// - `uint64x2_t` - Current two-lane 64-bit accumulator.
/// - `*const u8` - Pointer to 16 input bytes.
/// - `*const u8` - Pointer to 16 secret bytes.
///
/// # Returns
///
/// - `uint64x2_t` - Updated two-lane 64-bit accumulator.
#[cfg(target_arch = "aarch64")]
#[cfg(target_feature = "neon")]
#[cfg(target_endian = "little")]
#[inline(always)]
unsafe fn xxh3_neon_acc_pair(
    acc: uint64x2_t,
    stripe_ptr: *const u8,
    secret_ptr: *const u8,
) -> uint64x2_t {
    unsafe {
        let data_vec: uint64x2_t = vreinterpretq_u64_u8(vld1q_u8(stripe_ptr));
        let key_vec: uint64x2_t = vreinterpretq_u64_u8(vld1q_u8(secret_ptr));
        let data_key: uint32x4_t = vreinterpretq_u32_u64(veorq_u64(data_vec, key_vec));
        let data_key_lo: uint32x2_t = vmovn_u64(vreinterpretq_u64_u32(data_key));
        let data_key_hi: uint32x2_t = vshrn_n_u64::<32>(vreinterpretq_u64_u32(data_key));
        let data_swap: uint64x2_t = vextq_u64::<1>(data_vec, data_vec);
        let sum: uint64x2_t = vaddq_u64(acc, data_swap);
        vmlal_u32(sum, data_key_lo, data_key_hi)
    }
}

/// Scrambles one 128-bit lane pair of an XXH3 accumulator using ARM64 NEON intrinsics.
///
/// # Arguments
///
/// - `uint64x2_t` - Two-lane 64-bit accumulator.
/// - `*const u8` - Pointer to 16 secret tail bytes.
/// - `uint32x2_t` - Broadcast `XXH3_PRIME32_1` lane vector.
///
/// # Returns
///
/// - `uint64x2_t` - Scrambled two-lane 64-bit accumulator.
#[cfg(target_arch = "aarch64")]
#[cfg(target_feature = "neon")]
#[cfg(target_endian = "little")]
#[inline(always)]
unsafe fn xxh3_neon_scramble_pair(
    acc: uint64x2_t,
    secret_ptr: *const u8,
    prime: uint32x2_t,
) -> uint64x2_t {
    unsafe {
        let key_vec: uint64x2_t = vreinterpretq_u64_u8(vld1q_u8(secret_ptr));
        let mixed: uint64x2_t = veorq_u64(veorq_u64(acc, vshrq_n_u64::<47>(acc)), key_vec);
        let lo: uint32x2_t = vmovn_u64(mixed);
        let hi: uint32x2_t = vshrn_n_u64::<32>(mixed);
        let prod_hi: uint64x2_t = vshlq_n_u64::<32>(vmull_u32(hi, prime));
        vmlal_u32(prod_hi, lo, prime)
    }
}

/// Computes the exact 64-bit XXH3 digest for inputs longer than 240 bytes using register-resident ARM64 NEON.
///
/// # Arguments
///
/// - `&[u8]` - Input payload slice with `data.len() > 240`.
///
/// # Returns
///
/// - `u64` - Bit-exact 64-bit XXH3 digest.
#[cfg(target_arch = "aarch64")]
#[cfg(target_feature = "neon")]
#[cfg(target_endian = "little")]
#[inline]
fn xxh3_hash_long_neon(data: &[u8]) -> u64 {
    let len: usize = data.len();
    let mut acc: [u64; 8] = XXH3_INIT_ACC;
    unsafe {
        let mut a0: uint64x2_t = vld1q_u64(acc.as_ptr());
        let mut a1: uint64x2_t = vld1q_u64(acc.as_ptr().add(2));
        let mut a2: uint64x2_t = vld1q_u64(acc.as_ptr().add(4));
        let mut a3: uint64x2_t = vld1q_u64(acc.as_ptr().add(6));
        let prime: uint32x2_t = vdup_n_u32(XXH3_PRIME32_1 as u32);
        let secret_ptr: *const u8 = XXH3_DEFAULT_SECRET.as_ptr();
        let data_ptr: *const u8 = data.as_ptr();
        let nb_blocks: usize = (len - 1) / 1024;
        let mut n: usize = 0;
        while n < nb_blocks {
            let block_ptr: *const u8 = data_ptr.add(n * 1024);
            let mut s: usize = 0;
            while s < 16 {
                let sp: *const u8 = block_ptr.add(s * 64);
                let kp: *const u8 = secret_ptr.add(s * 8);
                a0 = xxh3_neon_acc_pair(a0, sp, kp);
                a1 = xxh3_neon_acc_pair(a1, sp.add(16), kp.add(16));
                a2 = xxh3_neon_acc_pair(a2, sp.add(32), kp.add(32));
                a3 = xxh3_neon_acc_pair(a3, sp.add(48), kp.add(48));
                s += 1;
            }
            let tail_kp: *const u8 = secret_ptr.add(128);
            a0 = xxh3_neon_scramble_pair(a0, tail_kp, prime);
            a1 = xxh3_neon_scramble_pair(a1, tail_kp.add(16), prime);
            a2 = xxh3_neon_scramble_pair(a2, tail_kp.add(32), prime);
            a3 = xxh3_neon_scramble_pair(a3, tail_kp.add(48), prime);
            n += 1;
        }
        let last_block_start: usize = nb_blocks * 1024;
        let nb_stripes: usize = ((len - 1) - last_block_start) / 64;
        let mut s: usize = 0;
        while s < nb_stripes {
            let sp: *const u8 = data_ptr.add(last_block_start + s * 64);
            let kp: *const u8 = secret_ptr.add(s * 8);
            a0 = xxh3_neon_acc_pair(a0, sp, kp);
            a1 = xxh3_neon_acc_pair(a1, sp.add(16), kp.add(16));
            a2 = xxh3_neon_acc_pair(a2, sp.add(32), kp.add(32));
            a3 = xxh3_neon_acc_pair(a3, sp.add(48), kp.add(48));
            s += 1;
        }
        let last_sp: *const u8 = data_ptr.add(len - 64);
        let last_kp: *const u8 = secret_ptr.add(121);
        a0 = xxh3_neon_acc_pair(a0, last_sp, last_kp);
        a1 = xxh3_neon_acc_pair(a1, last_sp.add(16), last_kp.add(16));
        a2 = xxh3_neon_acc_pair(a2, last_sp.add(32), last_kp.add(32));
        a3 = xxh3_neon_acc_pair(a3, last_sp.add(48), last_kp.add(48));
        vst1q_u64(acc.as_mut_ptr(), a0);
        vst1q_u64(acc.as_mut_ptr().add(2), a1);
        vst1q_u64(acc.as_mut_ptr().add(4), a2);
        vst1q_u64(acc.as_mut_ptr().add(6), a3);
    }
    xxh3_merge_accs(&acc, (len as u64).wrapping_mul(XXH3_PRIME64_1))
}

/// Accumulates one 64-byte stripe into the 8-lane XXH3 accumulator vector using scalar arithmetic.
///
/// # Arguments
///
/// - `&mut [u64; 8]` - Eight 64-bit accumulators.
/// - `&[u8]` - 64-byte input stripe slice.
/// - `&[u8]` - 64-byte secret window slice.
#[inline(always)]
fn xxh3_accumulate_512_scalar(acc: &mut [u64; 8], stripe: &[u8], secret: &[u8]) {
    let (s_words, _): (&[[u8; 8]], &[u8]) = stripe[..64].as_chunks::<8>();
    let (k_words, _): (&[[u8; 8]], &[u8]) = secret[..64].as_chunks::<8>();
    let mut i: usize = 0;
    while i < 8 {
        let d: u64 = u64::from_le_bytes(s_words[i]);
        let k: u64 = d ^ u64::from_le_bytes(k_words[i]);
        acc[i ^ 1] = acc[i ^ 1].wrapping_add(d);
        acc[i] = acc[i].wrapping_add((k & 0xFFFF_FFFF).wrapping_mul(k >> 32));
        i += 1;
    }
}

/// Computes the exact 64-bit XXH3 digest for inputs longer than 240 bytes using scalar fallback.
///
/// # Arguments
///
/// - `&[u8]` - Input payload slice with `data.len() > 240`.
///
/// # Returns
///
/// - `u64` - Bit-exact 64-bit XXH3 digest.
#[inline]
fn xxh3_hash_long_scalar(data: &[u8]) -> u64 {
    let len: usize = data.len();
    let mut acc: [u64; 8] = XXH3_INIT_ACC;
    let nb_blocks: usize = (len - 1) / 1024;
    let mut n: usize = 0;
    while n < nb_blocks {
        let block: &[u8] = &data[n * 1024..];
        let mut s: usize = 0;
        while s < 16 {
            xxh3_accumulate_512_scalar(&mut acc, &block[s * 64..], &XXH3_DEFAULT_SECRET[s * 8..]);
            s += 1;
        }
        let (k_words, _): (&[[u8; 8]], &[u8]) = XXH3_DEFAULT_SECRET[128..192].as_chunks::<8>();
        let mut i: usize = 0;
        while i < 8 {
            let v: u64 = (acc[i] ^ (acc[i] >> 47)) ^ u64::from_le_bytes(k_words[i]);
            acc[i] = v.wrapping_mul(XXH3_PRIME32_1);
            i += 1;
        }
        n += 1;
    }
    let last_block_start: usize = nb_blocks * 1024;
    let nb_stripes: usize = ((len - 1) - last_block_start) / 64;
    let mut s: usize = 0;
    while s < nb_stripes {
        xxh3_accumulate_512_scalar(
            &mut acc,
            &data[last_block_start + s * 64..],
            &XXH3_DEFAULT_SECRET[s * 8..],
        );
        s += 1;
    }
    xxh3_accumulate_512_scalar(&mut acc, &data[len - 64..], &XXH3_DEFAULT_SECRET[121..]);
    xxh3_merge_accs(&acc, (len as u64).wrapping_mul(XXH3_PRIME64_1))
}

/// Dispatches long-input XXH3 hashing to ARM64 NEON when available, falling back to scalar.
///
/// # Arguments
///
/// - `&[u8]` - Input payload slice with `data.len() > 240`.
///
/// # Returns
///
/// - `u64` - Bit-exact 64-bit XXH3 digest.
#[inline]
fn xxh3_hash_long(data: &[u8]) -> u64 {
    if USE_AARCH64_NEON {
        #[cfg(target_arch = "aarch64")]
        #[cfg(target_feature = "neon")]
        #[cfg(target_endian = "little")]
        return xxh3_hash_long_neon(data);
    }
    xxh3_hash_long_scalar(data)
}

/// Folds the 8-lane XXH3 accumulator vector into the final 64-bit digest.
///
/// # Arguments
///
/// - `&[u64; 8]` - Finalized 8-lane accumulators.
/// - `u64` - Initial merge accumulator (`len * PRIME64_1`).
///
/// # Returns
///
/// - `u64` - Avalanched 64-bit XXH3 digest.
#[inline(always)]
fn xxh3_merge_accs(acc: &[u64; 8], mut result: u64) -> u64 {
    let mut k: usize = 0;
    while k < 4 {
        let lo: u64 = acc[k * 2] ^ read_le_u64(&XXH3_DEFAULT_SECRET, 11 + k * 16);
        let hi: u64 = acc[k * 2 + 1] ^ read_le_u64(&XXH3_DEFAULT_SECRET, 11 + k * 16 + 8);
        result = result.wrapping_add(xxh3_mul128_fold64(lo, hi));
        k += 1;
    }
    xxh3_avalanche(result)
}