Skip to content
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
14 changes: 14 additions & 0 deletions spec/std/slice_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,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 @@ -845,6 +845,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