Skip to content

Commit

Permalink
Merge pull request #117 from localshred/bj/fix_frozen_string_encode
Browse files Browse the repository at this point in the history
Dup string value when encoding if it is frozen
  • Loading branch information
localshred committed Sep 6, 2013
2 parents d95dbcc + 302ef0c commit 0b42aa2
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/protobuf/field/string_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ def decode(bytes)
bytes
end

# TODO: make replace character configurable?
def encode(value)
# TODO: make replace character configurable?
value = value.dup if value.frozen?
value.encode!(::Protobuf::Field::StringField::ENCODING, :invalid => :replace, :undef => :replace, :replace => "")
value.force_encoding(::Protobuf::Field::BytesField::BYTES_ENCODING)

Expand Down
23 changes: 23 additions & 0 deletions spec/lib/protobuf/field/string_field_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require 'spec_helper'

describe ::Protobuf::Field::StringField do
describe '#encode' do
context 'when a repeated string field contains frozen strings' do
it 'does not raise an encoding error' do
expect {
frozen_strings = [ "foo".freeze, "bar".freeze, "baz".freeze ]
::Test::ResourceFindRequest.encode(:name => 'resource', :widgets => frozen_strings)
}.not_to raise_error
end
end

context 'when a repeated bytes field contains frozen strings' do
it 'does not raise an encoding error' do
expect {
frozen_strings = [ "foo".freeze, "bar".freeze, "baz".freeze ]
::Test::ResourceFindRequest.encode(:name => 'resource', :widget_bytes => frozen_strings)
}.not_to raise_error
end
end
end
end
2 changes: 2 additions & 0 deletions spec/support/test/resource.pb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ class NestedLevelOne < ::Protobuf::Message; end
class ResourceFindRequest
required ::Protobuf::Field::StringField, :name, 1
optional ::Protobuf::Field::BoolField, :active, 2
repeated ::Protobuf::Field::StringField, :widgets, 3
repeated ::Protobuf::Field::BytesField, :widget_bytes, 4
end

class ResourceSleepRequest
Expand Down
2 changes: 2 additions & 0 deletions spec/support/test/resource.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ enum StatusType {
message ResourceFindRequest {
required string name = 1;
optional bool active = 2;
repeated string widgets = 3;
repeated bytes widget_bytes = 4;
}

message ResourceSleepRequest {
Expand Down

0 comments on commit 0b42aa2

Please sign in to comment.