Idiomatic OCaml: int8 int16 int32 int64 uint8 uint16 uint32 uint64

I can define my own types:

module Int8 = struct type t = int end;
module Int16 = struct type t = int end;
...

But I’m wondering if there is a standard / idiomatic set of definitions.

The XY problem: I’m using this not for computation, but for serialization, where I want the type to specify how many bytes we are writing to, and this needs to be consistent across multiple different programming languages.

2 Likes

I think these days the canonical solution is ocaml-stdint.

That may have been fixed now, but I rather remember that one as being quite buggy. I would rather go with GitHub - yallop/ocaml-integers: Various signed and unsigned integer types for OCaml

Also, I suspect that stdint doesn’t support js_of_ocaml

1 Like

Adding support for jsoo should not be difficult, if anyone is interested …

1 Like

Unfortunately it does not seem to implement i8 and i16 – see: Where are signed 8-bit and 16-bit numbers?.

Seems like int_repr supports bit widths up to 128bits, but that requires you to depend on base?

1 Like

I wrote a PR to add support for small signed integers but it hasn’t gotten any comments/review yet. I’ve pinned the branch in my private projects without issue though, so maybe that would be of interest.

Here’s the PR: feat: add small signed integers by zbaylin · Pull Request #49 · yallop/ocaml-integers · GitHub

3 Likes

Ah cool, I saw that PR, and was considering depending on that branch in my projects, if that’s ok!

Is there any differences in performance among the integer libraries mentioned on this thread? I’ve used stdint but im wondering if there is a more performant alternative.

1 Like