diff --git a/lib/packer.rb b/lib/packer.rb index 4dc3472..c061736 100644 --- a/lib/packer.rb +++ b/lib/packer.rb @@ -2,6 +2,10 @@ require_relative 'array' +SANITIZE = 1 +SANITIZE_CC = 2 +SKIP_START_WHITESPACES = 4 + class Packer # Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign def self.pack_int(num) @@ -79,13 +83,22 @@ class Unpacker end end - def get_string + def str_sanitize(str) + letters = str.chars + letters.map! do |c| + c.ord < 32 && c != "\r" && c != "\n" && c != "\t" ? ' ' : c + end + letters.join + end + + def get_string(sanitize = SANITIZE) return nil if @data.nil? str = '' @data.each_with_index do |byte, index| if byte.zero? @data = index == @data.length - 1 ? nil : @data[(index + 1)..] + str = str_sanitize(str) unless (sanitize & SANITIZE).zero? return str end str += byte.chr diff --git a/spec/05_unpacker_spec.rb b/spec/05_unpacker_spec.rb index e282b52..b646e3d 100644 --- a/spec/05_unpacker_spec.rb +++ b/spec/05_unpacker_spec.rb @@ -12,6 +12,15 @@ describe 'Unpacker', :unpacker do end end + context 'Unpack strings sanitize (default)' do + it 'Should replace bytes lower than 32 with spaces' do + u = Unpacker.new([0x02, 0x41, 0x41, 0x00, 0x1F, 0x42, 0x42, 0x00]) + expect(u.get_string).to eq(' AA') + expect(u.get_string).to eq(' BB') + expect(u.get_string).to eq(nil) + end + end + context 'Unpack single byte integers' do it 'Should unpack positive integers' do u = Unpacker.new([0x01, 0x02])