diff options
author | Xander <xander@biltopia.org> | 2023-07-13 21:41:37 +0200 |
---|---|---|
committer | Xander <xander@biltopia.org> | 2023-07-13 21:41:37 +0200 |
commit | 947331444708d2dc622ad6d8d3eb069e29a1898f (patch) | |
tree | 0d6fa96210954333a051ee58a246fcfa65448824 /lib/DATS | |
parent | 67245a7eebeb135427d50171fda7af58770afc6d (diff) | |
download | ats-os-947331444708d2dc622ad6d8d3eb069e29a1898f.tar.xz ats-os-947331444708d2dc622ad6d8d3eb069e29a1898f.zip |
Allow negative number conversion
Diffstat (limited to 'lib/DATS')
-rw-r--r-- | lib/DATS/itoa.dats | 34 |
1 files changed, 25 insertions, 9 deletions
diff --git a/lib/DATS/itoa.dats b/lib/DATS/itoa.dats index 35b8c47..2fef14c 100644 --- a/lib/DATS/itoa.dats +++ b/lib/DATS/itoa.dats @@ -31,11 +31,12 @@ in //TODO: make function better by handling to large number for buffer -extern fun itoa {v,n:nat | n > 1 && n < 33 && v > 0} (value : int v, base : int n) : [k : nat | k < BUFFER_SIZE] string k +extern fun itoa {n:nat | n > 1 && n < 33} (value : int, base : int n) : [k : nat | k < BUFFER_SIZE] string k implement itoa(value,base) = let prval (pf , fpf) = __assert(addr@buffer) // Get proofs UNSAFE: + val offset = (if(value < 0) then 1 else 0) : [n: nat | n == 0 || n == 1] int n - fun loop {n,i : nat | n > 0 && i < BUFFER_SIZE} {l:addr} (pf : !(@[char][BUFFER_SIZE] @ l) | p : ptr l , n : int n, i : size_t i): void = let + fun loop {i : nat | i < BUFFER_SIZE} {l:addr} (pf : !(@[char][BUFFER_SIZE] @ l) | p : ptr l , n : int, i : int i): void = let val r = n % base val k = n / base in @@ -48,16 +49,31 @@ implement itoa(value,base) = let if (k > 0) then loop(pf | p, k, succ(i)) else ( - p->[succ(i)] := '\0'; - reverse(pf | p, sz2i(i))) + p->[i+1+offset] := '\0'; + reverse(pf | p, i+offset) + ) end - // Run loop - val () = loop(pf | addr@buffer, value, i2sz(0)); - val str = char_arr2string(buffer); // Convert arr to string UNSAFE: in - let prval () = fpf(pf) in end; - str // Return string + + if (value != 0) then + loop(pf | addr@buffer, abs(value), 0) + else ( + buffer[0] := '0'; + buffer[1] := '\0' + ); + + if (value < 0) then + buffer[0] := '-'; + + // Run loop + let + val str = char_arr2string(buffer) // Convert arr to string UNSAFE: + prval () = fpf(pf) + in + str // Return string + end + end end |