Skip to content

Commit aec396e

Browse files
committed
Merge pull request #42 from thatdutchguy/empty_chunks
fix: reading chunks from an empty (zero-length) grid-stored file
2 parents 504bdef + 6e66b11 commit aec396e

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

lib/mongo/gridfs/grid_io.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,8 +251,9 @@ def close
251251
# @return [Mongo::GridIO] self
252252
def each
253253
return read_all unless block_given?
254-
while chunk = read(chunk_size)
254+
while chunk = read(chunk_size)
255255
yield chunk
256+
break if chunk.empty?
256257
end
257258
self
258259
end

test/data/empty_data

Whitespace-only changes.

test/grid_test.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def read_and_write_stream(filename, read_length, opts={})
1313
read_data = ""
1414
while(chunk = file.read(read_length))
1515
read_data << chunk
16+
break if chunk.empty?
1617
end
1718
assert_equal data.length, read_data.length
1819
end
@@ -195,6 +196,39 @@ class GridTest < Test::Unit::TestCase
195196
end
196197
end
197198

199+
context "Grid streaming an empty file: " do
200+
setup do
201+
@grid = Grid.new(@db, 'test-fs')
202+
filename = 'empty_data'
203+
@io = File.open(File.join(File.dirname(__FILE__), 'data', filename), 'r')
204+
id = @grid.put(@io, :filename => filename)
205+
@file = @grid.get(id)
206+
@io.rewind
207+
@data = @io.read
208+
if @data.respond_to?(:force_encoding)
209+
@data.force_encoding("binary")
210+
end
211+
end
212+
213+
should "be equal in length" do
214+
@io.rewind
215+
assert_equal @io.read.length, @file.read.length
216+
end
217+
218+
should "read the file" do
219+
read_data = ""
220+
@file.each do |chunk|
221+
read_data << chunk
222+
end
223+
assert_equal @data.length, read_data.length
224+
end
225+
226+
should "read the file if no block is given" do
227+
read_data = @file.each
228+
assert_equal @data.length, read_data.length
229+
end
230+
end
231+
198232
context "Streaming: " do || {}
199233
setup do
200234
@grid = Grid.new(@db, 'test-fs')
@@ -204,6 +238,10 @@ class GridTest < Test::Unit::TestCase
204238
read_and_write_stream('small_data.txt', 1, :chunk_size => 2)
205239
end
206240

241+
should "put and get an empty io object" do
242+
read_and_write_stream('empty_data', 1)
243+
end
244+
207245
should "put and get a small io object" do
208246
read_and_write_stream('small_data.txt', 1)
209247
end

0 commit comments

Comments
 (0)