<commit_before>
module MaxMindDB
  class LowMemoryReader
    METADATA_MAX_SIZE = 128 * 1024

    def initialize(path)
      @mutex = Mutex.new
      @file = File.open(path, 'rb')
    end

    def [](pos, length=1)
      atomic_read(length, pos)
    end

    def rindex(search)
      base = [0, @file.size - METADATA_MAX_SIZE].max
      tail = atomic_read(METADATA_MAX_SIZE, base)
      pos = tail.rindex(search)
      return nil if pos.nil?
      base + pos
    end

    def atomic_read(length, pos)
      @mutex.synchronize do
        @file.seek(pos)
        @file.read(length)
      end
    end
  end
end<commit_msg>Add support for IO.pread if available.<commit_after>
require 'thread'

begin
  # For ruby versions that do not have IO.pread.
  require 'io/extra'
rescue LoadError
  # Fallback to seek/read.
end

module MaxMindDB
  class LowMemoryReader
    METADATA_MAX_SIZE = 128 * 1024

    def initialize(path)
      @mutex = Mutex.new
      @file = File.open(path, 'rb')
    end

    def [](pos, length=1)
      atomic_read(length, pos)
    end

    def rindex(search)
      base = [0, @file.size - METADATA_MAX_SIZE].max
      tail = atomic_read(METADATA_MAX_SIZE, base)
      pos = tail.rindex(search)
      return nil if pos.nil?
      base + pos
    end

    def atomic_read(length, pos)
      if IO.respond_to?(:pread)
        IO.pread(@file.fileno, length, pos)
      else
        @mutex.synchronize do
          @file.seek(pos)
          @file.read(length)
        end
      end
    end
  end
end
{'fraction_non_alphanumeric': 0.09741550695825049, 'fraction_numerical': 0.011928429423459244, 'mean_word_length': 2.2543103448275863, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1743974', 'n_tokens_mistral': 546, 'n_tokens_neox': 514, 'n_words': 132}