get_file_data: avoid exposing users to copy_stream invocation
[ruby-mogilefs-client.git] / lib / mogilefs / copy_stream.rb
blob7531f545052720f4e8f7b6576eb17b04aabed3a6
1 # -*- encoding: binary -*-
3 # internal compatibility class for older Rubies
4 module MogileFS::CopyStream # :nodoc:
5   def self.copy_stream(src, dst)
6     src_io = src.respond_to?(:to_str) ? File.open(src) : src
7     dst_io = dst.respond_to?(:to_str) ? File.open(dst, "w") : dst
8     buf = ""
9     written = 0
10     if src_io.respond_to?(:readpartial)
11       begin
12         src_io.readpartial(0x4000, buf)
13         written += dst_io.write(buf)
14       rescue EOFError
15         break
16       end while true
17     else
18       while src_io.read(0x4000, buf)
19         written += dst_io.write(buf)
20       end
21     end
22     dst_io.flush if dst_io.respond_to?(:flush)
23     written
24     ensure
25       src_io.close if src_io != src
26       dst_io.close if dst_io != dst
27   end
28 end