Skip to content

Commit

Permalink
Showing 2 changed files with 39 additions and 0 deletions.
17 changes: 17 additions & 0 deletions spec/std/io/io_spec.cr
Original file line number Diff line number Diff line change
@@ -155,6 +155,23 @@ describe IO do
dst.to_s.should eq(string)
end

it "copies with limit" do
string = "abcあぼ"
src = MemoryIO.new(string)
dst = MemoryIO.new
IO.copy(src, dst, 3).should eq(3)
dst.to_s.should eq("abc")
end

it "raises on copy with negative limit" do
string = "abcあぼ"
src = MemoryIO.new(string)
dst = MemoryIO.new
expect_raises(ArgumentError, "negative limit") do
IO.copy(src, dst, -10)
end
end

it "reopens" do
File.open("#{__DIR__}/../data/test_file.txt") do |file1|
File.open("#{__DIR__}/../data/test_file.ini") do |file2|
22 changes: 22 additions & 0 deletions src/io.cr
Original file line number Diff line number Diff line change
@@ -896,6 +896,28 @@ module IO
len < 0 ? len : count
end

# Copy at most *limit* bytes from *src* to *dst*.
#
# ```
# io = MemoryIO.new "hello"
# io2 = MemoryIO.new
#
# IO.copy io, io2, 3
#
# io2.to_s # => "hel"
# ```
def self.copy(src, dst, limit : Int)
raise ArgumentError.new("negative limit") if limit < 0

buffer = uninitialized UInt8[1024]
remaining = limit
while (len = src.read(buffer.to_slice[0, Math.min(buffer.size, Math.max(remaining, 0))])) > 0
dst.write buffer.to_slice[0, len]
remaining -= len
end
limit - remaining
end

# :nodoc:
struct LineIterator(I, A)
include Iterator(String)

0 comments on commit 6dced6c

Please sign in to comment.