String unpacker should sanitize by default

This commit is contained in:
ChillerDragon 2022-11-15 18:15:27 +01:00
parent 07eb3841d2
commit db56a97e8c
2 changed files with 23 additions and 1 deletions

View file

@ -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

View file

@ -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])