Module: BSON::Encodable

Included in:
Array, Binary, Code, CodeWithScope, Hash, String
Defined in:
lib/bson/encodable.rb

Overview

Defines behaviour around objects that can be encoded.

Since:

  • 2.0.0

Constant Summary collapse

PLACEHOLDER =

A 4 byte placeholder that would be replaced by a length at a later point.

Since:

  • 2.0.0

0.to_bson.freeze
BSON_ADJUST =

Adjustment value for total number of document bytes.

Since:

  • 2.0.0

0.freeze
STRING_ADJUST =

Adjustment value for total number of string bytes.

Since:

  • 2.0.0

-4.freeze

Instance Method Summary collapse

Instance Method Details

#encode_binary_data_with_placeholder(encoded = ''.force_encoding(BINARY)) {|encoded| ... } ⇒ String

Encodes binary data with a generic placeholder value to be written later once all bytes have been written.

Examples:

Encode the BSON with placeholder bytes.

string.encode_binary_data_with_placeholder(encoded) do |encoded|
  each do |field, value|
    value.to_bson(encoded)
  end
end

Parameters:

  • encoded (String) (defaults to: ''.force_encoding(BINARY))

    The string to encode.

Yields:

  • (encoded)

Returns:

  • (String)

    The encoded string.

Since:

  • 2.0.0



78
79
80
81
82
83
84
# File 'lib/bson/encodable.rb', line 78

def encode_binary_data_with_placeholder(encoded = ''.force_encoding(BINARY))
  pos = encoded.bytesize
  encoded << PLACEHOLDER
  yield(encoded)
  encoded.set_int32(pos, encoded.bytesize - pos - 5)
  encoded
end

#encode_with_placeholder_and_null(adjust, encoded = ''.force_encoding(BINARY)) {|encoded| ... } ⇒ String

Encodes BSON to raw bytes, for types that require the length of the entire bytes to be present as the first word of the encoded string. This includes Hash, CodeWithScope.

Examples:

Encode the BSON with placeholder bytes.

hash.encode_with_placeholder_and_null(BSON_ADJUST, encoded) do |encoded|
  each do |field, value|
    value.to_bson(encoded)
  end
end

Parameters:

  • adjust (Integer)

    The number of bytes to adjust with.

  • encoded (String) (defaults to: ''.force_encoding(BINARY))

    The string to encode.

Yields:

  • (encoded)

Returns:

  • (String)

    The encoded string.

Since:

  • 2.0.0



54
55
56
57
58
59
60
61
# File 'lib/bson/encodable.rb', line 54

def encode_with_placeholder_and_null(adjust, encoded = ''.force_encoding(BINARY))
  pos = encoded.bytesize
  encoded << PLACEHOLDER
  yield(encoded)
  encoded << NULL_BYTE
  encoded.set_int32(pos, encoded.bytesize - pos + adjust)
  encoded
end