Skip to content

Commit

Permalink
Add from_json for 128-bit integers (#13041)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored Feb 3, 2023
1 parent 95463a9 commit 7aefd61
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
11 changes: 11 additions & 0 deletions spec/std/json/serializable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ class JSONAttrWithBigDecimal
property value : BigDecimal
end

class JSONAttrWithInt128
include JSON::Serializable

property value : Int128
end

class JSONAttrWithTime
include JSON::Serializable

Expand Down Expand Up @@ -1045,6 +1051,11 @@ describe "JSON mapping" do
end
end

it "parses 128-bit integer" do
json = JSONAttrWithInt128.from_json(%({"value": #{Int128::MAX}}))
json.value.should eq Int128::MAX
end

describe "work with module and inheritance" do
it { JSONAttrModuleTest.from_json(%({"phoo": 20})).to_tuple.should eq({10, 20}) }
it { JSONAttrModuleTest.from_json(%({"phoo": 20})).to_tuple.should eq({10, 20}) }
Expand Down
12 changes: 12 additions & 0 deletions spec/std/json/serialization_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ describe "JSON serialization" do
UInt64.from_json(UInt64::MAX.to_s).should eq(UInt64::MAX)
end

it "does UInt128.from_json" do
UInt128.from_json(UInt128::MAX.to_s).should eq(UInt128::MAX)
end

it "does Int128.from_json" do
Int128.from_json(Int128::MAX.to_s).should eq(Int128::MAX)
end

it "raises ParserException for overflow UInt64.from_json" do
expect_raises(JSON::ParseException, "Can't read UInt64 at line 0, column 0") do
UInt64.from_json("1#{UInt64::MAX}")
Expand Down Expand Up @@ -501,6 +509,10 @@ describe "JSON serialization" do
1.to_json.should eq("1")
end

it "does for Int128" do
Int128::MAX.to_json.should eq(Int128::MAX.to_s)
end

it "does for Float64" do
1.5.to_json.should eq("1.5")
end
Expand Down
20 changes: 11 additions & 9 deletions src/json/from_json.cr
Original file line number Diff line number Diff line change
Expand Up @@ -125,19 +125,21 @@ def Bool.new(pull : JSON::PullParser)
end

{% for type, method in {
"Int8" => "i8",
"Int16" => "i16",
"Int32" => "i32",
"Int64" => "i64",
"UInt8" => "u8",
"UInt16" => "u16",
"UInt32" => "u32",
"UInt64" => "u64",
"Int8" => "i8",
"Int16" => "i16",
"Int32" => "i32",
"Int64" => "i64",
"Int128" => "i128",
"UInt8" => "u8",
"UInt16" => "u16",
"UInt32" => "u32",
"UInt64" => "u64",
"UInt128" => "u128",
} %}
def {{type.id}}.new(pull : JSON::PullParser)
location = pull.location
value =
{% if type == "UInt64" %}
{% if type == "UInt64" || type == "UInt128" || type == "Int128" %}
pull.read_raw
{% else %}
pull.read_int
Expand Down

0 comments on commit 7aefd61

Please sign in to comment.