/* AI-assisted (Claude), human review required.
   lemire8batch.c — the same parsers inlined into a loop over many strings (no call per string), so the compiler can
   keep everything in registers and, for branch-free code, vectorize.  Interface:
     batch(const uint32_t *words, const uint8_t *lens, size_t n, uint8_t *val, uint8_t *ok)
   words[i] is the 4-byte slot of string i.  Each batch is checked against the naive parser before timing.
   On ARM with the dot-product extension there is also a hand-written NEON parser (b_neon_udot): 16 strings per
   iteration, four per 16-byte register, digits tested bytewise, the value formed by one UDOT against length-selected weights
   (100,10,1 / 10,1 / 1) looked up with TBL, so no shift, multiply-high or byte-swap range trick is needed.
   "-x" mode checks every batch parser exhaustively: all 2^32 words at lengths 0..8 and 255, against p_ref,
   on all cores, so the compiler-vectorized loops and the NEON code are checked as compiled.
   Build: cc -O3 -mcpu=native -pthread -o lemire8batch lemire8batch.c   Run: ./lemire8batch [count] | -x */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <stdatomic.h>
#include <unistd.h>
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
#include <arm_neon.h>
#define HAVE_UDOT 1
#endif
#include "lemire8.h"

#define BATCH(name, expr)                                                                                     \
    static __attribute__((noinline)) void b_##name(const uint32_t *w, const uint8_t *L, size_t n, uint8_t *val, \
                                                   uint8_t *ok) {                                             \
        for (size_t i = 0; i < n; i++) { uint32_t r = expr(w[i], L[i]); val[i] = (uint8_t)r; ok[i] = (uint8_t)(r >> 8); } }
BATCH(ref, p_ref) BATCH(fastswar, p_fastswar) BATCH(fastswar_bl, p_fastswar_bl) BATCH(bob, p_bob)
BATCH(bob_safe, p_bob_safe) BATCH(mulfirst, p_mulfirst) BATCH(so, p_so) BATCH(so32, p_so32)

#ifdef HAVE_UDOT
/* four strings: x holds their 4-byte slots, lb each string's length repeated in its 4 bytes */
static inline void udot4(uint8x16_t x, uint8x16_t lb, uint8x16_t WT, uint8x16_t POS, uint32x4_t *num, uint32x4_t *good) {
    uint8x16_t d = vsubq_u8(x, vdupq_n_u8('0'));
    uint8x16_t bad = vandq_u8(vcgtq_u8(d, vdupq_n_u8(9)), vcltq_u8(POS, lb));      /* non-digit inside string */
    uint8x16_t wts = vqtbl1q_u8(WT, vaddq_u8(vshlq_n_u8(lb, 2), POS));            /* index >= 16 gives 0 */
    *num = vdotq_u32(vdupq_n_u32(0), d, wts);
    uint32x4_t okl = vreinterpretq_u32_u8(vcltq_u8(vsubq_u8(lb, vdupq_n_u8(1)), vdupq_n_u8(3)));
    *good = vandq_u32(vandq_u32(okl, vceqzq_u32(vreinterpretq_u32_u8(bad))), vcltq_u32(*num, vdupq_n_u32(256)));
}
static __attribute__((noinline)) void b_neon_udot(const uint32_t *w, const uint8_t *L, size_t n, uint8_t *val,
                                                  uint8_t *ok) {
    static const uint8_t wt[16] = {0, 0, 0, 0, 1, 0, 0, 0, 10, 1, 0, 0, 100, 10, 1, 0};   /* weights by len 0..3 */
    static const uint8_t pos[16] = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3};
    static const uint8_t sp[4][16] = {{0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3},
                                      {4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7},
                                      {8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11},
                                      {12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15}};
    const uint8x16_t WT = vld1q_u8(wt), POS = vld1q_u8(pos);
    const uint8x16_t S0 = vld1q_u8(sp[0]), S1 = vld1q_u8(sp[1]), S2 = vld1q_u8(sp[2]), S3 = vld1q_u8(sp[3]);
    size_t i = 0;
    for (; i + 16 <= n; i += 16) {                                                 /* 16 strings per iteration */
        const uint8_t *p = (const uint8_t *)(w + i);
        uint8x16_t l16 = vld1q_u8(L + i);
        uint32x4_t n0, n1, n2, n3, g0, g1, g2, g3;
        udot4(vld1q_u8(p), vqtbl1q_u8(l16, S0), WT, POS, &n0, &g0);
        udot4(vld1q_u8(p + 16), vqtbl1q_u8(l16, S1), WT, POS, &n1, &g1);
        udot4(vld1q_u8(p + 32), vqtbl1q_u8(l16, S2), WT, POS, &n2, &g2);
        udot4(vld1q_u8(p + 48), vqtbl1q_u8(l16, S3), WT, POS, &n3, &g3);
        uint16x8_t na = vcombine_u16(vmovn_u32(n0), vmovn_u32(n1)), nb = vcombine_u16(vmovn_u32(n2), vmovn_u32(n3));
        uint16x8_t ga = vcombine_u16(vmovn_u32(g0), vmovn_u32(g1)), gb = vcombine_u16(vmovn_u32(g2), vmovn_u32(g3));
        vst1q_u8(val + i, vcombine_u8(vmovn_u16(na), vmovn_u16(nb)));
        vst1q_u8(ok + i, vshrq_n_u8(vcombine_u8(vmovn_u16(ga), vmovn_u16(gb)), 7));
    }
    for (; i < n; i++) { uint32_t r = p_fastswar_bl(w[i], L[i]); val[i] = (uint8_t)r; ok[i] = (uint8_t)(r >> 8); }
}
#endif

