From b8493d76f3ddc72cb2dfb520d5ff1c8316850cbb Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 13 Mar 2017 09:17:21 -0700 Subject: [PATCH] Check types passed in to packer dump methods --- ext/msgpack/packer_class.c | 6 ++++++ spec/packer_spec.rb | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/ext/msgpack/packer_class.c b/ext/msgpack/packer_class.c index f03da5a8..15eb32e0 100644 --- a/ext/msgpack/packer_class.c +++ b/ext/msgpack/packer_class.c @@ -159,6 +159,7 @@ static VALUE Packer_write_float(VALUE self, VALUE obj) static VALUE Packer_write_string(VALUE self, VALUE obj) { PACKER(self, pk); + Check_Type(obj, T_STRING); msgpack_packer_write_string_value(pk, obj); return self; } @@ -166,6 +167,7 @@ static VALUE Packer_write_string(VALUE self, VALUE obj) static VALUE Packer_write_array(VALUE self, VALUE obj) { PACKER(self, pk); + Check_Type(obj, T_ARRAY); msgpack_packer_write_array_value(pk, obj); return self; } @@ -173,6 +175,7 @@ static VALUE Packer_write_array(VALUE self, VALUE obj) static VALUE Packer_write_hash(VALUE self, VALUE obj) { PACKER(self, pk); + Check_Type(obj, T_HASH); msgpack_packer_write_hash_value(pk, obj); return self; } @@ -180,6 +183,7 @@ static VALUE Packer_write_hash(VALUE self, VALUE obj) static VALUE Packer_write_symbol(VALUE self, VALUE obj) { PACKER(self, pk); + Check_Type(obj, T_SYMBOL); msgpack_packer_write_symbol_value(pk, obj); return self; } @@ -191,6 +195,7 @@ static VALUE Packer_write_int(VALUE self, VALUE obj) if (FIXNUM_P(obj)) { msgpack_packer_write_fixnum_value(pk, obj); } else { + Check_Type(obj, T_BIGNUM); msgpack_packer_write_bignum_value(pk, obj); } return self; @@ -199,6 +204,7 @@ static VALUE Packer_write_int(VALUE self, VALUE obj) static VALUE Packer_write_extension(VALUE self, VALUE obj) { PACKER(self, pk); + Check_Type(obj, T_STRUCT); int ext_type = FIX2INT(RSTRUCT_GET(obj, 0)); if(ext_type < -128 || ext_type > 127) { diff --git a/spec/packer_spec.rb b/spec/packer_spec.rb index 86314847..ccb00fe1 100644 --- a/spec/packer_spec.rb +++ b/spec/packer_spec.rb @@ -189,6 +189,17 @@ def close Array.new.to_msgpack(MessagePack::Packer.new).to_str.should == Array.new.to_msgpack end + it 'raises type error on wrong type' do + packer = MessagePack::Packer.new + expect { packer.write_float "hello" }.to raise_error(TypeError) + expect { packer.write_string 1 }.to raise_error(TypeError) + expect { packer.write_array "hello" }.to raise_error(TypeError) + expect { packer.write_hash "hello" }.to raise_error(TypeError) + expect { packer.write_symbol "hello" }.to raise_error(TypeError) + expect { packer.write_int "hello" }.to raise_error(TypeError) + expect { packer.write_extension "hello" }.to raise_error(TypeError) + end + class CustomPack01 def to_msgpack(pk=nil) return MessagePack.pack(self, pk) unless pk.class == MessagePack::Packer