Skip to content

Commit ed97672

Browse files
MaxGraeydcodeIO
authored andcommitted
Use faster clamping for Uint8ClampedArray (AssemblyScript#422)
1 parent 6a1ffb8 commit ed97672

File tree

3 files changed

+293
-289
lines changed

3 files changed

+293
-289
lines changed

std/assembly/typedarray.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ import {
1515
COMPARATOR
1616
} from "./internal/sort";
1717

18+
function clampToByte(value: i32): i32 {
19+
return ~(value >> 31) & (((255 - value) >> 31) | value); // & 255
20+
}
21+
1822
export class Int8Array extends TypedArray<i8> {
1923
@lazy static readonly BYTES_PER_ELEMENT: usize = sizeof<i8>();
2024

@@ -112,12 +116,12 @@ export class Uint8ClampedArray extends Uint8Array {
112116

113117
@inline @operator("[]=")
114118
protected __set(index: i32, value: i32): void {
115-
super.__set(index, max(min(value, 255), 0));
119+
super.__set(index, clampToByte(value));
116120
}
117121

118122
@inline @operator("{}=")
119123
protected __unchecked_set(index: i32, value: i32): void {
120-
super.__unchecked_set(index, max(min(value, 255), 0));
124+
super.__unchecked_set(index, clampToByte(value));
121125
}
122126

123127
fill(value: u32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8ClampedArray {

tests/compiler/std/typedarray.optimized.wat

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1814,21 +1814,21 @@
18141814
i32.store8 offset=8
18151815
)
18161816
(func $~lib/typedarray/Uint8ClampedArray#__set (; 25 ;) (type $iii_) (param $0 i32) (param $1 i32) (param $2 i32)
1817-
(local $3 i32)
18181817
local.get $0
18191818
local.get $1
1820-
local.get $2
18211819
i32.const 255
18221820
local.get $2
1823-
i32.const 255
1824-
i32.lt_s
1825-
select
1826-
local.tee $3
1827-
i32.const 0
1828-
local.get $3
1829-
i32.const 0
1830-
i32.gt_s
1831-
select
1821+
i32.sub
1822+
i32.const 31
1823+
i32.shr_s
1824+
local.get $2
1825+
i32.or
1826+
local.get $2
1827+
i32.const 31
1828+
i32.shr_s
1829+
i32.const -1
1830+
i32.xor
1831+
i32.and
18321832
call $~lib/internal/typedarray/TypedArray<u8>#__set
18331833
)
18341834
(func $~lib/internal/typedarray/TypedArray<u8>#__get (; 26 ;) (type $iii) (param $0 i32) (param $1 i32) (result i32)

0 commit comments

Comments
 (0)