class Rsrb::Misc::TextUtils

Constants

XLATE_TABLE

Public Class Methods

filter(str) click to toggle source
# File lib/rsrb/core/util.rb, line 168
def TextUtils.filter(str)
  valid = str.unpack("C" * str.size).find_all {|c| XLATE_TABLE.include?(c.chr) }
  valid.pack("C" * valid.size)
end
optimize(str) click to toggle source
# File lib/rsrb/core/util.rb, line 151
def TextUtils.optimize(str)
  end_marker = true
  
  (0...str.length).each {|i|
    if end_marker && str[i].chr >= 'a' && str[i].chr <= 'z'
      str[i] = (str[i].bytes.first - 0x20).chr
      end_marker = false
    end
    
    if str[i].chr == "." || str[i].chr == "!" || str[i].chr == "?"
      end_marker = true
    end
  }
  
  str
end
pack(size, text) click to toggle source
# File lib/rsrb/core/util.rb, line 173
def TextUtils.pack(size, text)
  data = Array.new(size, 0)
  text = text[0...80] if text.size > 80
  text = text.downcase
  carry = -1
  offset = 0
  
  (0...text.size).each {|i|
    table_idx = XLATE_TABLE.find_index {|e| e == text[i].chr} || 0
    table_idx += 195 if table_idx > 12
    
    if carry == -1
      if table_idx < 13
        carry = table_idx
      else
        data[offset] = table_idx.byte
        offset += 1
      end
    elsif table_idx < 13
      data[offset] = ((carry << 4) + table_idx).byte
      carry = -1
      offset += 1
    else
      data[offset] = ((carry << 4) + (table_idx >> 4)).byte
      carry = table_idx.nibble
      offset += 1
    end
  }
  
  if carry != -1
    data[offset] = (carry << 4).byte
    offset += 1
  end
  
  data
end
repack(size, packet) click to toggle source
# File lib/rsrb/core/util.rb, line 210
def TextUtils.repack(size, packet)
  raw_data = packet.read_bytes(size).unpack("C" * size)
  chat_data = (0...size).collect {|i| (raw_data[size - i - 1] - 128).byte }
  unpacked = TextUtils.unpack(chat_data, size)
  unpacked = TextUtils.filter(unpacked)
  unpacked = TextUtils.optimize(unpacked)
  TextUtils.pack(size, unpacked)
end
unpack(data, size) click to toggle source
# File lib/rsrb/core/util.rb, line 126
def TextUtils.unpack(data, size)
  decode = Array.new(4096, 0)
  idx = 0
  high = -1
  
  (0...(size * 2)).each {|i|
    val = (data[i / 2] >> (4 - 4 * (i % 2))).nibble
    
    if high == -1
      if val < 13
        decode[idx] = XLATE_TABLE[val].bytes.first.byte
        idx += 1
      else
        high = val
      end
    else
      decode[idx] = XLATE_TABLE[((high << 4) + val) - 195].bytes.first.byte
      high = -1
      idx += 1
    end
  }
  
  decode[0...idx].pack("C" * idx)
end