Class: LocalStorage

Inherits:
Storage show all
Defined in:
lib/immutablebox.rb

Instance Method Summary collapse

Methods inherited from Storage

#close

Constructor Details

#initialize(dir) ⇒ LocalStorage

Returns a new instance of LocalStorage.



253
254
255
# File 'lib/immutablebox.rb', line 253

def initialize(dir)
  @dir = dir
end

Instance Method Details

#compress?(piece) ⇒ Boolean

Returns:

  • (Boolean)


259
260
261
262
# File 'lib/immutablebox.rb', line 259

def compress?(piece)
  limit = 3 * TORRENT_PIECE_SIZE / 256
  [' ', "\n", "\000"].map{|c| piece.count(c)}.max < limit
end

#get(piece_hash) ⇒ Object



273
274
275
276
277
278
279
280
281
282
# File 'lib/immutablebox.rb', line 273

def get(piece_hash)
  filename = getfilename(piece_hash)
  return unless File.exist?(filename)
  piece = File.open(filename, 'rb'){|fd| fd.read}
  if piece.size == TORRENT_PIECE_SIZE
    piece
  else
    Zlib::Inflate.inflate(piece)
  end
end

#getfilename(piece_hash) ⇒ Object



263
264
265
# File 'lib/immutablebox.rb', line 263

def getfilename(piece_hash)
  "#{@dir}/#{Torrent.str2hex(piece_hash)}"
end

#openObject



256
257
258
# File 'lib/immutablebox.rb', line 256

def open
  FileUtils.mkdir_p(@dir)
end

#put(piece_hash, piece) ⇒ Object



266
267
268
269
270
271
272
# File 'lib/immutablebox.rb', line 266

def put(piece_hash, piece)
  filename = getfilename(piece_hash)
  return if File.exist?(filename)
  File.open(filename, 'wb') do |fd|
    fd.write(compress?(piece) ? piece : Zlib::Deflate.deflate(piece))
  end
end