module BSON::Array::ClassMethods

Class-level methods to be added to the Array class.

Public Instance Methods

from_bson(buffer, **options) click to toggle source

Deserialize the array from BSON.

@note If the argument cannot be parsed, an exception will be raised

and the argument will be left in an undefined state. The caller
must explicitly call `rewind` on the buffer before trying to parse
it again.

@param [ ByteBuffer ] buffer The byte buffer.

@option options [ nil | :bson ] :mode Decoding mode to use.

@return [ Array ] The decoded array.

@see bsonspec.org/#/specification

# File lib/bson/array.rb, line 126
def from_bson(buffer, **options)
  if buffer.respond_to?(:get_array)
    buffer.get_array(**options)
  else
    parse_array_from_buffer(buffer, **options)
  end
end

Private Instance Methods

parse_array_elements_from_buffer(array, buffer, **options) click to toggle source

Parse a sequence of array elements from the buffer.

@param [ Array ] array the array to populate @param [ ByteBuf ] buffer the buffer to read from @param [ Hash ] options the optional keyword arguments

# File lib/bson/array.rb, line 163
def parse_array_elements_from_buffer(array, buffer, **options)
  while (type = buffer.get_byte) != NULL_BYTE
    buffer.get_cstring
    cls = BSON::Registry.get(type)
    value = if options.empty?
              cls.from_bson(buffer)
            else
              cls.from_bson(buffer, **options)
            end
    array << value
  end
end
parse_array_from_buffer(buffer, **options) click to toggle source

Parse an array from the buffer.

@param [ ByteBuf ] buffer the buffer to read from @param [ Hash ] options the optional keyword arguments

@return [ Array ] the array that was parsed

@raise [ BSON::Error::BSONDecodeError ] if the expected number of

bytes were not read from the buffer
# File lib/bson/array.rb, line 145
def parse_array_from_buffer(buffer, **options)
  new.tap do |array|
    start_position = buffer.read_position
    expected_byte_size = buffer.get_int32
    parse_array_elements_from_buffer(array, buffer, **options)
    actual_byte_size = buffer.read_position - start_position
    if actual_byte_size != expected_byte_size
      raise Error::BSONDecodeError,
            "Expected array to take #{expected_byte_size} bytes but it took #{actual_byte_size} bytes"
    end
  end
end