whitepaper: 352/169 — wave4 MEDIUM (hadoop/hbase/nova/neutron/openstack) + fix odl-0002 dup
This commit is contained in:
parent
9934133dcf
commit
835ae73b0f
82 changed files with 5931 additions and 6 deletions
71
defects/substrate/unit/IsMemberAlgorithm.java
Normal file
71
defects/substrate/unit/IsMemberAlgorithm.java
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
package unit;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* substrate-0002: CWE-407 Aura/BABE/BEEFY is_member linear authority scan
|
||||
*
|
||||
* Simulates:
|
||||
* Slow: authorities.iter().any(|id| id == authority_id) — O(A)
|
||||
* Fast: authorities.binary_search(authority_id).is_ok() — O(log A)
|
||||
*/
|
||||
public class IsMemberAlgorithm {
|
||||
|
||||
static class Result {
|
||||
final long ops;
|
||||
final boolean found;
|
||||
Result(long ops, boolean found) { this.ops = ops; this.found = found; }
|
||||
}
|
||||
|
||||
/** Slow: linear scan. Mirrors .iter().any() */
|
||||
static Result slowIsMember(int[] authorities, int target) {
|
||||
long ops = 0;
|
||||
for (int id : authorities) {
|
||||
ops++;
|
||||
if (id == target) return new Result(ops, true);
|
||||
}
|
||||
return new Result(ops, false);
|
||||
}
|
||||
|
||||
/** Fast: binary search. Mirrors .binary_search() on sorted BoundedVec */
|
||||
static Result fastIsMember(int[] sortedAuthorities, int target) {
|
||||
int lo = 0, hi = sortedAuthorities.length - 1;
|
||||
long ops = 0;
|
||||
while (lo <= hi) {
|
||||
ops++;
|
||||
int mid = (lo + hi) >>> 1;
|
||||
if (sortedAuthorities[mid] == target) return new Result(ops, true);
|
||||
else if (sortedAuthorities[mid] < target) lo = mid + 1;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return new Result(ops, false);
|
||||
}
|
||||
|
||||
static void bench() {
|
||||
int N_AUTH = 1000;
|
||||
int[] authorities = new int[N_AUTH];
|
||||
for (int i = 0; i < N_AUTH; i++) authorities[i] = i * 2; // even IDs, sorted
|
||||
|
||||
// Worst case: target not present (or last element)
|
||||
int target = N_AUTH * 2 - 1; // odd, not in list → full scan
|
||||
|
||||
Result slow = slowIsMember(authorities, target);
|
||||
Result fast = fastIsMember(authorities, target);
|
||||
|
||||
System.out.println("is_member N_AUTH=" + N_AUTH);
|
||||
System.out.println(" slow ops: " + slow.ops + " found=" + slow.found);
|
||||
System.out.println(" fast ops: " + fast.ops + " found=" + fast.found);
|
||||
|
||||
double speedup = (double) slow.ops / fast.ops;
|
||||
System.out.printf(" speedup: %.1fx%n", speedup);
|
||||
|
||||
assert slow.found == fast.found : "result mismatch";
|
||||
assert slow.ops > fast.ops * 10 : "expected >10x speedup, got " + speedup;
|
||||
|
||||
System.out.println("1/1 PASS");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
bench();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue