From b4ed3084b3667e0baefd4b4a4cb2bc943dec3d82 Mon Sep 17 00:00:00 2001 From: Oleg Pudeyev <39304720+p-mongo@users.noreply.github.com> Date: Tue, 3 Nov 2020 16:33:12 -0500 Subject: [PATCH] RUBY-2435 Document & test ByteBuffer length decreasing after reads (#223) Co-authored-by: Oleg Pudeyev --- ext/bson/init.c | 10 ++++++++++ spec/bson/byte_buffer_spec.rb | 14 +++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/ext/bson/init.c b/ext/bson/init.c index 63d6252e5..9de5d75b5 100644 --- a/ext/bson/init.c +++ b/ext/bson/init.c @@ -56,6 +56,16 @@ void Init_bson_native() rb_define_alloc_func(rb_byte_buffer_class, rb_bson_byte_buffer_allocate); rb_define_method(rb_byte_buffer_class, "initialize", rb_bson_byte_buffer_initialize, -1); + + /* + * call-seq: + * buffer.length -> Fixnum + * + * Returns the number of bytes available to be read in the buffer. + * + * When a buffer is being written to, each added byte increases its length. + * When a buffer is being read from, each read byte decreases its length. + */ rb_define_method(rb_byte_buffer_class, "length", rb_bson_byte_buffer_length, 0); /* diff --git a/spec/bson/byte_buffer_spec.rb b/spec/bson/byte_buffer_spec.rb index b098bb5a4..79de137d9 100644 --- a/spec/bson/byte_buffer_spec.rb +++ b/spec/bson/byte_buffer_spec.rb @@ -42,7 +42,6 @@ end end - context 'when the byte buffer is initialized with some bytes' do let(:buffer) do @@ -53,6 +52,19 @@ expect(buffer.length).to eq(2) end end + + context 'after the byte buffer was read from' do + + let(:buffer) do + described_class.new({}.to_bson.to_s) + end + + it 'returns the number of bytes remaining in the buffer' do + expect(buffer.length).to eq(5) + buffer.get_int32 + expect(buffer.length).to eq(1) + end + end end describe '#rewind!' do