Skip to content

Commit 8727e79

Browse files
committed
Improve performance and specialise maths ops
1 parent 351126d commit 8727e79

File tree

2 files changed

+16
-47
lines changed

2 files changed

+16
-47
lines changed

src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ use alloc::{vec, vec::Vec};
7878
use core::cmp::{max, min};
7979

8080
mod math;
81-
use crate::math::{abs, clamp, round};
81+
use crate::math::{abs, clamp_round};
8282

8383
const CHANNELS: usize = 4;
8484

@@ -398,10 +398,10 @@ impl NeuQuant {
398398
/// initializes the color map
399399
fn build_colormap(&mut self) {
400400
for i in 0usize..self.netsize {
401-
self.colormap[i].b = clamp(round(self.network[i].b) as i32);
402-
self.colormap[i].g = clamp(round(self.network[i].g) as i32);
403-
self.colormap[i].r = clamp(round(self.network[i].r) as i32);
404-
self.colormap[i].a = clamp(round(self.network[i].a) as i32);
401+
self.colormap[i].b = clamp_round(self.network[i].b);
402+
self.colormap[i].g = clamp_round(self.network[i].g);
403+
self.colormap[i].r = clamp_round(self.network[i].r);
404+
self.colormap[i].a = clamp_round(self.network[i].a);
405405
}
406406
}
407407

src/math.rs

Lines changed: 11 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,21 @@
11
#[inline]
2-
pub(crate) fn clamp(a: i32) -> i32 {
3-
if a < 0 {
4-
0
5-
} else if a > 255 {
6-
255
7-
} else {
2+
pub(crate) fn abs(a: f64) -> f64 {
3+
if a.is_sign_positive() {
84
a
9-
}
10-
}
11-
12-
#[inline]
13-
fn fract(a: f64) -> f64 {
14-
if a == 0.0 {
15-
0.
5+
} else if a.is_sign_negative() {
6+
-a
167
} else {
17-
a % 1.
8+
core::f64::NAN
189
}
1910
}
2011

2112
#[inline]
22-
pub(crate) fn round(a: f64) -> f64 {
23-
let one = 1.0;
24-
let h = 0.5;
25-
let f = fract(a);
26-
if f.is_nan() || f == 0.0 {
27-
a
28-
} else if a > 0. {
29-
if f < h {
30-
a - f
31-
} else {
32-
a - f + one
33-
}
34-
} else if -f < h {
35-
a - f
13+
pub(crate) fn clamp_round(a: f64) -> i32 {
14+
if a < 0. {
15+
0
16+
} else if a > 255. {
17+
255
3618
} else {
37-
a - f - one
38-
}
39-
}
40-
41-
#[inline]
42-
pub(crate) fn abs(a: f64) -> f64 {
43-
if a.is_sign_positive() {
44-
return a;
19+
(a + 0.5) as i32
4520
}
46-
47-
if a.is_sign_negative() {
48-
return -a;
49-
}
50-
51-
core::f64::NAN
5221
}

0 commit comments

Comments
 (0)