|
1 | | -(* Hash Array Mapped Trie (HAMT) library for Troupe *) |
| 1 | +(* Hash Array Mapped Trie (HAMT) library for Troupe - Optimized with native bit operations *) |
2 | 2 |
|
3 | | -(* 2025-07-29: Note; AA -- this is currently very slow -- |
4 | | - so it is a good target for driving the performance tuning |
5 | | - *) |
| 3 | +(* 2025-07-29: Updated to use native bit operations instead of arithmetic simulation *) |
6 | 4 |
|
7 | 5 | import lists |
8 | 6 |
|
|
15 | 13 | val BRANCH_FACTOR = 32 (* 2^5 branches *) |
16 | 14 | val MASK = 31 (* 0b11111 *) |
17 | 15 |
|
18 | | - (* Integer power function *) |
19 | | - fun intPow base exp = |
20 | | - if exp = 0 then 1 |
21 | | - else base * intPow base (exp - 1) |
22 | | - |
23 | | - (* String length helper *) |
24 | | - (* fun strLen s = |
25 | | - let fun len s idx = |
26 | | - case (substring (s, idx, 1)) of |
27 | | - "" => idx |
28 | | - | _ => len s (idx + 1) |
29 | | - in len s 0 |
30 | | - end |
31 | | - *) |
32 | 16 | (* Character code at index - extended character set *) |
33 | 17 | fun charCode s idx = charCodeAtWithDefault (s, idx, 63) |
34 | 18 |
|
|
53 | 37 | end |
54 | 38 | end |
55 | 39 |
|
56 | | - (* Get the index at a given level from hash *) |
57 | | - fun getIndex hashval level = (hashval div (intPow BRANCH_FACTOR level)) mod BRANCH_FACTOR |
| 40 | + (* Get the index at a given level from hash - using bit operations *) |
| 41 | + fun getIndex hashval level = (hashval >> (level * SHIFT)) andb MASK |
58 | 42 |
|
59 | | - (* Bitmap operations simulated with arithmetic *) |
60 | | - fun setBit bitmap pos = bitmap + intPow 2 pos |
61 | | - fun testBit bitmap pos = ((bitmap div (intPow 2 pos)) mod 2) = 1 |
62 | | - fun clearBit bitmap pos = |
63 | | - if testBit bitmap pos |
64 | | - then bitmap - intPow 2 pos |
65 | | - else bitmap |
| 43 | + (* Bitmap operations using native bit operations *) |
| 44 | + fun setBit bitmap pos = bitmap orb (1 << pos) |
| 45 | + fun testBit bitmap pos = ((bitmap >> pos) andb 1) = 1 |
| 46 | + fun clearBit bitmap pos = bitmap andb ((-1) xorb (1 << pos)) |
66 | 47 |
|
67 | 48 | fun popcount bitmap = |
68 | 49 | let fun count bm acc = |
69 | 50 | if bm = 0 then acc |
70 | | - else count (bm div 2) (acc + (bm mod 2)) |
| 51 | + else count (bm >> 1) (acc + (bm andb 1)) |
71 | 52 | in count bitmap 0 |
72 | 53 | end |
73 | 54 |
|
74 | 55 | fun positionInBitmap bitmap pos = |
75 | | - let fun countBits bm p acc = |
76 | | - if p = 0 then acc |
77 | | - else countBits (bm div 2) (p - 1) (acc + (bm mod 2)) |
78 | | - in countBits bitmap pos 0 |
| 56 | + (* Count the number of 1 bits before position pos *) |
| 57 | + let val mask = (1 << pos) - 1 |
| 58 | + val masked = bitmap andb mask |
| 59 | + in popcount masked |
79 | 60 | end |
80 | 61 |
|
81 | 62 | (* Array operations using lists *) |
|
0 commit comments