Skip to content

Commit

Permalink
constants, clamp ints on rust impl
Browse files Browse the repository at this point in the history
  • Loading branch information
enricozb committed May 31, 2024
1 parent 934d4a0 commit ed5936b
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ impl Numb {
} else if val.is_nan() {
format!("+NaN")
} else {
format!("{:.7e}", val)
format!("{:?}", val)
}
}
_ => {
Expand Down
8 changes: 6 additions & 2 deletions src/hvm.c
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ typedef u32 Numb; // Numb ::= 29-bit (rounded up to u32)
#define SWIT 0x7

// Numbers
static const f32 U24_MAX = (f32) (1 << 24) - 1;
static const f32 U24_MIN = 0.0;
static const f32 I24_MAX = (f32) (1 << 23) - 1;
static const f32 I24_MIN = (f32) (i32) ((-1u) << 23);
#define TY_SYM 0x00
#define TY_U24 0x01
#define TY_I24 0x02
Expand Down Expand Up @@ -469,7 +473,7 @@ static inline Numb cast(Numb a, Numb b) {
if (isnan(val)) {
return new_u24(0);
}
return new_u24((u32) clamp(val, 0.0, 16777215));
return new_u24((u32) clamp(val, U24_MIN, U24_MAX));
}

if (get_sym(a) == TY_I24 && get_typ(b) == TY_U24) {
Expand All @@ -483,7 +487,7 @@ static inline Numb cast(Numb a, Numb b) {
if (isnan(val)) {
return new_i24(0);
}
return new_i24((i32) clamp(val, -8388608.0, 8388607.0));
return new_i24((i32) clamp(val, I24_MIN, I24_MAX));
}

if (get_sym(a) == TY_F24 && get_typ(b) == TY_U24) return new_f24((f32) get_u24(b));
Expand Down
8 changes: 6 additions & 2 deletions src/hvm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ pub struct APair(pub AtomicU64);

// Number
pub struct Numb(pub Val);
const U24_MAX : u32 = 1 << 24 - 1;
const U24_MIN : u32 = 0;
const I24_MAX : i32 = 1 << 23 - 1;
const I24_MIN : i32 = -1 << 23;

// Tags
pub const VAR : Tag = 0x0; // variable
Expand Down Expand Up @@ -295,11 +299,11 @@ impl Numb {
match (a.get_sym(), b.get_typ()) {
(TY_U24, TY_U24) => b,
(TY_U24, TY_I24) => Self::new_u24(b.get_i24() as u32),
(TY_U24, TY_F24) => Self::new_u24(b.get_f24().clamp(0.0, 16777215.0) as u32),
(TY_U24, TY_F24) => Self::new_u24((b.get_f24() as u32).clamp(U24_MIN, U24_MAX)),

(TY_I24, TY_U24) => Self::new_i24(b.get_u24() as i32),
(TY_I24, TY_I24) => b,
(TY_I24, TY_F24) => Self::new_i24(b.get_f24().clamp(-8388608.0, 8388607.0) as i32),
(TY_I24, TY_F24) => Self::new_i24((b.get_f24() as i32).clamp(I24_MIN, I24_MAX)),

(TY_F24, TY_U24) => Self::new_f24(b.get_u24() as f32),
(TY_F24, TY_I24) => Self::new_f24(b.get_i24() as f32),
Expand Down

0 comments on commit ed5936b

Please sign in to comment.