Class: Foxify::ResumableSHA1

Inherits:
Object
  • Object
show all
Defined in:
lib/foxify/resumable_sha1.rb

Overview

A resumable SHA1 implementation

Constant Summary collapse

CHUNK_SIZE =
1024 * 1024 * 5

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(state = nil, finalized: false) ⇒ ResumableSHA1

Returns a new instance of ResumableSHA1.



12
13
14
15
16
# File 'lib/foxify/resumable_sha1.rb', line 12

def initialize(state = nil, finalized: false)
  @state = state
  @finalized = finalized
  reset unless @state
end

Instance Attribute Details

#finalizedObject (readonly)

Returns the value of attribute finalized.



10
11
12
# File 'lib/foxify/resumable_sha1.rb', line 10

def finalized
  @finalized
end

#stateObject (readonly)

Returns the value of attribute state.



10
11
12
# File 'lib/foxify/resumable_sha1.rb', line 10

def state
  @state
end

Class Method Details

.file(path) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/foxify/resumable_sha1.rb', line 50

def self.file(path)
  new.tap do |t|
    stream = File.open(path, "rb")
    t.update stream.read(CHUNK_SIZE) until stream.eof?
    stream.close
  end
end

.from_msgpack(data) ⇒ Object



66
67
68
69
# File 'lib/foxify/resumable_sha1.rb', line 66

def self.from_msgpack(data)
  state, finalized = MessagePack.unpack(data)
  new(state, finalized:)
end

.hexdigest(data) ⇒ Object



46
47
48
# File 'lib/foxify/resumable_sha1.rb', line 46

def self.hexdigest(data)
  new.update(data).hexdigest
end

Instance Method Details

#==(other) ⇒ Object



58
59
60
# File 'lib/foxify/resumable_sha1.rb', line 58

def ==(other)
  self.class == other.class && state == other.state && finalized == other.finalized
end

#hexdigestObject

Raises:



38
39
40
41
42
43
44
# File 'lib/foxify/resumable_sha1.rb', line 38

def hexdigest
  raise Foxify::Error, "Invalid state - this is already finalized" if @finalized

  Foxify::Native.sha1_finalize(@state).tap do
    @finalized = true
  end
end

#resetObject



18
19
20
21
22
# File 'lib/foxify/resumable_sha1.rb', line 18

def reset
  @state = Foxify::Native.sha1_init
  @finalized = false
  self
end

#to_msgpackObject



62
63
64
# File 'lib/foxify/resumable_sha1.rb', line 62

def to_msgpack
  [@state, @finalized].to_msgpack
end

#update(data) ⇒ Object Also known as: <<



24
25
26
27
28
29
# File 'lib/foxify/resumable_sha1.rb', line 24

def update(data)
  raise Foxify::Error "Invalid state - you must reset this instance before adding new data" if @finalized

  @state = Foxify::Native.sha1_update(@state, data)
  self
end

#write(data) ⇒ Object



33
34
35
36
# File 'lib/foxify/resumable_sha1.rb', line 33

def write(data)
  update(data)
  data.size
end