From 443c22b1510e9a551a4e1a5173732d33e6f3eaca Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sat, 21 Nov 2020 00:21:26 +0800 Subject: [PATCH 1/2] Add wrapped unary negation to unsigned integer types --- spec/std/uint_spec.cr | 44 +++++++++++++++++++++++++++++++++++++++++++ src/int.cr | 21 +++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/spec/std/uint_spec.cr b/spec/std/uint_spec.cr index 1634b377e20e..7de658f63b70 100644 --- a/spec/std/uint_spec.cr +++ b/spec/std/uint_spec.cr @@ -6,4 +6,48 @@ describe "UInt" do (0_u32 <=> 0_u32).should eq(0) (0_u32 <=> 1_u32).should eq(-1) end + + describe "&-" do + it "returns the wrapped negation" do + x = &-0_u32 + x.should eq(0_u32) + x.should be_a(UInt32) + + x = &-100_u8 + x.should eq(156_u8) + x.should be_a(UInt8) + + x = &-1_u8 + x.should eq(255_u8) + x.should be_a(UInt8) + + x = &-255_u8 + x.should eq(1_u8) + x.should be_a(UInt8) + + x = &-1_u16 + x.should eq(65535_u16) + x.should be_a(UInt16) + + x = &-65535_u16 + x.should eq(1_u16) + x.should be_a(UInt16) + + x = &-1_u32 + x.should eq(4294967295_u32) + x.should be_a(UInt32) + + x = &-4294967295_u32 + x.should eq(1_u32) + x.should be_a(UInt32) + + x = &-1_u64 + x.should eq(18446744073709551615_u64) + x.should be_a(UInt64) + + x = &-18446744073709551615_u64 + x.should eq(1_u64) + x.should be_a(UInt64) + end + end end diff --git a/src/int.cr b/src/int.cr index 87e868995f89..5c4fcc031b47 100644 --- a/src/int.cr +++ b/src/int.cr @@ -980,6 +980,10 @@ struct UInt8 Number.expand_div [Float32], Float32 Number.expand_div [Float64], Float64 + def &- + 0_u8 &- self + end + def abs self end @@ -1020,6 +1024,10 @@ struct UInt16 Number.expand_div [Float32], Float32 Number.expand_div [Float64], Float64 + def &- + 0_u16 &- self + end + def abs self end @@ -1060,6 +1068,10 @@ struct UInt32 Number.expand_div [Float32], Float32 Number.expand_div [Float64], Float64 + def &- + 0_u32 &- self + end + def abs self end @@ -1100,6 +1112,10 @@ struct UInt64 Number.expand_div [Float32], Float32 Number.expand_div [Float64], Float64 + def &- + 0_u64 &- self + end + def abs self end @@ -1141,6 +1157,11 @@ struct UInt128 Number.expand_div [Float32], Float32 Number.expand_div [Float64], Float64 + def &- + # TODO: use 0_u128 - self + UInt128.new(0) &- self + end + def abs self end From fe9bffa08ab1c709fb87c27f97ecf1b185234fa7 Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sat, 21 Nov 2020 20:14:52 +0800 Subject: [PATCH 2/2] Update src/int.cr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Johannes Müller --- src/int.cr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/int.cr b/src/int.cr index 5c4fcc031b47..359921e40f8e 100644 --- a/src/int.cr +++ b/src/int.cr @@ -1158,7 +1158,7 @@ struct UInt128 Number.expand_div [Float64], Float64 def &- - # TODO: use 0_u128 - self + # TODO: use 0_u128 &- self UInt128.new(0) &- self end