ocaml-stdint icon indicating copy to clipboard operation
ocaml-stdint copied to clipboard

Numeric conversion functions: do function raises when target type is smaller than source type?

Open braibant opened this issue 8 years ago • 3 comments

Reading the "Numeric conversion functions" of the lib, it's not clear to me whether the functions there will raise if one tries to convert, e.g., an int32 into an int24, or if it will truncate/mask the value.

It could make sense to improve the doc to make this really clear.

braibant avatar Apr 04 '16 08:04 braibant

the semantic is similar to the one in C -- there will be no exceptions raised, just truncated values

mwweissmann avatar Apr 26 '16 18:04 mwweissmann

I wish one could select different behavior. For example:

  • Int24.of_int32 or Int24.Wrapping.of_int32—truncates
  • Int24.of_int32_exn or Int24.Exn.of_int32—raises exception
  • Int24.of_int32_opt or Int24.of_int32—returns None on wrapping.

@mwweissmann what do you think of that feature and its API?

keleshev avatar May 04 '16 07:05 keleshev

This should be pretty easy to implement: Just check if the forward+backward conversion is idemnpotent: let f x = let y = of_int32 x in if Int32.of_int8 y = x then y else raise Overflow

mwweissmann avatar May 05 '16 19:05 mwweissmann