Skip to content

Commit

Permalink
Add Slice#same? (#14728)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Aug 19, 2024
1 parent 1237210 commit 2fcb168
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
14 changes: 14 additions & 0 deletions spec/std/slice_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,20 @@ describe "Slice" do
end
end

it "#same?" do
slice = Slice[1, 2, 3]

slice.should be slice
slice.should_not be slice.dup
slice.should_not be Slice[1, 2, 3]

(slice + 1).should be slice + 1
slice.should_not be slice + 1

(slice[0, 2]).should be slice[0, 2]
slice.should_not be slice[0, 2]
end

it "does macro []" do
slice = Slice[1, 'a', "foo"]
slice.should be_a(Slice(Int32 | Char | String))
Expand Down
15 changes: 15 additions & 0 deletions src/slice.cr
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,21 @@ struct Slice(T)
{% end %}
end

# Returns `true` if `self` and *other* point to the same memory, i.e. pointer
# and size are identical.
#
# ```
# slice = Slice[1, 2, 3]
# slice.same?(slice) # => true
# slice == Slice[1, 2, 3] # => false
# slice.same?(slice + 1) # => false
# (slice + 1).same?(slice + 1) # => true
# slice.same?(slice[0, 2]) # => false
# ```
def same?(other : self) : Bool
to_unsafe == other.to_unsafe && size == other.size
end

def to_slice : self
self
end
Expand Down
12 changes: 10 additions & 2 deletions src/spec/expectations.cr
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,19 @@ module Spec
end

def failure_message(actual_value)
"Expected: #{@expected_value.pretty_inspect} (object_id: #{@expected_value.object_id})\n got: #{actual_value.pretty_inspect} (object_id: #{actual_value.object_id})"
"Expected: #{@expected_value.pretty_inspect} (#{identify(@expected_value)})\n got: #{actual_value.pretty_inspect} (#{identify(actual_value)})"
end

def negative_failure_message(actual_value)
"Expected: value.same? #{@expected_value.pretty_inspect} (object_id: #{@expected_value.object_id})\n got: #{actual_value.pretty_inspect} (object_id: #{actual_value.object_id})"
"Expected: #{@expected_value.pretty_inspect} (#{identify(@expected_value)})\n got: #{actual_value.pretty_inspect} (#{identify(actual_value)})"
end

private def identify(value)
if value.responds_to?(:object_id)
"object_id: #{value.object_id}"
else
value.to_unsafe
end
end
end

Expand Down

0 comments on commit 2fcb168

Please sign in to comment.