typedef void (*bf)(const uint32_t *, const uint8_t *, size_t, uint8_t *, uint8_t *);
static const struct { const char *name; bf f; } B[] = {
    {"naive (inlined loop)", b_ref}, {"fastswar", b_fastswar}, {"fastswar_bl (branch-free)", b_fastswar_bl},
    {"bob (masked shift)", b_bob}, {"bob_safe", b_bob_safe}, {"mulfirst", b_mulfirst},
    {"so (superopt, 64-bit mul)", b_so}, {"so32 (superopt, 32-bit)", b_so32},
#ifdef HAVE_UDOT
    {"neon_udot (hand-written)", b_neon_udot},
#endif
};
#define NB (int)(sizeof B / sizeof B[0])

static uint64_t rs = 0x9E3779B97F4A7C15ull;
static uint32_t rnd(void) { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return (uint32_t)(rs >> 16); }
static void fill(uint32_t *w, uint8_t *lens, size_t n, int mixed) {   /* same mix as lemire8bench.c */
    for (size_t i = 0; i < n; i++) {
        char s[8]; for (int k = 0; k < 8; k++) s[k] = (char)rnd();
        int kind = mixed ? (int)(rnd() % 8) : 0; char t[8];
        if (kind < 4) { lens[i] = (uint8_t)snprintf(t, 8, "%u", rnd() % 256); memcpy(s, t, lens[i]); }
        else if (kind == 4) { lens[i] = (uint8_t)snprintf(t, 8, "%u", 256 + rnd() % 744); memcpy(s, t, 3); }
        else if (kind == 5) { lens[i] = (uint8_t)(1 + rnd() % 3); s[rnd() % lens[i]] = (char)("/:a -"[rnd() % 5]); }
        else if (kind == 6) { lens[i] = 0; }
        else { lens[i] = 4; for (int k = 0; k < 4; k++) s[k] = (char)('0' + rnd() % 10); }
        memcpy(&w[i], s, 4);
    }
}
static double now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + 1e-9 * t.tv_nsec; }

