Sha256: 942afb820b05516883e1619fbf4f695e1587d5e9798ae59f5efc059b5b8a0f7c

Contents?: true

Size: 1.11 KB

Versions: 26

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2020-2023, by Samuel Williams.

require_relative 'wrapper'

require 'digest/sha2'

module Protocol
	module HTTP
		module Body
			# Invokes a callback once the body has finished reading.
			class Digestable < Wrapper
				def self.wrap(message, digest = Digest::SHA256.new, &block)
					if body = message&.body and !body.empty?
						message.body = self.new(message.body, digest, block)
					end
				end
				
				# @parameter callback [Block] The callback is invoked when the digest is complete.
				def initialize(body, digest = Digest::SHA256.new, callback = nil)
					super(body)
					
					@digest = digest
					@callback = callback
				end
				
				def digest
					@digest
				end
				
				def etag(weak: false)
					if weak
						"W/\"#{digest.hexdigest}\""
					else
						"\"#{digest.hexdigest}\""
					end
				end
				
				def stream?
					false
				end
				
				def read
					if chunk = super
						@digest.update(chunk)
						
						return chunk
					else
						@callback&.call(self)
						
						return nil
					end
				end
			end
		end
	end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
protocol-http-0.32.0 lib/protocol/http/body/digestable.rb
protocol-http-0.31.0 lib/protocol/http/body/digestable.rb
protocol-http-0.30.0 lib/protocol/http/body/digestable.rb
protocol-http-0.29.0 lib/protocol/http/body/digestable.rb
protocol-http-0.28.2 lib/protocol/http/body/digestable.rb
protocol-http-0.28.1 lib/protocol/http/body/digestable.rb
protocol-http-0.28.0 lib/protocol/http/body/digestable.rb
protocol-http-0.27.0 lib/protocol/http/body/digestable.rb
protocol-http-0.26.8 lib/protocol/http/body/digestable.rb
protocol-http-0.26.7 lib/protocol/http/body/digestable.rb
protocol-http-0.26.6 lib/protocol/http/body/digestable.rb
protocol-http-0.26.5 lib/protocol/http/body/digestable.rb
protocol-http-0.26.4 lib/protocol/http/body/digestable.rb
protocol-http-0.26.3 lib/protocol/http/body/digestable.rb
protocol-http-0.26.2 lib/protocol/http/body/digestable.rb
protocol-http-0.26.1 lib/protocol/http/body/digestable.rb
protocol-http-0.26.0 lib/protocol/http/body/digestable.rb
protocol-http-0.25.0 lib/protocol/http/body/digestable.rb
protocol-http-0.24.7 lib/protocol/http/body/digestable.rb
protocol-http-0.24.6 lib/protocol/http/body/digestable.rb