Skip to content

Commit

Permalink
fix: reject out-of-bounds numbers as ints
Browse files Browse the repository at this point in the history
  • Loading branch information
mlms13 committed Oct 15, 2023
1 parent 2888c28 commit efab581
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Decode_Base.re
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ module Make =
let floatFromNumber = value(Js.Json.decodeNumber, `ExpectedNumber);

let intFromNumber = {
let isInt = v => v == 0.0 || mod_float(v, floor(v)) == 0.0;
let isInt = num => float(int_of_float(num)) == num;
flatMap(
v => isInt(v) ? pure(int_of_float(v)) : T.valErr(`ExpectedInt),
floatFromNumber,
Expand Down
5 changes: 5 additions & 0 deletions test/Decode_AsResult_OfParseError_test.re
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ describe("Simple decoders", () => {
|> toEqual(valErr(`ExpectedNumber, Sample.jsonString4))
);

test("intFromNumber (out-of-range int)", () =>
expect(Decode.intFromNumber(Sample.jsonLargeFloat))
|> toEqual(valErr(`ExpectedInt, Sample.jsonLargeFloat))
);

test("intFromNumber (float)", () =>
expect(Decode.intFromNumber(Sample.jsonFloat))
|> toEqual(valErr(`ExpectedInt, Sample.jsonFloat))
Expand Down
1 change: 1 addition & 0 deletions test/utils/Decode_TestSampleData.re
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ let jsonStringTrue: Js.Json.t = [%raw {| "true" |}];
let jsonString4: Js.Json.t = [%raw {| "4" |}];
let jsonFloat: Js.Json.t = [%raw {| 3.14 |}];
let jsonInt: Js.Json.t = [%raw {| 1 |}];
let jsonLargeFloat: Js.Json.t = [%raw {|1542433304450|}];
let jsonIntZero: Js.Json.t = [%raw {| 0 |}];
let jsonDateNumber: Js.Json.t = [%raw {| 1542433304450.0 |}];
let jsonDateString: Js.Json.t = [%raw {| "2018-11-17T05:40:35.869Z" |}];
Expand Down

0 comments on commit efab581

Please sign in to comment.