Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active January 22, 2024 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/87c155e1d0b0547436b3a4264a7f6a25 to your computer and use it in GitHub Desktop.
Save havenwood/87c155e1d0b0547436b3a4264a7f6a25 to your computer and use it in GitHub Desktop.
A spike implementing part of this nifty Ruby feature request: https://bugs.ruby-lang.org/issues/20196
# frozen_string_literal: true
module Kernel
def Binary(string, exception: true)
hex = string.b
hex.gsub!(/#[^#]*$\R*/, '')
hex.gsub!(/"[^"]*"/) do |quotes|
quotes[1..-2].unpack1('H*')
end
hex.delete!("\s\t")
if hex.match?(/\H/)
return unless exception
invalid_chars = hex.scan(/\H/).to_set.join
raise ArgumentError,
"invalid non-hex chars for Binary(): #{invalid_chars.inspect}"
end
[hex].pack('H*').freeze
end
end
string = <<-BINARY
89 "PNG" 0d0a1a0a # PNG header
0000000d # Length = 13 bytes
"IHDR" # IHDR chunk
00000060 # Width = 96px
00000060 # Height = 96px
08 06 # 8bpp RGBA
00 00 00 # deflate / no filter / non-interlaced}
BINARY
binary = Binary(string)
pp string: binary, encoding: binary.encoding, frozen: binary.frozen?
# => {:string=>"\x89PNG\r\n" + "\x1A\n" + "\x00\x00\x00\rIHDR\x00\x00\x00`\x00\x00\x00`\b\x06\x00\x00\x00",
# :encoding=>#<Encoding:ASCII-8BIT>,
# :frozen=>true}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment