lib/protocol/http1/body/chunked.rb in protocol-http1-0.22.0 vs lib/protocol/http1/body/chunked.rb in protocol-http1-0.23.0

- old
+ new

@@ -2,11 +2,11 @@ # Released under the MIT License. # Copyright, 2019-2024, by Samuel Williams. # Copyright, 2023, by Thomas Morgan. -require 'protocol/http/body/readable' +require "protocol/http/body/readable" module Protocol module HTTP1 module Body class Chunked < HTTP::Body::Readable @@ -24,19 +24,23 @@ def empty? @stream.nil? end - def close(error = nil) - if @stream + def discard + if stream = @stream + @stream = nil + # We only close the connection if we haven't completed reading the entire body: unless @finished - @stream.close_read + stream.close_read end - - @stream = nil end + end + + def close(error = nil) + self.discard super end VALID_CHUNK_LENGTH = /\A[0-9a-fA-F]+\z/ @@ -65,16 +69,21 @@ end # Read trailing CRLF: chunk = @stream.read(length + 2) - # ...and chomp it off: - chunk.chomp!(CRLF) - - @length += length - @count += 1 - - return chunk + if chunk.bytesize == length + 2 + # ...and chomp it off: + chunk.chomp!(CRLF) + + @length += length + @count += 1 + + return chunk + else + # The stream has been closed before we have read the requested length: + self.discard + end end # If the stream has been closed before we have read the final chunk, raise an error: raise EOFError, "Stream closed before expected length was read!" end