Sha256: cef714a509997c6aa2e1e50bc1dd8fa5ddb986a710315c7ed18ef9f7e264d30b

Contents?: true

Size: 1.07 KB

Versions: 8

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2020-2024, 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 read
					if chunk = super
						@digest.update(chunk)
						
						return chunk
					else
						@callback&.call(self)
						
						return nil
					end
				end
			end
		end
	end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
protocol-http-0.44.0 lib/protocol/http/body/digestable.rb
protocol-http-0.43.0 lib/protocol/http/body/digestable.rb
protocol-http-0.42.0 lib/protocol/http/body/digestable.rb
protocol-http-0.41.0 lib/protocol/http/body/digestable.rb
protocol-http-0.40.0 lib/protocol/http/body/digestable.rb
protocol-http-0.39.0 lib/protocol/http/body/digestable.rb
protocol-http-0.38.0 lib/protocol/http/body/digestable.rb
protocol-http-0.37.0 lib/protocol/http/body/digestable.rb