Skip to content

Commit

Permalink
Fix hex_str and hex_str_upper primitives for negative numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
Alasdair committed Sep 26, 2024
1 parent fe628b0 commit 65bc406
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 deletions.
20 changes: 18 additions & 2 deletions lib/sail.c
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,29 @@ void dec_str(sail_string *str, const mpz_t n)
void hex_str(sail_string *str, const mpz_t n)
{
sail_free(*str);
gmp_asprintf(str, "0x%Zx", n);

if (mpz_cmp_si(n, 0) < 0) {
mpz_t abs;
mpz_init(abs);
mpz_abs(abs, n);
gmp_asprintf(str, "-0x%Zx", abs);
} else {
gmp_asprintf(str, "0x%Zx", n);
}
}

void hex_str_upper(sail_string *str, const mpz_t n)
{
sail_free(*str);
gmp_asprintf(str, "0x%ZX", n);

if (mpz_cmp_si(n, 0) < 0) {
mpz_t abs;
mpz_init(abs);
mpz_abs(abs, n);
gmp_asprintf(str, "-0x%ZX", abs);
} else {
gmp_asprintf(str, "0x%ZX", n);
}
}

bool eq_string(const_sail_string str1, const_sail_string str2)
Expand Down
3 changes: 2 additions & 1 deletion src/lib/sail_lib.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,7 @@ let to_lower_hex_char n = if 10 <= n && n <= 15 then Char.chr (n + 87) else Char
let to_upper_hex_char n = if 10 <= n && n <= 15 then Char.chr (n + 55) else Char.chr (n + 48)

let hex_str_helper to_char x =
let x, negative = if Big_int.less x Big_int.zero then (Big_int.abs x, "-") else (x, "") in
if Big_int.equal x Big_int.zero then "0x0"
else (
let x = ref x in
Expand All @@ -1084,7 +1085,7 @@ let hex_str_helper to_char x =
s := String.make 1 (to_char lower_4) ^ !s;
x := Big_int.shift_right !x 4
done;
"0x" ^ !s
negative ^ "0x" ^ !s
)

let hex_str = hex_str_helper to_lower_hex_char
Expand Down
6 changes: 6 additions & 0 deletions test/c/hex_str_negative.expect
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
0xa
0xA
-0xa
-0xA
0x0
0x0
15 changes: 15 additions & 0 deletions test/c/hex_str_negative.sail
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
default Order dec

$include <prelude.sail>
$include <string.sail>

val main : unit -> unit

function main() = {
print_endline(hex_str(10));
print_endline(hex_str_upper(10));
print_endline(hex_str(-10));
print_endline(hex_str_upper(-10));
print_endline(hex_str(0));
print_endline(hex_str(0));
}

0 comments on commit 65bc406

Please sign in to comment.