Skip to content

Instantly share code, notes, and snippets.

@edwintorok
Created December 17, 2023 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwintorok/46b3b4247b2484aab19a942210a68627 to your computer and use it in GitHub Desktop.
Save edwintorok/46b3b4247b2484aab19a942210a68627 to your computer and use it in GitHub Desktop.
let base = Char.code '0'
let rec string_of_int_rec b i n =
let i = i - 1 in
Bytes.unsafe_set b i (Char.unsafe_chr (base + n mod 10));
let n = n / 10 in
if n = 0 then i
else string_of_int_rec b i n
let int_min_str = string_of_int min_int
let string_of_int2 n =
let len = 20 in
let b = Bytes.create len in
if n < 0 then
if n = min_int then int_min_str
else
let pos = string_of_int_rec b len (-n) - 1 in
Bytes.unsafe_set b pos '-';
Bytes.sub_string b pos (len - pos)
else
let pos = string_of_int_rec b len n in
Bytes.sub_string b pos (len - pos)
let tst = [min_int; min_int+1;-10;-1;0;1;10;max_int-1;max_int]
let () =
tst |> List.iter @@ fun i ->
assert (string_of_int i = string_of_int i)
let () =
for _ = 1 to 10_000_000 do
ignore @@ Sys.opaque_identity (string_of_int2 0)
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment