Skip to content

Commit c27b6e8

Browse files
MaxGraeydcodeIO
authored andcommitted
Add integer power functions (#212)
1 parent 658ab23 commit c27b6e8

File tree

4 files changed

+1810
-2
lines changed

4 files changed

+1810
-2
lines changed

std/assembly/math.ts

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2303,3 +2303,111 @@ export namespace NativeMathf {
23032303
return sx ? -x : x;
23042304
}
23052305
}
2306+
2307+
export function ipow32(x: i32, e: i32): i32 {
2308+
var out = 1;
2309+
if (ASC_SHRINK_LEVEL < 1) {
2310+
if (e < 0) return 0;
2311+
2312+
switch (e) {
2313+
case 0: return 1;
2314+
case 1: return x;
2315+
case 2: return x * x;
2316+
}
2317+
2318+
let log = 32 - clz(e);
2319+
if (log <= 5) {
2320+
// 32 = 2 ^ 5, so need only five cases.
2321+
// But some extra cases needs for properly overflowing
2322+
switch (log) {
2323+
case 5: {
2324+
if (e & 1) out *= x;
2325+
e >>= 1;
2326+
x *= x;
2327+
}
2328+
case 4: {
2329+
if (e & 1) out *= x;
2330+
e >>= 1;
2331+
x *= x;
2332+
}
2333+
case 3: {
2334+
if (e & 1) out *= x;
2335+
e >>= 1;
2336+
x *= x;
2337+
}
2338+
case 2: {
2339+
if (e & 1) out *= x;
2340+
e >>= 1;
2341+
x *= x;
2342+
}
2343+
case 1: {
2344+
if (e & 1) out *= x;
2345+
}
2346+
}
2347+
return out;
2348+
}
2349+
}
2350+
2351+
while (e > 0) {
2352+
if (e & 1) out *= x;
2353+
e >>= 1;
2354+
x *= x;
2355+
}
2356+
return out;
2357+
}
2358+
2359+
export function ipow64(x: i64, e: i32): i64 {
2360+
var out: i64 = 1;
2361+
if (ASC_SHRINK_LEVEL < 1) {
2362+
if (e < 0) return 0;
2363+
switch (e) {
2364+
case 0: return 1;
2365+
case 1: return x;
2366+
case 2: return x * x;
2367+
}
2368+
2369+
let log = 32 - clz(e);
2370+
if (log <= 6) {
2371+
// 64 = 2 ^ 6, so need only six cases.
2372+
// But some extra cases needs for properly overflowing
2373+
switch (log) {
2374+
case 6: {
2375+
if (e & 1) out *= x;
2376+
e >>= 1;
2377+
x *= x;
2378+
}
2379+
case 5: {
2380+
if (e & 1) out *= x;
2381+
e >>= 1;
2382+
x *= x;
2383+
}
2384+
case 4: {
2385+
if (e & 1) out *= x;
2386+
e >>= 1;
2387+
x *= x;
2388+
}
2389+
case 3: {
2390+
if (e & 1) out *= x;
2391+
e >>= 1;
2392+
x *= x;
2393+
}
2394+
case 2: {
2395+
if (e & 1) out *= x;
2396+
e >>= 1;
2397+
x *= x;
2398+
}
2399+
case 1: {
2400+
if (e & 1) out *= x;
2401+
}
2402+
}
2403+
return out;
2404+
}
2405+
}
2406+
2407+
while (e > 0) {
2408+
if (e & 1) out *= x;
2409+
e >>= 1;
2410+
x *= x;
2411+
}
2412+
return out;
2413+
}

0 commit comments

Comments
 (0)