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`).



551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/opal_patches.rb', line 551

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

  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



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

alias_method :unpack1_without_homura_hex, :unpack1