Module: Moped::BSON::Extensions::String

Included in:
String
Defined in:
lib/moped/bson/extensions/string.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#__bson_dump__(io, key) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/moped/bson/extensions/string.rb', line 12

def __bson_dump__(io, key)
  io << Types::STRING
  io << key.to_bson_cstring

  data = to_utf8_binary

  io << [ data.bytesize + 1 ].pack(INT32_PACK)
  io << data
  io << NULL_BYTE
end

#from_utf8_binaryObject



40
41
42
# File 'lib/moped/bson/extensions/string.rb', line 40

def from_utf8_binary
  force_encoding(UTF8_ENCODING).encode!
end

#to_bson_cstringObject



23
24
25
26
27
28
29
30
# File 'lib/moped/bson/extensions/string.rb', line 23

def to_bson_cstring
  if include? NULL_BYTE
    raise EncodingError, "#{inspect} cannot be converted to a BSON " \
      "cstring because it contains a null byte"
  end

  to_utf8_binary << NULL_BYTE
end

#to_utf8_binaryObject



32
33
34
35
36
37
38
# File 'lib/moped/bson/extensions/string.rb', line 32

def to_utf8_binary
  encode(UTF8_ENCODING).force_encoding(BINARY_ENCODING)
rescue EncodingError
  data = dup.force_encoding(UTF8_ENCODING)
  raise unless data.valid_encoding?
  data.force_encoding(BINARY_ENCODING)
end