import java.util.*; /** * CWE-407 unit test for bun yarn lock processing defect. * * bun-0001: src/install/yarn.zig — scoped package version lookup * Two sequential linear scans over version list for same package: * Pass 1 (lines 777-780): find found_existing and found_new * Pass 2 (lines 800-805): find package_id when found_new=true * Fix: capture package_id in pass 1 → eliminate pass 2 → O(M) → O(M/2) */ public class BunTest { static class VersionInfo { int yarnIdx; String version; int packageId; VersionInfo(int y, String v, int p) { yarnIdx=y; version=v; packageId=p; } } // Two-pass scan (defect) static int resolveVersionTwoPass(List list, String version) { boolean foundNew = false; for (VersionInfo item : list) { // pass 1 if (item.version.equals(version)) foundNew = true; } if (foundNew) { for (VersionInfo item : list) { // pass 2 — redundant if (item.version.equals(version)) return item.packageId; } } return -1; } // Single-pass (fix) static int resolveVersionSinglePass(List list, String version) { for (VersionInfo item : list) { // single pass, capture id if (item.version.equals(version)) return item.packageId; } return -1; } static void testBun0001() throws Exception { int N = 5000; // yarn entries int V = 10; // versions per package // Build a scoped package list with V versions List versionList = new ArrayList<>(); for (int i = 0; i < V; i++) { versionList.add(new VersionInfo(i, "1." + i + ".0", 100 + i)); } String targetVersion = "1.5.0"; // correctness int r1 = resolveVersionTwoPass(versionList, targetVersion); int r2 = resolveVersionSinglePass(versionList, targetVersion); assert r1 == r2 : "two-pass and single-pass must agree: " + r1 + " vs " + r2; // performance: simulate N yarn entries each needing version resolution long t0 = System.nanoTime(); long sum1 = 0; for (int i = 0; i < N; i++) sum1 += resolveVersionTwoPass(versionList, targetVersion); long tTwo = System.nanoTime() - t0; t0 = System.nanoTime(); long sum2 = 0; for (int i = 0; i < N; i++) sum2 += resolveVersionSinglePass(versionList, targetVersion); long tOne = System.nanoTime() - t0; assert sum1 == sum2 : "sums must match"; double ratio = (double) tTwo / tOne; System.out.printf("bun-0001: two-pass=%.3fs single-pass=%.3fs ratio=%.1f×%n", tTwo / 1e9, tOne / 1e9, ratio); assert ratio > 1.5 : "Expected >1.5× speedup, got " + ratio; System.out.println("PASS bun-0001"); } public static void main(String[] args) throws Exception { testBun0001(); System.out.println("ALL PASS"); } }