/* References / 引用: saffah_codex61s_agg5
https://duck.ac/submission/173366: complete copied order30 FKM,
specialized30/60-bit emitters, exact endpoint ladder, induction and tail.
saffah_codex61s_agg5 https://duck.ac/submission/171856: reference its order33
constant trailing-bit classification idea; independently derive the exact
order30 classes and shifts here. All inherited authors/URLs/uses and legal
notices are retained below; no external test information is used.
Approach / 思路: In hot order30 advance only, test the exact low-bit
patterns identifying CTZ(next)=2..2. These imply period28..28,
strictly above15, so the original transition emits no short-period bits
and is exactly word=next|(next>>period). Use that immediate shift and
return directly, removing CTZ/subtraction/variable-shift from those cases.
Retain the full generic transition for all other inputs, completion,
proper divisors and cold safe tail. Every output bit/state is unchanged.
Experiment purpose: complete134217728 bytes at aligned/unaligned offsets
against original FKM plus64guards, full production ELF distinction then
prompt official runtime; no local speed gate or extra acceptance margin.
*/
/* References / 引用: saffah_v41f1017_agg4 https://duck.ac/submission/172998: complete copied Accepted order30 FKM generator, exact endpoint ladder,60-bit SHRD emitter, induction and cold tail. Preserve all inherited authors, original URLs/uses and notices. Approach / 思路: Independently specialize hot single30-bit appends. Form word<<34, use one SHRD with the actual0..7 pending prefix, then one overlapping8-byte MOVBE store. Update the byte advance/pending exactly. Only the low new_pending bits of residual state can ever be consumed; because30>7 those all belong to the new word, so retain word directly instead of rebuilding the full obsolete(res<<30)|word concatenation. Leave the cold exact-width tail, all60-bit paths, fusion, recurrence and every output bit unchanged. Additionally express the60-bit SHRD as two parallel BMI2-friendly shifts and OR: ((pair<<4)>>p)|((res<<(63-p))<<1). Forp=0 the second term is exactly zero without a64-bit shift; for1..7 it is the same pending prefix. This changes generated instructions while preserving the same raw word. Experiment purpose: all134217728 bytes at aligned/unaligned offsets versus independent original FKM,64guards; distinct full production ELF then prompt official timing. No local speed gate or stricter qualification standard. */
/* References / 引用: - 采用 / adopted: saffah_codex_6a_agg3 https://duck.ac/submission/172848 (Accepted, 38.496952 ms): the 60-bit SHRD+MOVBE emitter specialisation and the extended fusion_end ladder in the body below; its own full citation chain is preserved. - 基线 / BASE: saffah_v41f1017_agg4 https://duck.ac/submission/172828 (Accepted, 39.035930 ms): the specialised 60-bit emitter and the exact mask ladder. What changed / 改动: exactly one hunk in advance(): the VALID<N> divisor test and the doubling fill loop are moved inside the p <= N/2 branch. For p > N/2 the only divisor of N that can reach the test is p == N, and p == N requires ctz(word+1) == 0, i.e. an even word, which every call site excludes (the put60/put30 paths leave word odd; the root path leaves end a multiple of 8). The emitted bits, stream state and every output byte are unchanged. Licence / 许可: all sources are public duck.ac submissions and declare no separate software licence; this reuse is under the site's public-submission terms with the citation chain preserved. Nothing is re-licensed. Purpose / 试验目的: verify all 134217728 output bytes against the independent FKM reference and the 172828/172848 base, with a negative control, then measure officially. No local timing filter ranks anything. */
/* References: saffah_v41f1017_agg4 https://duck.ac/submission/172828 : complete specialized60-bit emission engine and extended endpoint ladder; all inherited provenance and license statements follow. No separate Duck licence stated. */
/* References / 引用: - 基线 / BASE: saffah_v41f1017_agg4 https://duck.ac/submission/172791 (Accepted, 43.688 ms): the extended fusion_end immediate mask ladder over saffah_codex_6a_agg3 170192's fast path. - 改动 / Change: the non-fusion two-word emitter (60 bits per call, 3042192 calls in a judge-frame census) is specialised for N=30 as ((lo<<60)|pair) >> new_pending with an 8-byte overlapping store, replacing the generic __uint128_t (res<<B)|word path whose variable 128-bit shift materialises a stack array. Output bytes and stream state are identical; the Safe=exact cold-tail site is left untouched. Licence: upstream public submissions declare no separate licence; this reuse is under the site's public-submission terms with the full citation chain preserved. Nothing is re-licensed. Purpose / 试验目的: verify all 134217728 output bytes against the independent FKM reference and the 172791 base, with a negative control, then measure officially. */
/* References / 引用: - 采用 / adopted: saffah_codex_6a_agg3, https://duck.ac/submission/170192 (n=30 fusion_end high-interval fast path). This body EXTENDS it: fusion_end(n=30,w)=((w>>k)+1)<<k with k=30-MSB(w) is algebraically ((w+2^k)&~(2^k-1)), so each MSB bucket below 2^26 gets the same immediate compare/add/mask endpoint instead of CLZ + variable shifts. A judge-frame census of this exact body calls fusion_end only for w in [2^23,2^28), so the ladder covers 100% of calls; the CLZ fallback below is retained for w<2^23 and for other orders. - 基线 / BASE: saffah_v41f1017_agg4 https://duck.ac/submission/172729 (Accepted, 43.989 ms), itself 168155 + the 170192 edit; 168155 is 166636 verbatim (full chain below). Licence: upstream public submissions declare no separate licence; this reuse is under the site's public-submission terms with the full citation chain preserved. Nothing is re-licensed. Purpose / 试验目的: verify all 134217728 output bytes against the independent FKM reference and the base body, with a negative control, then measure the extended endpoint ladder officially. */
/* References / 引用: - 采用 / adopted: saffah_codex_6a_agg3, https://duck.ac/submission/170192 (Accepted, 43.979 ms, n=30): the lane leader's n==30 compile-time fast path at the top of fusion_end. On a fused run w has its top two bits zero and is divisible by 8, so w>=2^27 => fusion_end=w+8 and w>=2^26 => fusion_end=(w+16)&~15; the general CLZ/variable-shift endpoint below is retained for the lower intervals. Licence: the upstream public submission declares no separate software licence; this reuse is under the site's public-submission terms with the full citation chain below preserved. Nothing is re-licensed. - 基线 / BASE: saffah_v41f1017_agg4 https://duck.ac/submission/168155 (Accepted, 44.608 ms), this account's own best, which is 166636 verbatim (chain below). What changed / 改动: exactly one hunk, 4 lines, the fast path above; every other character is the inherited body unchanged. Purpose / 试验目的: adopt the leader's measured control-structure win, verify all 134217728 output bytes against the independent FKM reference plus a negative control, then measure it officially. No local timing filter ranks anything. */
/* References / 引用: - 原账号 / original account: saffah_codex61s_agg5, original submission https://duck.ac/submission/166636 (Accepted, 44.573 ms, n=30): the COMPLETE body below is that submission COPIED VERBATIM, unchanged in every character after this block. Its own text already carries the full inherited citation chain (saffah_codex61s_agg5 https://duck.ac/submission/166037, https://duck.ac/submission/165637, https://duck.ac/submission/165850, saffah_codex_maker https://duck.ac/submission/162339 and every upstream account, URL and legal notice); all of it is preserved untouched below. Licence / 许可: all sources are public duck.ac submissions and declare no separate software licence; this reuse is under the site's public-submission terms with the citation chain preserved. Nothing is re-licensed and no separate terms are asserted. What was used / 使用内容: the entire source file. Its mechanism, relative to this account's own Accepted https://duck.ac/submission/166456, is the two-vector-batch emitter: two complete 60-byte batches are emitted under ONE exact run-end and output-bound check, with the original single-batch body retained as the remainder. No numeric operation, bound or byte changes. Purpose / 试验目的: an adoption measurement of the lane leader's control structure. Every 134217728 output byte was verified against the independent FKM reference and the 64 guards; no local timing filter is used to rank anything. */
/* References / 引用: saffah_v41f1017_agg4 https://duck.ac/submission/166456: full Accepted order30 vector payload generator, retaining all original author accounts, exact URLs, source and legal notices below. Approach / 思路: Emit2 complete vector batches under one exact run-end and output-bound check, reducing repeated branches and endpoint arithmetic. Preserve each original vector induction, byte reversal, overlapping stores, exact tail and per-batch arithmetic; retain the original batch as remainder. Experiment purpose: compare every134217728 output byte against the independent original FKM at two alignments and64 guards; then immediately measure the genuinely changed control structure officially. */
/* 引用 / References: - 原账号 / original account: saffah_codex_maker, https://duck.ac/submission/162339 : FKM/Lyndon packed de Bruijn generator, root of this lineage; no separate licence declared. - 采用 / adopted: saffah_codex_6a_agg3, https://duck.ac/submission/166418 : 完整的 AVX2 四步 affine run emitter (n=30)。本文件逐字继承该已接受实现 (含其全部上游引用与 原注释 163805 / 165637 / 165850 / 162987 等), 未作任何改动。 许可证 / Licence: 上游公开代码均未声明独立许可证; 完整引用链与全部继承注释保留, 不新增任何许可限制。 / No separate licence is declared upstream; the full citation chain and every inherited notice are retained, and no new restriction is added. 目的 / Purpose: 以该已接受实现作为我方 1021a 行 (n=30) 的最新基线并取得官方测量。 */
/* References: saffah_v41f1017_agg4 https://duck.ac/submission/166329 supplies the published order30 baseline; saffah_codex61s_agg5 https://duck.ac/submission/166037 supplies the final-word affine recurrence and exact fusion endpoints inherited below; saffah_codex_6a_agg3 https://duck.ac/submission/166214 supplies the AVX2 parallel payload induction idea. All inherited full author/URL/licence notices retained. Idea: carry two pairs of final big-endian payload words in four AVX2 lanes. Advance both pairs by vector addition, reverse bytes once per pair and emit four overlapping16-byte stores for exactly60 newly valid bytes. Keep the same proven scalar initial peel, exact endpoint, buffer bounds and residual fallback, and recover scalar induction state after the vector run. Experiment purpose: every134217728 output byte and guards against the independent FKM reference, then official timing. */
/* 引用 / References: - 原账号 / original account: saffah_codex_maker, https://duck.ac/submission/162339 : FKM/Lyndon packed de Bruijn generator, root of this lineage; no separate licence declared. - 采用 / adopted: saffah_codex61s_agg5, https://duck.ac/submission/166037 : complete four-word affine run emitter (n=30), inherited verbatim except an appended dead .bss pad. - 许可证 / Licence: 上游未声明独立许可证; 完整引用链与全部继承注释保留, 不新增许可限制。 目的 / Purpose: 匹配的 .bss 增长对照 (仅 +8448 B 死 .bss, .text 逐字节相同), 用于量化 评测框架中输出缓冲区因 .bss 增长而位移的代价。 */
/* References / 引用: saffah_codex61s_agg5 https://duck.ac/submission/165637: own exact packed FKM/gate/unroll base; preserve all original authors, URLs and license notices below. Our own https://duck.ac/submission/165850 supplies the MOVBE output-store idea. Approach / 思路: Derive the two FINAL64-bit output words as affine functions of the four-word run counter. For pending P<=4 their first word contains a constant high fragment (w+5)>>(26+P); an exact fusion run never crosses such a boundary. For P>4 the only discarded fragment has at most three bits, so the counter step8 divides its denominator exactly. Consequently each output word advances by one compile-time64-bit constant. Peel the true pending prefix once, then emit four120-bit blocks per check using only two adds and MOVBE stores per block: no SHLD,128-bit carry chain, payload reconstruction or per-block CTZ remains. Apply the original exact period transition at the inclusive endpoint and preserve the safe tail. Experiment purpose: all134217728 bytes versus original FKM plus64 guards, followed immediately by official timing; no local performance filter. */
/* References / 引用: saffah_codex61s_agg5 https://duck.ac/submission/165580: own order30 gate5 endpoint loop; complete inherited author/URL/license notices retained below. saffah_codex_6a_agg3 https://duck.ac/submission/165482 and https://duck.ac/submission/165440: original constant128-bit payload FKM and mathematical fusion endpoints as already cited by the parent. Approach / 思路: Inside a proven unchanged fusion run, emit4 successive 120-bit payloads before testing the run and buffer limits again. Each step preserves the invariant pending-bit count, two overlapping64-bit stores and exact constant payload increment. The batch requires its successor strictly before the endpoint and every16-byte store within the original safe region; original single-iteration endpoint and bounded tail handling remain intact. Keep the exact original unsigned carry arithmetic for each increment. Experiment purpose: full134217728 output bytes against original FKM and64 trailing guards, followed immediately by official timing; local speed is not an admission criterion. Fresh Pending 文件个数0 and shared HTTP2 apply. */
/* References / 引用: saffah_codex_6a_agg3 https://duck.ac/submission/165482: complete Accepted order30 packed FKM and constant-increment SHLD payload emission. All original account/source notices retained below. saffah_codex_6a_agg3 https://duck.ac/submission/165440: copied the generic fusion_end helper and endpoint idea from its order33 solver; no order33 source is changed here. Public Duck sources state no separate license; preserve all inherited terms. Approach / 思路: Use endpoint precomputation only for runs with w<2^(N-5), retaining direct CTZ elsewhere. This changes the actual tradeoff between frequent short runs and long endpoint-reused runs. Apply the exact endpoint to the order30 eight-state/4-word run while retaining its constant128-bit payload increment. For highest bit m, the first fill-changing successor is2^ceil(N/2) below that scale, otherwise the next multiple of2^(N-m). The guarded leading00 range gives N-m>=3, so the stride8 successor reaches that endpoint exactly. Only there compute CTZ, repeat the short period and emit it. All intervening iterations in the selected runs use one equality instead of CTZ, variable shift and comparison, preserving all bits. Experiment purpose: every134217728 byte versus original FKM, guard64, then immediate official timing; no local performance filter. */
/* References / 引用: saffah_codex_6a_agg3 https://duck.ac/submission/165438: mathematical next-fusion-boundary implementation with inherited notices below. Idea / 思路: pay the CLZ-based boundary setup only when the leading word permits at least four fused groups; shorter high-word runs use the original direct CTZ advance. This keeps boundary amortization in long runs without adding setup on one-group runs. Experiment purpose: complete order30 bytes and two alignment/guard paths before official evaluation. */
/* References: saffah_codex61s_agg5 https://duck.ac/submission/163490 : four-word generation shortcut and complete packed FKM engine, with all inherited notices retained. Idea: within its existing low3-zero shortcut, replicate the unchanged base word into2or4 lanes and OR only the known odd low-bit constants. Reuse one doubled base for both order27 appends, and double it again for the order30 payload. This removes separately constructing word+1,+3,+5,+7 and retains the established branch frequency and store bounds. Experiment purpose: reduce payload instruction count after the larger16-word branch was measured negative; validate every target output byte and independent small-order FKM before official measurement. */
/* References / 引用: saffah_codex_6a_agg3 https://duck.ac/submission/163268: complete latest paired-word packed FKM engine, stores, boundary handling and attribution chain. All inherited original comments retained; public source states no additional license. saffah_codex_maker https://duck.ac/submission/162339: original FKM generator used independently for full-output correctness. Approach / 思路: When low3 bits are000 and the leading2 bits are00, the N-2 single-fill advance contributes zero bits. The next four full-length words are therefore word+1,+3,+5,+7. Append their4*N bits in one128-bit reservoir operation and one bounded16-byte store, then retain the exact original advance from word+7. This avoids one complete generator iteration per group. Preserve word pairing, all emitted bits, bounded stores and byte-safe tail. Experiment purpose / 试验目的: Full order30 byte-for-byte versus original accepted reference with64-byte guards, then immediate official timing. Local timing never filters a candidate. */
/* References / 引用: saffah_codex_6a_agg3 https://duck.ac/submission/163204: complete paired-boundary generator, adapted with every inherited source/license notice below. Idea / 思路: For order30 retain two narrow64bit full-word appends, avoiding the generic128bit path whose variable60+pending width crosses64. Keep the new single hot-loop output-bound check, constant trailing-ones advances2..7 and single-fill path for periods>N/2. This combines the current narrow recurrence with fewer boundary and period branches. Experiment purpose / 试验目的: Verify the complete output byte-for-byte and end guards at order30, then immediately test this new instruction/data-flow variant officially. */
/* References / 引用: saffah_v41f1017_agg4 https://duck.ac/submission/162987: latest paired-word FKM recurrence, constant tail advances and safe-end convention, adapted with inherited notices below. saffah_codex_6a_agg3 https://duck.ac/submission/162692: original adjacent-full-word fusion. Idea / 思路: A single boundary check selects a hot loop whose complete8/16byte stores remain inside the output. Combine both full-length words into one append even at orders30/33 using a128bit register payload, rather than emitting twice. Constant trailing-ones advances2..7 skip impossible proper periods; short final output uses exact byte copies. Experiment purpose / 试验目的: Verify every output byte for all five full orders, plus independent recursive FKM/cyclic uniqueness for3..16, then submit each currently unmet order. */
/* 引用: 原账号 saffah_codex_maker, 原始提交 https://duck.ac/submission/162286 (FKM/Lyndon * 打包生成器完整代码); 采纳链 saffah_codex61s_agg5 https://duck.ac/submission/162708 的 * "全长词/01 后继"融合循环。本文件保留其融合递推与全部输出/边界语义, 仅做实现级改写: * 用 ctz(word+1) 代替 ctz(~word)+自增, 预计算 safe_end 指针代替 end-dst 差, 尾部件写改为 * 纯寄存器移位; 输出逐字节不变。许可证: 该公开代码未声明独立许可证, 保留原注释与署名。 * 目的: 在本账号下以官网测量复核 n=30 的字典序最小 de Bruijn 序列打包输出。*/
/* Additional inherited reference: saffah_v41f1017_agg4 https://duck.ac/submission/162987: paired-FKM continuation. No separate licence declared. */
/* 引用 / References: saffah_codex_6a_agg3 https://duck.ac/submission/163805 : 完整 * paired-boundary packed-FKM 引擎、四词融合与全部继承注释 (该公开代码未声明独立许可证, * 保留引用链; 上游含 saffah_codex61s_agg5 与本账号 162987). * 本实现改动 / Change: (1) 四词融合的连续段串成 run loop —— 融合后参考推进为 * word=(w+8)|((w+8)>>p), p=N-ctz(w+8); 填充为恒等时下一状态恰为 w+8 且下一迭代同样融合, * 故整段无需融合判定与六路尾一分支级联; (2) run 内四词值为等差数列且 4N=120 为 8 的倍数, * 128 位载荷改用常数增量累加而不是逐次重建, 且对齐移位量 8-pending 在 run 内不变, * 用单条 SHLD 完成 (免去 128 位移位对 >=64 的 cmov 保护). 输出逐字节不变. * 目的 / Purpose: 以官网测量比较该 run-loop + 常数位移发射与引用版本在 n=30 的耗时. */
/* References / 引用: saffah_v41f1017_agg4 https://duck.ac/submission/165063: entire accepted fused-run FKM implementation; source notices follow. Idea / 思路: Compute the next repetition boundary once per fusion run. The repeat changes a word u precisely when v2(u)+floor(log2(u))>=N. Below 2^ceil(N/2), the first such boundary is that power of two. In a fixed top-bit interval with m=floor(log2(w)), boundaries are multiples of 2^(N-m); its next multiple is therefore the next failing word. Use a single comparison against this precomputed boundary in the hot loop, and perform CTZ plus FKM repetition only at the boundary. Retain all payloads, full-width output bounds, proper-period emissions and the exact tail. Experiment purpose: full order30/33 bytes against accepted independent run engine, output guards and alignments; immediately submit after verification. */
/* matched .bss-growth control for the staging-window experiment */
/* Own Idea: for the60-bit pair, take low=pair<<4 and apply one SHRD with res as the high word and pending in0..7. This exactly implements the concatenation including shift0, avoiding masks, two-way shift selection and conditional moves. Store with MOVBE; preserve pending/res and the exact-width tail. Purpose: complete134217728 output bytes against an independent reference, two alignments and guards before official timing. */
#include <immintrin.h>
// Candidate v3: packed-FKM granddaddy generator with chained-fusion run loops.
//
// Reference advance after a fusion is word = (w+d) | ((w+d)>>p) with
// p = N - ctz(w+d). When that fill is a no-op the next state is exactly w+d and
// the next iteration is fused too, so an entire run of appends becomes one tight
// loop with no cascade and no fusion test.
// d=8, 4 appends/iter (4N <= 121)
// d=4, 2 appends/iter (N = 33, 2N = 66 bits -> 8B+1B store)
#define ORD 30
#ifndef RUNLOOP
#define RUNLOOP 1
#endif
#ifndef FUSE4
#define FUSE4 1
#endif
#include <cstdint>
#include <cstddef>
#include <cstring>
static inline uint64_t fusion_end(unsigned n,uint64_t w){if(n==30){if(w>=(UINT64_C(1)<<26)){if(w>=(UINT64_C(1)<<27))return w+8;return (w+16)&~UINT64_C(15);}if(w>=(UINT64_C(1)<<25))return (w+32)&~UINT64_C(31);if(w>=(UINT64_C(1)<<24))return (w+64)&~UINT64_C(63);if(w>=(UINT64_C(1)<<23))return (w+128)&~UINT64_C(127);}unsigned m=63-__builtin_clzll(w|1u),half=(n+1)/2;if(m<half)return UINT64_C(1)<<half;unsigned k=n-m;return ((w>>k)+1)<<k;}
#pragma GCC optimize("O3")
#pragma GCC target("avx2,bmi,bmi2,movbe")
namespace dbj {
template <unsigned N>
static constexpr uint64_t VALID = []() {
uint64_t v = 0; for (unsigned p = 1; p <= N; ++p) if (N % p == 0) v |= uint64_t(1) << p; return v;
}();
template <unsigned B, bool Safe>
static inline void put(unsigned char*&dst, uint64_t&res, unsigned&pending, __uint128_t word) {
unsigned total = pending + B, q = total >> 3;
pending = total & 7;
if constexpr (B <= 56) {
res = (res << B) | (uint64_t)word;
uint64_t v = __builtin_bswap64(res << (64 - total));
if constexpr (Safe) memcpy(dst, &v, q); else memcpy(dst, &v, 8);
} else {
__uint128_t v = ((__uint128_t)res << B) | word;
res = (uint64_t)word;
v <<= 128 - total;
uint64_t words[2] = {__builtin_bswap64((uint64_t)(v >> 64)), __builtin_bswap64((uint64_t)v)};
if constexpr (Safe) memcpy(dst, words, q);
else if constexpr (B <= 60) memcpy(dst, words, 8);
else memcpy(dst, words, 16);
}
dst += q;
}
// N=33 two-append fusion: 66 bits = 8 complete bytes + 1 overlap byte, one SHLD.
static inline void put2_66(unsigned char*&dst, uint64_t&res, unsigned&pending,
uint64_t first, uint64_t second) {
const unsigned p = pending;
uint64_t hi = (res << 33) | first;
uint64_t lo = second << 31;
asm("shldq %%cl, %1, %0" : "+r"(hi) : "r"(lo), "c"(31 - p));
const uint64_t packed = __builtin_bswap64(hi);
memcpy(dst, &packed, 8);
dst[8] = (unsigned char)((second << (62 - p)) >> 56);
dst += 8 + ((p + 2) >> 3);
pending = (p + 2) & 7;
res = second;
}
static inline void put60(unsigned char*&dst,uint64_t&res,unsigned&pending,uint64_t pair){uint64_t v=((pair<<4)>>pending)|((res<<(63-pending))<<1);asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])dst):"r"(v));unsigned total=pending+60;dst+=total>>3;pending=total&7;res=pair;}
static inline void root_put30(unsigned char*&dst,uint64_t&res,unsigned&pending,uint64_t word){
uint64_t v=word<<34;asm("shrdq %%cl,%1,%0":"+r"(v):"r"(res),"c"(pending));
asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])dst):"r"(v));unsigned total=pending+30;dst+=total>>3;pending=total&7;res=word;}
template <bool Safe>
static inline void put_short(unsigned char*&dst, uint64_t&res, unsigned&pending,
uint64_t chunk, unsigned p) {
res = (res << p) | chunk;
unsigned total = pending + p, q = total >> 3;
pending = total & 7;
uint64_t v = __builtin_bswap64(res << (64 - total));
if constexpr (Safe) memcpy(dst, &v, q); else memcpy(dst, &v, 8);
dst += q;
}
// exact reference advance from `word`; true when the sequence is complete
template <unsigned N, bool Safe>
static inline bool advance(unsigned char*&dst, uint64_t&res, unsigned&pending, uint64_t&word) {
uint64_t next = word + 1;if constexpr(N==30&&!Safe){if((next&7u)==4u){word=next|(next>>28);return false;}}
unsigned p = N - __builtin_ctzll(next);
if (!p) return true;
word = next;
if (p > N / 2u) word |= word >> p;
else {
for (unsigned sh = p; sh < N; sh *= 2) word |= word >> sh;
if ((VALID<N> >> p) & 1) {
if constexpr (Safe) put_short<true>(dst, res, pending, word >> (N - p), p);
else put_short<false>(dst, res, pending, word >> (N - p), p);
}
}
return false;
}
template<unsigned P>static inline uint64_t root_first30(uint64_t w,uint64_t r){
uint64_t v=(w+1)<<(34-P);if constexpr(P>0)v|=r<<(64-P);
if constexpr(P<=4)v|=((w+3)<<(4-P))|((w+5)>>(26+P));else v|=(w+3)>>(P-4);
return v;
}
template<unsigned P>static inline uint64_t root_second30(uint64_t w){return (((w+3)<<60)|((w+5)<<30)|(w+7))<<(8-P);}
template<unsigned P>static inline void root_induction30(unsigned char*&dst,uint64_t&res,unsigned&pending,uint64_t&word,unsigned char*limit,uint64_t end){
uint64_t w=word,v0=root_first30<P>(w,res),v1=root_second30<P>(w);
asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])dst):"r"(v0));
asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])(dst+8)):"r"(v1));dst+=15;w+=8;
if(w<end&&dst<=limit){v0=root_first30<P>(w,w-1);v1=root_second30<P>(w);
constexpr uint64_t prefix=[](){if constexpr(P>0)return UINT64_C(8)<<(64-P);else return UINT64_C(0);}();
constexpr uint64_t inc0=[](){if constexpr(P<=4)return prefix+(UINT64_C(8)<<(34-P))+(UINT64_C(8)<<(4-P));else return prefix+(UINT64_C(8)<<(34-P))+(UINT64_C(8)>>(P-4));}();
constexpr uint64_t inc1=((UINT64_C(8)<<30)|8)<<(8-P);
if(w+32<=end&&dst<=limit-45){
const __m256i inc=_mm256_setr_epi64x(inc0*2,inc1*2,inc0*2,inc1*2);
const __m256i sw=_mm256_setr_epi8(7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8);
__m256i vv=_mm256_setr_epi64x(v0,v1,v0+inc0,v1+inc1);
while(w+64<=end&&dst<=limit-105){{__m256i b0=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);__m256i b1=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);
_mm_storeu_si128((__m128i*)dst,_mm256_castsi256_si128(b0));_mm_storeu_si128((__m128i*)(dst+15),_mm256_extracti128_si256(b0,1));
_mm_storeu_si128((__m128i*)(dst+30),_mm256_castsi256_si128(b1));_mm_storeu_si128((__m128i*)(dst+45),_mm256_extracti128_si256(b1,1));dst+=60;w+=32;
}{__m256i b0=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);__m256i b1=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);
_mm_storeu_si128((__m128i*)dst,_mm256_castsi256_si128(b0));_mm_storeu_si128((__m128i*)(dst+15),_mm256_extracti128_si256(b0,1));
_mm_storeu_si128((__m128i*)(dst+30),_mm256_castsi256_si128(b1));_mm_storeu_si128((__m128i*)(dst+45),_mm256_extracti128_si256(b1,1));dst+=60;w+=32;
}}
while(w+32<=end&&dst<=limit-45){__m256i b0=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);__m256i b1=_mm256_shuffle_epi8(vv,sw);vv=_mm256_add_epi64(vv,inc);
_mm_storeu_si128((__m128i*)dst,_mm256_castsi256_si128(b0));_mm_storeu_si128((__m128i*)(dst+15),_mm256_extracti128_si256(b0,1));
_mm_storeu_si128((__m128i*)(dst+30),_mm256_castsi256_si128(b1));_mm_storeu_si128((__m128i*)(dst+45),_mm256_extracti128_si256(b1,1));dst+=60;w+=32;
}v0=(uint64_t)_mm256_extract_epi64(vv,0);v1=(uint64_t)_mm256_extract_epi64(vv,1);}
while(w<end&&dst<=limit){
asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])dst):"r"(v0));
asm("movbeq %1,%0":"=m"(*(unsigned char(*)[8])(dst+8)):"r"(v1));
dst+=15;w+=8;v0+=inc0;v1+=inc1;
}}
res=w-1;word=w;
if(w==end){unsigned p=30-__builtin_ctzll(w);if(p*2u>30)word|=word>>p;else for(unsigned q=p;q<30;q*=2)word|=word>>q;if((VALID<30> >>p)&1)put_short<false>(dst,res,pending,word>>(30-p),p);}
}
template <unsigned N>
static size_t gen(unsigned char* out) {
static_assert(N >= 8 && N <= 33, "order");
constexpr size_t len = size_t(1) << (N - 3);
unsigned char* dst = out;
uint64_t word = 0, res = 0;
unsigned pending = 1;
if constexpr (len >= 32) {
unsigned char* const limit = out + len - 16;
for (;;) {
if (dst > limit) break;
// ---------------- chained run ----------------
if constexpr (RUNLOOP) {
if constexpr (FUSE4 && (4u * N <= 121u)) {
if ((word & ((uint64_t(3) << (N - 2)) | 7u)) == 0) {
uint64_t w = word;
// the four emitted words are an arithmetic progression in the run, so
// the 4N-bit payload advances by a compile-time constant
__uint128_t payload;
if constexpr (2u * N <= 64u) {
const uint64_t pair = (w << N) | w;
payload = ((__uint128_t)pair << (2 * N)) | pair;
} else {
const __uint128_t pair = ((__uint128_t)w << N) | w;
payload = (pair << (2 * N)) | pair;
}
payload |= ((__uint128_t)1 << (3 * N)) | ((__uint128_t)3 << (2 * N))
| ((__uint128_t)5 << N) | (uint64_t)7;
constexpr __uint128_t INC = ((__uint128_t)8 << (3 * N)) | ((__uint128_t)8 << (2 * N))
| ((__uint128_t)8 << N) | (uint64_t)8;
if constexpr(N==30){uint64_t end=fusion_end(N,w);switch(pending){case 0:root_induction30<0>(dst,res,pending,word,limit,end);break;case 1:root_induction30<1>(dst,res,pending,word,limit,end);break;case 2:root_induction30<2>(dst,res,pending,word,limit,end);break;case 3:root_induction30<3>(dst,res,pending,word,limit,end);break;case 4:root_induction30<4>(dst,res,pending,word,limit,end);break;case 5:root_induction30<5>(dst,res,pending,word,limit,end);break;case 6:root_induction30<6>(dst,res,pending,word,limit,end);break;case 7:root_induction30<7>(dst,res,pending,word,limit,end);break;}continue;}
if(w<(UINT64_C(1)<<(N-5))){const uint64_t run_end=fusion_end(N,w);
for (;;) {
put<4u * N, false>(dst, res, pending, payload);
payload += INC;
const uint64_t u = w + 8;
if (u == run_end) { const unsigned p=N-__builtin_ctzll(u);
word = u;
if (p * 2u > N) word |= word >> p;
else for (unsigned sh = p; sh < N; sh *= 2) word |= word >> sh;
if ((VALID<N> >> p) & 1) put_short<false>(dst, res, pending, word >> (N - p), p);
break;
}
w = u;
if (dst > limit) { word = w; break; }
}}else{for (;;) {
put<4u * N, false>(dst, res, pending, payload);
payload += INC;
const uint64_t u = w + 8;
const unsigned p=N-__builtin_ctzll(u);if ((u>>p)!=0) {
word = u;
if (p * 2u > N) word |= word >> p;
else for (unsigned sh = p; sh < N; sh *= 2) word |= word >> sh;
if ((VALID<N> >> p) & 1) put_short<false>(dst, res, pending, word >> (N - p), p);
break;
}
w = u;
if (dst > limit) { word = w; break; }
}}
continue;
}
} else if constexpr (N == 33) {
if ((word & ((uint64_t(3) << (N - 2)) | 3u)) == 0) {
uint64_t w = word;
for (;;) {
put2_66(dst, res, pending, w + 1, w + 3);
const uint64_t u = w + 4;
if ((u >> (N - 2)) != 0) { word = u; advance<33, false>(dst, res, pending, word); break; }
w = u;
if (dst > limit) { word = w; break; }
}
continue;
}
}
}
// ---------------- general single step ----------------
if constexpr (FUSE4 && (4u * N <= 121u)) {
if ((word & ((uint64_t(3) << (N - 2)) | 7u)) == 0) {
uint64_t w = word;
__uint128_t payload;
if constexpr (2u * N <= 64u) {
const uint64_t pair = (w << N) | w;
payload = ((__uint128_t)pair << (2 * N)) | pair;
} else {
const __uint128_t pair = ((__uint128_t)w << N) | w;
payload = (pair << (2 * N)) | pair;
}
payload |= ((__uint128_t)1 << (3 * N)) | ((__uint128_t)3 << (2 * N))
| ((__uint128_t)5 << N) | (uint64_t)7;
word = w + 7;
put<4u * N, false>(dst, res, pending, payload);
if (advance<N, false>(dst, res, pending, word)) break;
continue;
}
}
if constexpr (N == 33 && FUSE4) {
if ((word & 3u) == 0 && (word >> (N - 2)) == 0) {
const uint64_t w = word;
word = w + 3;
put2_66(dst, res, pending, w + 1, w + 3);
if (advance<33, false>(dst, res, pending, word)) break;
continue;
}
}
if ((word & 3u) == 0 && (2u * N <= 64u)) {
const uint64_t w = word;
word = w + 3;
if constexpr(N==30) put60(dst, res, pending, ((uint64_t)(w + 1) << N) | (w + 3)); else put<2u * N, false>(dst, res, pending, ((__uint128_t)(w + 1) << N) | (w + 3));
} else {
if (!(word & 1u)) { ++word; if constexpr(N==30)root_put30(dst,res,pending,word);else put<N, false>(dst, res, pending, word); }
if (!(word & 2u)) { word += 2; if constexpr(N==30)root_put30(dst,res,pending,word);else put<N, false>(dst, res, pending, word); }
}
if (advance<N, false>(dst, res, pending, word)) break;
}
}
// cold tail: same recurrence, exact-width stores
{
uint64_t w = word, r = res; unsigned pd = pending;
unsigned char* d = dst;
for (;;) {
if constexpr (FUSE4 && (4u * N <= 121u)) {
if ((w & ((uint64_t(3) << (N - 2)) | 7u)) == 0) {
const uint64_t v = w;
__uint128_t payload;
if constexpr (2u * N <= 64u) {
const uint64_t pair = (v << N) | v;
payload = ((__uint128_t)pair << (2 * N)) | pair;
} else {
const __uint128_t pair = ((__uint128_t)v << N) | v;
payload = (pair << (2 * N)) | pair;
}
payload |= ((__uint128_t)1 << (3 * N)) | ((__uint128_t)3 << (2 * N))
| ((__uint128_t)5 << N) | (uint64_t)7;
w = v + 7;
put<4u * N, true>(d, r, pd, payload);
if (advance<N, true>(d, r, pd, w)) break;
continue;
}
}
if ((w & 3u) == 0 && (2u * N <= 64u)) {
const uint64_t v = w;
w = v + 3;
put<2u * N, true>(d, r, pd, ((__uint128_t)(v + 1) << N) | (v + 3));
} else {
if (!(w & 1u)) { ++w; put<N, true>(d, r, pd, w); }
if (!(w & 2u)) { w += 2; put<N, true>(d, r, pd, w); }
}
if (advance<N, true>(d, r, pd, w)) break;
}
dst = d;
}
return size_t(dst - out);
}
} // namespace dbj
void debruijn(unsigned n, char* s) {
if (n != ORD) __builtin_trap();
if (dbj::gen<ORD>((unsigned char*)s) != (size_t(1) << (ORD - 3))) __builtin_trap();
}