Skip to content

Commit

Permalink
Check types passed in to packer dump methods
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Mar 13, 2017
1 parent 9feb40f commit b8493d7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ext/msgpack/packer_class.c
Original file line number Diff line number Diff line change
Expand Up @@ -159,27 +159,31 @@ 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;
}

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;
}

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;
}

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;
}
Expand All @@ -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;
Expand All @@ -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) {
Expand Down
11 changes: 11 additions & 0 deletions spec/packer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit b8493d7

Please sign in to comment.