Skip to content

Commit

Permalink
Add spaceship operator to StaticArray (#11364)
Browse files Browse the repository at this point in the history
  • Loading branch information
henrikac authored Oct 27, 2021
1 parent f00f04a commit 8a8e36d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
10 changes: 10 additions & 0 deletions spec/std/static_array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ describe "StaticArray" do
end
end

describe "<=>" do
it "correctly compares two static arrays" do
array1 = StaticArray(Int32, 3).new(5)
array2 = StaticArray(Int32, 3).new(7)
(array1 <=> array2).should be < 0
(array2 <=> array1).should be > 0
(array1 <=> array1).should eq 0
end
end

describe "values_at" do
it "returns the given indexes" do
StaticArray(Int32, 4).new { |i| i + 1 }.values_at(1, 0, 2).should eq({2, 1, 3})
Expand Down
5 changes: 5 additions & 0 deletions src/static_array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
# doesn't specify a type but a size. Its value can be an `Int32` literal or
# constant.
struct StaticArray(T, N)
include Comparable(StaticArray)
include Indexable::Mutable(T)

# Creates a new `StaticArray` with the given *args*. The type of the
Expand Down Expand Up @@ -113,6 +114,10 @@ struct StaticArray(T, N)
false
end

def <=>(other : StaticArray)
to_slice <=> other.to_slice
end

@[AlwaysInline]
def unsafe_fetch(index : Int) : T
to_unsafe[index]
Expand Down

0 comments on commit 8a8e36d

Please sign in to comment.