quick fix; ok json response ~~

This commit is contained in:
swrup 2025-10-18 20:28:38 +02:00
parent 1674e338ac
commit 5e6f8766fb
4 changed files with 28 additions and 23 deletions

View file

@ -1,6 +1,7 @@
(* TODO
have safe amount arithmetic
make type private *)
make type private
use config currency option *)
(* Amounts of currency, serialized as `<Currency>:<IntegerPart>.<FractionalPart>`
Fixed-precision numbers with 8 decimal places.
- <Currency> must be at most 11 characters long
@ -18,22 +19,19 @@ type t = {
}
let ( let* ) o f = match o with Ok v -> f v | Error _ as e -> e
let check_not msg = function false -> Ok () | true -> Error msg
let value_upper_bound = Z.(pow (of_int 2) 52) |> Z.to_int64
let fraction_upper_bound = Int64.of_int 100_000_000
let make ~sign ~currency ~value ~fraction =
let value_upper_bound = Z.(pow (of_int 2) 52) |> Z.to_int64 in
let fraction_upper_bound = Int64.of_int 99_999_999 in
let* () = if value < Int64.zero then Error "value is negative" else Ok () in
let* () = check_not "value is negative" (value < Int64.zero) in
let* () = check_not "fraction is negative" (fraction < Int64.zero) in
let* () =
if fraction < Int64.zero then Error "fraction is negative" else Ok ()
check_not "value is greater than 2^52" (value > value_upper_bound)
in
let* () =
if value > value_upper_bound then Error "value is greater than 2^52"
else Ok ()
in
let* () =
if fraction > fraction_upper_bound then
Error "fraction have more than 8 decimal digits"
else Ok ()
check_not "fraction has more than 8 decimal digits"
(fraction >= fraction_upper_bound)
in
Ok { sign; currency; value; fraction }
@ -46,8 +44,8 @@ let to_string =
in
let pp_currency ppf = function `Eur -> string ppf "EUR" in
fun ppf { sign; currency; value; fraction } ->
pf ppf "%a%a:%Ld.%Ld" (Fmt.option pp_sign) sign pp_currency currency value
fraction
pf ppf "%a%a:%Ld.%02Ld" (Fmt.option pp_sign) sign pp_currency currency
value fraction
in
Fmt.str "%a" pp