Codebase list ruby-maxmind-db / c0ed5af9-d9b9-47a8-bf44-9b96e7f204b8/main lib / maxmind / db / file_reader.rb
c0ed5af9-d9b9-47a8-bf44-9b96e7f204b8/main

Tree @c0ed5af9-d9b9-47a8-bf44-9b96e7f204b8/main (Download .tar.gz)

file_reader.rb @c0ed5af9-d9b9-47a8-bf44-9b96e7f204b8/mainraw · history · blame

require 'maxmind/db/errors'

module MaxMind # :nodoc:
  class DB
    class FileReader # :nodoc:
      def initialize(filename)
        @fh = File.new(filename, 'rb'.freeze)
        @size = @fh.size
        @mutex = Mutex.new
      end

      attr_reader :size

      def close
        @fh.close
      end

      def read(offset, size)
        return ''.freeze.b if size == 0

        # When we support only Ruby 2.5+, remove this and require pread.
        if @fh.respond_to?(:pread)
          buf = @fh.pread(size, offset)
        else
          @mutex.synchronize do
            @fh.seek(offset, IO::SEEK_SET)
            buf = @fh.read(size)
          end
        end

        raise InvalidDatabaseError, 'The MaxMind DB file contains bad data'.freeze if buf.nil? || buf.length != size

        buf
      end
    end
  end
end