1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
# frozen_string_literal: true
module HTTP2
module BufferUtils
if RUBY_VERSION > "3.4.0"
def append_str(str, data)
str.append_as_bytes(data)
end
else
def append_str(str, data)
enc = data.encoding
reset = false
if enc != Encoding::BINARY
reset = true
data = data.dup if data.frozen?
data.force_encoding(Encoding::BINARY)
end
str << data
ensure
data.force_encoding(enc) if reset
end
end
def read_str(str, n)
return "".b if n == 0
chunk = str.byteslice(0..n - 1)
remaining = str.byteslice(n..-1)
remaining ? str.replace(remaining) : str.clear
chunk
end
def read_uint32(str)
read_str(str, 4).unpack1("N")
end
def shift_byte(str)
read_str(str, 1).ord
end
end
# this mixin handles backwards-compatibility for the new packing options
# shipping with ruby 3.3 (see https://docs.ruby-lang.org/en/3.3/packed_data_rdoc.html)
module PackingExtensions
if RUBY_VERSION < "3.3.0"
def pack(array_to_pack, template, buffer:, offset: -1)
packed_str = array_to_pack.pack(template)
case offset
when -1
append_str(buffer, packed_str)
when 0
buffer.prepend(packed_str)
else
buffer.insert(offset, packed_str)
end
end
else
def pack(array_to_pack, template, buffer:, offset: -1)
case offset
when -1
array_to_pack.pack(template, buffer: buffer)
when 0
buffer.prepend(array_to_pack.pack(template))
else
buffer.insert(offset, array_to_pack.pack(template))
end
end
end
end
end
|