client: add each_file_info iterator
[ruby-mogilefs-client.git] / lib / mogilefs / chunker.rb
blob0d5c627ad6a684958f64963996ecbb9baf6fb4ec
1 # -*- encoding: binary -*-
2 class MogileFS::Chunker
3   CRLF = "\r\n"
4   attr_reader :io
6   def initialize(io, md5, expect_md5)
7     @io = io
8     @md5 = md5
9     @expect_md5 = expect_md5
10   end
12   def write(buf)
13     rv = buf.bytesize
14     @io.write("#{rv.to_s(16)}\r\n")
15     @io.write(buf)
16     @md5.update(buf) if @md5
17     @io.write(CRLF)
18     rv
19   end
21   def flush
22     if @md5
23       content_md5 = [ @md5.digest ].pack('m').rstrip!
24       if @expect_md5.respond_to?(:call)
25         expect = @expect_md5.call.strip
26         if expect != content_md5
27           raise MogileFS::ChecksumMismatchError,
28             "expected: #{expect.inspect} actual: #{content_md5.inspect}"
29         end
30       end
31       @io.write("0\r\nContent-MD5: #{content_md5}\r\n\r\n")
32     else
33       @io.write("0\r\n\r\n")
34     end
35   end
36 end