Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wrapped unary negation to unsigned integer types #9947

Merged
merged 2 commits into from
Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions spec/std/uint_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
21 changes: 21 additions & 0 deletions src/int.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down