/* exhaustive mode */
static _Atomic uint64_t next_blk; static _Atomic int fails; static uint8_t xlen;
#define XBLK 4096u
static void *xworker(void *arg) {
    (void)arg; uint32_t w[XBLK]; uint8_t L[XBLK], v[XBLK], o[XBLK], rv[XBLK], ro[XBLK];
    memset(L, xlen, sizeof L);
    for (;;) {
        uint64_t b = atomic_fetch_add(&next_blk, 1); if (b >= (1ull << 32) / XBLK) return 0;
        for (uint32_t k = 0; k < XBLK; k++) { w[k] = (uint32_t)(b * XBLK + k); uint32_t r = p_ref(w[k], xlen); rv[k] = (uint8_t)r; ro[k] = (uint8_t)(r >> 8); }
        for (int f = 1; f < NB; f++) {
            B[f].f(w, L, XBLK, v, o);
            for (uint32_t k = 0; k < XBLK; k++)
                if (o[k] != ro[k] || (o[k] && v[k] != rv[k])) {
                    if (atomic_fetch_add(&fails, 1) < 5) printf("  MISMATCH %s len %u x 0x%08x\n", B[f].name, xlen, w[k]);
                    break;
                }
        }
    }
}
static int exhaustive(void) {
    int nt = (int)sysconf(_SC_NPROCESSORS_ONLN); if (nt < 1) nt = 1; if (nt > 256) nt = 256;
    pthread_t th[256]; const uint8_t lens[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 255};
    for (unsigned j = 0; j < sizeof lens; j++) {
        xlen = lens[j]; atomic_store(&next_blk, 0); double t0 = now();
        for (int t = 0; t < nt; t++) pthread_create(&th[t], 0, xworker, 0);
        for (int t = 0; t < nt; t++) pthread_join(th[t], 0);
        printf("len %3u: all 2^32 words, %d batch parsers vs p_ref, %d threads, %.2f s, failures so far %d\n", xlen, NB - 1, nt,
               now() - t0, atomic_load(&fails));
    }
    printf(atomic_load(&fails) ? "EXHAUSTIVE: FAIL\n" : "EXHAUSTIVE: all batch parsers identical to p_ref\n");
    return atomic_load(&fails) != 0;
}

int main(int argc, char **argv) {
    if (argc > 1 && !strcmp(argv[1], "-x")) return exhaustive();
    size_t n = argc > 1 ? strtoul(argv[1], 0, 0) : 10000000, chunk = 4096;   /* chunks stay in L1 */
    uint32_t *w = malloc(4 * n); uint8_t *L = malloc(n), *v0 = malloc(n), *o0 = malloc(n), *v = malloc(n), *o = malloc(n);
    for (int mixed = 0; mixed < 2; mixed++) {
        fill(w, L, n, mixed); b_ref(w, L, n, v0, o0);
        size_t nv = 0; for (size_t i = 0; i < n; i++) nv += o0[i];
        printf("%s input: %zu strings, %.1f%% valid (batches of %zu)\n", mixed ? "mixed" : "valid", n, 100.0 * nv / n, chunk);
        for (int b = 0; b < NB; b++) {
            B[b].f(w, L, n, v, o);
            for (size_t i = 0; i < n; i++)
                if (o[i] != o0[i] || (o[i] && v[i] != v0[i])) { printf("MISMATCH %s at %zu\n", B[b].name, i); return 1; }
            double best = 1e9;
            for (int rep = 0; rep < 5; rep++) {
                double t0 = now();
                for (size_t i = 0; i < n; i += chunk) { size_t m = n - i < chunk ? n - i : chunk; B[b].f(w + i, L + i, m, v + i, o + i); }
                double t = now() - t0; if (t < best) best = t;
            }
            printf("  %-28s %6.3f ns/parse  %8.1f M parses/s\n", B[b].name, 1e9 * best / n, n / best / 1e6);
        }
    }
    return 0;
}
