Class: TrieFile::File

Inherits:
Object
  • Object
show all
Defined in:
lib/trie-file/file.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handle, hash_mode) ⇒ File

Returns a new instance of File.



48
49
50
51
52
# File 'lib/trie-file/file.rb', line 48

def initialize(handle, hash_mode)
  @handle = handle
  @semaphore = Mutex.new
  @hash_mode = hash_mode
end

Instance Attribute Details

#handleObject (readonly)

Returns the value of attribute handle.



19
20
21
# File 'lib/trie-file/file.rb', line 19

def handle
  @handle
end

#hash_modeObject (readonly)

Returns the value of attribute hash_mode.



19
20
21
# File 'lib/trie-file/file.rb', line 19

def hash_mode
  @hash_mode
end

Class Method Details

.open(path, mode, hash_mode = :none) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/trie-file/file.rb', line 21

def self.open(path, mode, hash_mode = :none)
  handle = ::File.open(path, mode)

  unless handle.binmode?
    raise ArgumentError, 'TrieFile must be opened in binary mode.'
  end

  file = new(handle, hash_mode)

  if block_given?
    yield file
    handle.close
  end

  file
end

.read(path, hash_mode = :none) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/trie-file/file.rb', line 38

def self.read(path, hash_mode = :none)
  root = nil

  ::File.open(path, 'rb') do |io|
    root = read_node(io)
  end

  Trie.new(root, hash_mode)
end

Instance Method Details

#closeObject



91
92
93
# File 'lib/trie-file/file.rb', line 91

def close
  handle.close
end

#closed?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/trie-file/file.rb', line 87

def closed?
  @handle.closed?
end

#find(key) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/trie-file/file.rb', line 59

def find(key)
  if closed?
    raise IOError, 'file is not currently open.'
  end

  @semaphore.synchronize do
    key = hash_key(key)
    cache.fetch(key) do
      handle.seek(0, IO::SEEK_SET)
      value = nil

      key.each_char do |char|
        value,  = self.class.read_node_header(handle)
         = .find do |data|
          data.first == char
        end

        return nil unless 
        handle.seek(.last, IO::SEEK_SET)
      end

      value = self.class.read_value(handle)
      cache[key] = value
      value
    end
  end
end

#write_trie(trie) ⇒ Object



54
55
56
57
# File 'lib/trie-file/file.rb', line 54

def write_trie(trie)
  mark(trie)
  self.class.write_node(trie.root, handle)
end