From 7c3b535a127ad08cdb5dd235236c81a7afcb0586 Mon Sep 17 00:00:00 2001
From: Andre Maroneze <andre.maroneze@cea.fr>
Date: Wed, 7 Apr 2021 13:43:20 +0200
Subject: [PATCH] [Libs] add Integer.to_int*_opt functions

---
 src/libraries/stdlib/integer.ml  |  5 ++++
 src/libraries/stdlib/integer.mli | 42 +++++++++++++++++++++++++++++---
 2 files changed, 44 insertions(+), 3 deletions(-)

diff --git a/src/libraries/stdlib/integer.ml b/src/libraries/stdlib/integer.ml
index 103b96f8acb..2b68a32bcc1 100644
--- a/src/libraries/stdlib/integer.ml
+++ b/src/libraries/stdlib/integer.ml
@@ -101,6 +101,11 @@ let to_int = Z.to_int
 let to_int64 = Z.to_int64
 let to_int32 = Z.to_int32
 
+let wrap to_int i = try Some (to_int i) with Z.Overflow -> None
+let to_int_opt = wrap Z.to_int
+let to_int64_opt = wrap Z.to_int64
+let to_int32_opt = wrap Z.to_int32
+
 let of_string = Z.of_string
 let to_string = Z.to_string
 
diff --git a/src/libraries/stdlib/integer.mli b/src/libraries/stdlib/integer.mli
index 5a3019d2b08..989c259f597 100644
--- a/src/libraries/stdlib/integer.mli
+++ b/src/libraries/stdlib/integer.mli
@@ -122,9 +122,45 @@ val of_int : int -> t
 val of_int64 : Int64.t -> t
 val of_int32 : Int32.t -> t
 
-val to_int : t -> int (** @raise Z.Overflow if too big *)
-val to_int64 : t -> int64 (** @raise Z.Overflow if too big *)
-val to_int32 : t -> int32 (** @raise Z.Overflow if too big *)
+(**
+   @raise Z.Overflow if too big
+   @deprecated Frama-C+dev use [to_int_opt] instead
+*)
+val to_int : t -> int
+
+(**
+   @raise Z.Overflow if too big
+   @deprecated Frama-C+dev use [to_int64_opt] instead
+*)
+val to_int64 : t -> int64
+
+(**
+   @raise Z.Overflow if too big
+   @deprecated Frama-C+dev use [to_int32_opt] instead
+*)
+val to_int32 : t -> int32
+
+(**
+   Returns [Some i] if the number can be converted to an [int],
+   or [None] otherwise.
+   @since Frama-C+dev
+*)
+val to_int_opt : t -> int option
+
+(**
+   Returns [Some i] if the number can be converted to an [int64],
+   or [None] otherwise.
+   @since Frama-C+dev
+*)
+val to_int64_opt : t -> int64 option
+
+(**
+   Returns [Some i] if the number can be converted to an [int32],
+   or [None] otherwise.
+   @since Frama-C+dev
+*)
+val to_int32_opt : t -> int32 option
+
 
 val to_float : t -> float
 val of_float : float -> t
-- 
GitLab