Add packer tests

This commit is contained in:
ChillerDragon 2022-11-06 13:35:10 +01:00
parent 11a7e9629d
commit 0479e7f07e
3 changed files with 48 additions and 29 deletions

View file

@ -46,6 +46,7 @@ class Packer
end
def self.pack_big_int(sign, num)
num += 1 if sign == '1'
num_bits = num.to_s(2)
first = "1#{sign}#{num_bits[-6..]}"
@ -129,32 +130,3 @@ class Unpacker
bits.join.to_i(2) * sign
end
end
def todo_make_this_rspec_test
# # single byte int
# p Packer.pack_int(1) == [1]
# p Packer.pack_int(3) == [3]
# p Packer.pack_int(16) == [16]
# p Packer.pack_int(63) == [63]
# # negative single byte
# p Packer.pack_int(-1) == [64]
# p Packer.pack_int(-2) == [65]
# p Packer.pack_int(-1).first.to_s(2) == '1000000'
# p Packer.pack_int(-2).first.to_s(2) == '1000001'
# p Packer.pack_int(-3).first.to_s(2) == '1000010'
# p Packer.pack_int(-4).first.to_s(2) == '1000011'
p Packer.pack_int(64).map { |e| e.to_s(2).rjust(8, '0') } == %w[10000000 00000001]
p Packer.pack_int(-64).map { |e| e.to_s(2).rjust(8, '0') } == %w[11000000 00000000]
# # multi byte int
# p Packer.pack_int(64) == [128, 1]
# p Packer.pack_int(99999999999999999) == [191, 131, 255, 147, 246, 194, 215, 232, 88]
# # string
# p Packer.pack_str("A") == [65, 0]
end
# todo_make_this_rspec_test

47
spec/04_packer_spec.rb Normal file
View file

@ -0,0 +1,47 @@
# frozen_string_literal: true
require_relative '../lib/packer'
describe 'Packer', :packer do
context 'Pack strings' do
it 'Should pack a single string' do
expect(Packer.pack_str('A')).to eq([65, 0])
end
end
context 'Pack single byte integers' do
it 'Should pack positive' do
expect(Packer.pack_int(1)).to eq([1])
expect(Packer.pack_int(3)).to eq([3])
expect(Packer.pack_int(16)).to eq([16])
expect(Packer.pack_int(63)).to eq([63])
end
it 'Should pack negative' do
expect(Packer.pack_int(-1)).to eq([64])
expect(Packer.pack_int(-2)).to eq([65])
end
it 'Should pack negative match binary' do
expect(Packer.pack_int(-1).first.to_s(2)).to eq('1000000')
expect(Packer.pack_int(-2).first.to_s(2)).to eq('1000001')
expect(Packer.pack_int(-3).first.to_s(2)).to eq('1000010')
expect(Packer.pack_int(-4).first.to_s(2)).to eq('1000011')
end
end
context 'Pack multi byte integers' do
it 'Should pack positive' do
expect(Packer.pack_int(64).map { |e| e.to_s(2).rjust(8, '0') }).to eq(%w[10000000 00000001])
expect(Packer.pack_int(64)).to eq([128, 1])
end
it 'Should pack negative' do
expect(Packer.pack_int(-65).map { |e| e.to_s(2).rjust(8, '0') }).to eq(%w[11000001 00000001])
end
it 'Should pack large numbers' do
expect(Packer.pack_int(99_999_999_999_999_999)).to eq([191, 131, 255, 147, 246, 194, 215, 232, 88])
end
end
end