Skip to content

Commit

Permalink
Pointer: raise on negative count in copy/move methods
Browse files Browse the repository at this point in the history
Ary Borenszweig committed Jun 13, 2016

Verified

This commit was signed with the committer’s verified signature. The key has expired.
andir Andreas Rammhold
1 parent c3cd3a7 commit ce2f6e2
Showing 2 changed files with 36 additions and 0 deletions.
28 changes: 28 additions & 0 deletions spec/std/pointer_spec.cr
Original file line number Diff line number Diff line change
@@ -35,6 +35,13 @@ describe "Pointer" do
p2[0].should eq(p1[0])
end
end

it "raises on negative count" do
p1 = Pointer.malloc(4, 0)
expect_raises(ArgumentError, "negative count") do
p1.copy_from(p1, -1)
end
end
end

describe "copy_to" do
@@ -46,6 +53,13 @@ describe "Pointer" do
p2[0].should eq(p1[0])
end
end

it "raises on negative count" do
p1 = Pointer.malloc(4, 0)
expect_raises(ArgumentError, "negative count") do
p1.copy_to(p1, -1)
end
end
end

describe "move_from" do
@@ -66,6 +80,13 @@ describe "Pointer" do
p1[2].should eq(1)
p1[3].should eq(2)
end

it "raises on negative count" do
p1 = Pointer.malloc(4, 0)
expect_raises(ArgumentError, "negative count") do
p1.move_from(p1, -1)
end
end
end

describe "move_to" do
@@ -86,6 +107,13 @@ describe "Pointer" do
p1[2].should eq(1)
p1[3].should eq(2)
end

it "raises on negative count" do
p1 = Pointer.malloc(4, 0)
expect_raises(ArgumentError, "negative count") do
p1.move_to(p1, -1)
end
end
end

describe "memcmp" do
8 changes: 8 additions & 0 deletions src/pointer.cr
Original file line number Diff line number Diff line change
@@ -146,6 +146,8 @@ struct Pointer(T)
# ptr1[3] # => 4
# ```
def copy_from(source : Pointer(T), count : Int)
raise ArgumentError.new("negative count") if count < 0

if self.class == source.class
Intrinsics.memcpy(self.as(Void*), source.as(Void*), (count * sizeof(T)).to_u32, 0_u32, false)
else
@@ -158,6 +160,8 @@ struct Pointer(T)

# :nodoc:
def copy_from(source : Pointer(NoReturn), count : Int)
raise ArgumentError.new("negative count") if count < 0

# We need this overload for cases when we have a pointer to unreachable
# data, like when doing Tuple.new.to_a
self
@@ -203,6 +207,8 @@ struct Pointer(T)
# ptr1[3] # => 3
# ```
def move_from(source : Pointer(T), count : Int)
raise ArgumentError.new("negative count") if count < 0

if self.class == source.class
Intrinsics.memmove(self.as(Void*), source.as(Void*), (count * sizeof(T)).to_u32, 0_u32, false)
else
@@ -219,6 +225,8 @@ struct Pointer(T)

# :nodoc:
def move_from(source : Pointer(NoReturn), count : Int)
raise ArgumentError.new("negative count") if count < 0

# We need this overload for cases when we have a pointer to unreachable
# data, like when doing Tuple.new.to_a
self

0 comments on commit ce2f6e2

Please sign in to comment.