Class: Bitcask::DataFile

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/bitcask/data_file.rb

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ DataFile

Returns a new instance of DataFile.



11
12
13
# File 'lib/bitcask/data_file.rb', line 11

def initialize(filename)
  @file = File.open(filename)
end

Instance Method Details

#[](offset, size = nil) ⇒ Object

Reads [key, value] from a particular offset. Also advances the cursor.



17
18
19
20
# File 'lib/bitcask/data_file.rb', line 17

def [](offset, size = nil)
  seek offset
  read size
end

#closeObject



22
23
24
# File 'lib/bitcask/data_file.rb', line 22

def close
  @file.close
end

#each(opts = {}) ⇒ Object

Iterates over every entry in this file, yielding an Entry. Options:

:rewind (true) - Rewind the file to the beginning, instead of starting
                 right here.
:raise_checksum (false) - Raise Bitcask::ChecksumError on crc failure, 
                 instead of silently continuing.


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/bitcask/data_file.rb', line 32

def each(opts = {})
  options = {
    :rewind => true,
    :raise_checksum => false
  }.merge opts

  rewind if options[:rewind]

  loop do
    begin
      o = read
      if o
        yield o
      else
        return self
      end
    rescue Bitcask::ChecksumError => e
      raise e if options[:raise]
    end
  end
end

#hint_fileObject



54
55
56
57
58
59
60
61
62
63
# File 'lib/bitcask/data_file.rb', line 54

def hint_file
  @hint_file ||= begin
    path = @file.path.sub(/\.data$/, '.hint')
    if File.exists? path
      h = Bitcask::HintFile.new path
      h.data_file = self
      h
    end
  end
end

#posObject Also known as: tell



65
66
67
# File 'lib/bitcask/data_file.rb', line 65

def pos
  @file.pos
end

#read(size = nil) ⇒ Object

Returns a single Entry read from the current offset, and advances to the next.

Can raise Bitcask::ChecksumError



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/bitcask/data_file.rb', line 74

def read(size = nil)
  if size
    f = StringIO.new @file.read(size)
  else
    f = @file
  end

  # Parse header
  header = f.read(14) or return
  crc, tstamp, ksz, value_sz = header.unpack "NNnN"
  
  # Read data
  key = f.read ksz
  value = f.read value_sz

  # CRC check
  raise Bitcask::ChecksumError unless crc == Zlib.crc32(header[4..-1] + key + value)

  Entry.new tstamp, key, value
end

#rewindObject

Rewinds the file.



96
97
98
# File 'lib/bitcask/data_file.rb', line 96

def rewind
  @file.rewind
end

#seek(offset) ⇒ Object

Seek to a given offset.



101
102
103
# File 'lib/bitcask/data_file.rb', line 101

def seek(offset)
  @file.seek offset
end