#!/usr/bin/env python3 """Build job1049/tilegap2.positions.c = the served tilegap2.c + a per-thread list of the maxima positions. Byte-level edits against the served file (CRLF preserved), so the resulting unified diff is minimal. Usage: python make_patch.py """ import difflib SERVED = "job587/pub/tools/tilegap/tilegap2.c" OUT = "job1049/tilegap2.positions.c" PATCH = "job1049/tilegap2-positions.patch" src = open(SERVED, "rb").read() E = [] # 1. the per-thread struct keeps a list, not just the least position E.append(( b" uint64_t bestGap, bestGapI1, bestGapJ, bestGapCount, bestGapMinPos;\r\n", b" uint64_t bestGap, bestGapI1, bestGapJ, bestGapCount, bestGapMinPos;\r\n" b" uint64_t bestPos[64]; int nBestPos; /* ALL positions attaining the max (<=64), chunk-local */\r\n", )) # 2. reset the list when a new, larger max appears E.append(( b"r->bestGapCount = 1; r->bestGapMinPos = gpos; }", b"r->bestGapCount = 1; r->bestGapMinPos = gpos; r->nBestPos = 0; }", )) # 3. append every attaining position, and warn if the list overflows E.append(( b" else { r->bestGapCount++; if (gpos < r->bestGapMinPos) r->bestGapMinPos = gpos; } }\r\n", b" else { r->bestGapCount++; if (gpos < r->bestGapMinPos) r->bestGapMinPos = gpos; }\r\n" b" if (r->nBestPos < 64) r->bestPos[r->nBestPos++] = gpos;\r\n" b" else fprintf(stderr, \"WARN thread %d: >64 maxima, position list truncated\\n\", L->tid); }\r\n", )) # 4. main prints the merged list (one extra stdout line; nothing else changes) E.append(( b' printf("maxima: count=%llu least position = %llu\\n", (unsigned long long)gc, (unsigned long long)gm);\r\n', b' printf("maxima: count=%llu least position = %llu\\n", (unsigned long long)gc, (unsigned long long)gm);\r\n' b' { uint64_t mpos[1024]; int nm = 0;\r\n' b' for (int t = 0; t < NT; t++) if (R[t].bestGap == bg)\r\n' b' for (int k = 0; k < R[t].nBestPos && nm < 1024; k++) mpos[nm++] = R[t].bestPos[k];\r\n' b' printf("maxima positions (%d):", nm);\r\n' b' for (int k = 0; k < nm; k++) printf(" %llu", (unsigned long long)mpos[k]);\r\n' b' printf("\\n"); }\r\n', )) out = src for i, (old, new) in enumerate(E): n = out.count(old) assert n == 1, "edit %d matched %d times" % (i, n) out = out.replace(old, new) open(OUT, "wb").write(out) print("wrote %s (%d -> %d bytes)" % (OUT, len(src), len(out))) a = src.decode("utf-8", "replace").splitlines(keepends=True) b = out.decode("utf-8", "replace").splitlines(keepends=True) diff = "".join(difflib.unified_diff(a, b, "a/tools/tilegap/tilegap2.c", "b/tools/tilegap/tilegap2.c", n=3)) open(PATCH, "w", encoding="utf-8", newline="").write(diff) print("wrote %s (%d hunks)" % (PATCH, diff.count("@@ ")))