Class: Rufus::Tokyo::Map

Inherits:
Object
  • Object
show all
Includes:
CabinetLibMixin, HashMethods
Defined in:
lib/rufus/tokyo/cabinet/util.rb

Overview

A Tokyo Cabinet in-memory (tcutil.h) map

tokyocabinet.sourceforge.net/spex-en.html#tcutilapi

Instance Attribute Summary

Attributes included from HashMethods

#default_proc

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HashMethods

#[], #default, #default=, #each, #merge, #merge!, #to_a, #to_h, #values

Constructor Details

#initialize(pointer = nil) ⇒ Map

Creates an empty instance of a Tokyo Cabinet in-memory map

(It’s OK to pass the pointer of a C map directly, this is in fact used in rufus/tokyo/table when retrieving entries)



52
53
54
# File 'lib/rufus/tokyo/cabinet/util.rb', line 52

def initialize (pointer = nil)
  @map = pointer || lib.tcmapnew
end

Class Method Details

.from_h(h) ⇒ Object

Turns a Ruby hash into a Tokyo Cabinet Map and returns it



142
143
144
# File 'lib/rufus/tokyo/cabinet/util.rb', line 142

def self.from_h (h)
  h.inject(Map.new) { |m, (k, v)| m[k] = v; m }
end

.to_h(map_pointer, free = true) ⇒ Object

Turns a given Tokyo map structure into a Ruby Hash. By default (free = true) will dispose of the map before replying with the Ruby Hash.



132
133
134
135
136
137
# File 'lib/rufus/tokyo/cabinet/util.rb', line 132

def self.to_h (map_pointer, free = true)
  m = self.new(map_pointer)
  h = m.to_h
  m.free if free
  h
end

Instance Method Details

#[]=(k, v) ⇒ Object

Inserts key/value pair



59
60
61
62
# File 'lib/rufus/tokyo/cabinet/util.rb', line 59

def []= (k, v)
  lib.tcmapput2(m, k, v)
  v
end

#clearObject

Empties the map



77
78
79
# File 'lib/rufus/tokyo/cabinet/util.rb', line 77

def clear
  lib.tcmapclear(m)
end

#delete(k) ⇒ Object

Deletes an entry



67
68
69
70
71
72
# File 'lib/rufus/tokyo/cabinet/util.rb', line 67

def delete (k)
  v = self[k]
  return nil unless v
  (lib.tcmapout2(m, k) == 1) || raise("failed to remove key '#{k}'")
  v
end

#freeObject Also known as: destroy, close

Frees the map (nukes it from memory)



111
112
113
114
# File 'lib/rufus/tokyo/cabinet/util.rb', line 111

def free
  lib.tcmapdel(@map)
  @map = nil
end

#keysObject

Returns an array of all the keys in the map



92
93
94
95
96
97
# File 'lib/rufus/tokyo/cabinet/util.rb', line 92

def keys
  a = []
  lib.tcmapiterinit(m)
  while (k = (lib.tcmapiternext2(m) rescue nil)); a << k; end
  a
end

#pointerObject Also known as: m

Returns the pointer to the underlying Tokyo Cabinet map



122
123
124
# File 'lib/rufus/tokyo/cabinet/util.rb', line 122

def pointer
  @map || raise('map got freed, cannot use anymore')
end

#sizeObject Also known as: length

Returns the count of entries in the map



102
103
104
# File 'lib/rufus/tokyo/cabinet/util.rb', line 102

def size
  lib.tcmaprnum(m)
end