Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/opal_patches.rb

Instance Method Summary collapse

Instance Method Details

#unpack1(format) ⇒ Object

‘unpack1(’H*‘)` returns one hex pair per byte. CRuby treats the receiver as a raw byte sequence (encoding ASCII-8BIT). Opal stores all Strings as JS Strings (UTF-16 chars) and reports `bytesize` as the UTF-8 encoded byte count, which double-counts chars > 0x7F.

For our crypto code, every “binary” String comes from ‘[hex].pack(’H*‘)` or other functions that pack each byte (0..255) as exactly one JS char. We therefore iterate by char (`length`) and read each char’s UTF-16 code unit as the byte value. This matches CRuby’s behavior for ASCII-8BIT encoded strings.

‘H*` produces 2 hex chars per byte. `H<n>` truncates to the first `n` nibbles (rounded down to whole bytes for an odd `n`).



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/opal_patches.rb', line 605

def unpack1(format)
  fmt = format.to_s
  unless fmt == "H*" || fmt =~ /\AH(\d+)\z/
    return unpack1_without_homura_hex(format)
  end

  requested_nibbles =
    if fmt == "H*"
      self.length * 2
    else
      fmt[1..-1].to_i
    end
  out = ""
  i = 0
  n = self.length
  while i < n && out.length < requested_nibbles
    b = `(#{self}.charCodeAt(#{i}) & 0xff)`
    h = b.to_s(16)
    h = "0" + h if h.length == 1
    out = out + h
    i += 1
  end
  out[0, requested_nibbles]
end

#unpack1_without_homura_hexObject



590
# File 'lib/opal_patches.rb', line 590

alias_method :unpack1_without_homura_hex, :unpack1