diff options
author | Chris Fallin <cfallin@c1f.net> | 2015-05-02 19:00:44 -0700 |
---|---|---|
committer | Chris Fallin <cfallin@c1f.net> | 2015-05-02 19:00:44 -0700 |
commit | dcf12136835af5239f0877aa455eabbd7b88b61e (patch) | |
tree | c40fc1f7c0c249c5d66fc6429222414cb5fcdf94 /ruby/ext/google/protobuf_c | |
parent | 4b2a6328bd2fe6a1d58bbe536c512c566a2673d3 (diff) | |
parent | d55733c76ee1db702529f38f602548ffe48a4ab1 (diff) | |
download | protobuf-dcf12136835af5239f0877aa455eabbd7b88b61e.tar.gz protobuf-dcf12136835af5239f0877aa455eabbd7b88b61e.tar.bz2 protobuf-dcf12136835af5239f0877aa455eabbd7b88b61e.zip |
Merge pull request #332 from skippy/nil-out-of-bounds
ruby: return nil for out of bounds
Diffstat (limited to 'ruby/ext/google/protobuf_c')
-rw-r--r-- | ruby/ext/google/protobuf_c/repeated_field.c | 20 |
1 files changed, 14 insertions, 6 deletions
diff --git a/ruby/ext/google/protobuf_c/repeated_field.c b/ruby/ext/google/protobuf_c/repeated_field.c index 8cf2e29b..5148ee87 100644 --- a/ruby/ext/google/protobuf_c/repeated_field.c +++ b/ruby/ext/google/protobuf_c/repeated_field.c @@ -47,6 +47,15 @@ RepeatedField* ruby_to_RepeatedField(VALUE _self) { return self; } +static int index_position(VALUE _index, RepeatedField* repeated_field) { + int index = NUM2INT(_index); + if (index < 0 && repeated_field->size > 0) { + index = repeated_field->size + index; + } + return index; +} + + /* * call-seq: * RepeatedField.each(&block) @@ -74,8 +83,7 @@ VALUE RepeatedField_each(VALUE _self) { * call-seq: * RepeatedField.[](index) => value * - * Accesses the element at the given index. Throws an exception on out-of-bounds - * errors. + * Accesses the element at the given index. Returns nil on out-of-bounds */ VALUE RepeatedField_index(VALUE _self, VALUE _index) { RepeatedField* self = ruby_to_RepeatedField(_self); @@ -83,9 +91,9 @@ VALUE RepeatedField_index(VALUE _self, VALUE _index) { upb_fieldtype_t field_type = self->field_type; VALUE field_type_class = self->field_type_class; - int index = NUM2INT(_index); + int index = index_position(_index, self); if (index < 0 || index >= self->size) { - rb_raise(rb_eRangeError, "Index out of range"); + return Qnil; } void* memory = (void *) (((uint8_t *)self->elements) + index * element_size); @@ -105,9 +113,9 @@ VALUE RepeatedField_index_set(VALUE _self, VALUE _index, VALUE val) { VALUE field_type_class = self->field_type_class; int element_size = native_slot_size(field_type); - int index = NUM2INT(_index); + int index = index_position(_index, self); if (index < 0 || index >= (INT_MAX - 1)) { - rb_raise(rb_eRangeError, "Index out of range"); + return Qnil; } if (index >= self->size) { RepeatedField_reserve(self, index + 1); |