Skip to content

Commit

Permalink
Fixes bug in handling of nil fields
Browse files Browse the repository at this point in the history
Fixes a bug that was causing the encoder to skip fields after other fields were set to nil.
  • Loading branch information
mherman-iseatz committed Dec 21, 2011
1 parent 3d50144 commit f40e7d3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/protocol_buffers/runtime/field.rb
Expand Up @@ -142,7 +142,7 @@ def has_#{name}?; true; end
def #{name}=(value)
field = fields[#{tag}]
if value.nil?
@set_fields.delete_at(#{tag})
@set_fields[#{tag}] = false
@#{name} = field.default_value
else
field.check_valid(value)
Expand Down
53 changes: 53 additions & 0 deletions spec/nil_fix_spec.rb
@@ -0,0 +1,53 @@
# Test by Mark Herman, II <mherman@iseatz.com>
#
# This is a test to demonstrate a significant bug with the handling of nil
# values. I will be contributing a fix that will cause these tests to pass.

# Here is an explanation of the bug...

# There is an array called @set_fields in our protobuf Message class.
# The Field class (field.rb) adds field accessors to the Message class that incorrect
# call delete_at on @set_fields rather than setting the value to false when a nil
# value is passed. So, @set_fields shrinks from the end rather than getting false
# values in the proper place. As more fields are set to nil, the Message class
# thinks fewer and fewer fields are set. The value_for_tag? method depends on the
# value of @set_fields. The encoder depends on value_for_tag?. So, as more nils
# are set, the encoded protobuffers shrink. The data isn't actually lost. It's
# never encoded.

require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'protocol_buffers'
require 'base64'

# This is a compiled Ruby protobuffer class that will demonstrate the bug
# with the handling of nil classes.

class TestMessage < ::ProtocolBuffers::Message
optional :string, :field1, 1
optional :string, :field2, 2

gen_methods! # new fields ignored after this point
end

describe "Error in nil handling" do
it "will flag field2 as not having a value when setting field1 to nil" do
tp = TestMessage.new # a test protobuffer
tp.field1 = "field1_value"
tp.field2 = "field2_value"

tp.field1 = nil

tp.value_for_tag?(2).should be_true
end

it "will still encode field2 after setting field1 to nil twice" do
tp = TestMessage.new # a test protobuffer
tp.field1 = "field1_value"
tp.field2 = "field2_value"

tp.field1 = nil
tp.field1 = nil

Base64.encode64(tp.to_s).length.should be > 0
end
end

0 comments on commit f40e7d3

Please sign in to comment.