# typed: strict
class HexUtil
  extend T::Sig

  sig { params(str: String).returns(String) }
  def self.hex2bin(str)
    [str].pack("H*")
  end

  sig { params(bin: String).returns(String) }
  def self.bin2hex(bin)
    unpacked = bin.unpack("H*").first
    raise("invalid bin2hex: nil") if unpacked.nil?
    raise("invalid bin2hex: #{unpacked.class}") unless unpacked.is_a?(String)
    unpacked
  end

  sig { params(size: Integer).returns(String) }
  def self.humansize(size)
    units = %w[B KiB MiB GiB TiB Pib EiB ZiB]
    return "0.0 B" if size == 0
    exp = (Math.log(size) / Math.log(1024)).to_i
    exp += 1 if (size.to_f / 1024**exp >= 1024 - 0.05)
    exp = units.size - 1 if exp > units.size - 1
    "%.1f %s" % [size.to_f / 1024**exp, units[exp]]
  end
end
