Class: Protobuf::Field::BytesField

Inherits:
BaseField
  • Object
show all
Defined in:
lib/protobuf/field/bytes_field.rb

Direct Known Subclasses

StringField

Constant Summary collapse

BYTES_ENCODING =

Constants

Encoding::BINARY

Constants inherited from BaseField

Protobuf::Field::BaseField::PACKED_TYPES

Instance Attribute Summary

Attributes inherited from BaseField

#fully_qualified_name, #message_class, #name, #options, #rule, #tag, #type_class

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseField

#default, #default_value, #deprecated?, #enum?, #extension?, #fully_qualified_name_only!, #initialize, #message?, #optional?, #packed?, #repeated?, #repeated_message?, #required?, #set, #tag_encoded, #to_s

Methods included from Logging

initialize_logger, #log_exception, #log_signature, #logger, #sign_message

Constructor Details

This class inherits a constructor from Protobuf::Field::BaseField

Class Method Details

.defaultObject

Class Methods



17
18
19
# File 'lib/protobuf/field/bytes_field.rb', line 17

def self.default
  ''
end

Instance Method Details

#acceptable?(val) ⇒ Boolean

Public Instance Methods

Returns:

  • (Boolean)


25
26
27
# File 'lib/protobuf/field/bytes_field.rb', line 25

def acceptable?(val)
  val.is_a?(String) || val.nil? || val.is_a?(Symbol) || val.is_a?(::Protobuf::Message)
end

#coerce!(value) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/protobuf/field/bytes_field.rb', line 53

def coerce!(value)
  case value
  when String, Symbol
    value.to_s
  when NilClass
    nil
  when ::Protobuf::Message
    value.dup
  else
    fail TypeError, "Unacceptable value #{value} for field #{name} of type #{type_class}"
  end
end

#decode(bytes) ⇒ Object



29
30
31
32
33
# File 'lib/protobuf/field/bytes_field.rb', line 29

def decode(bytes)
  bytes_to_decode = bytes.dup
  bytes_to_decode.force_encoding(::Protobuf::Field::BytesField::BYTES_ENCODING)
  bytes_to_decode
end

#encode(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/protobuf/field/bytes_field.rb', line 35

def encode(value)
  value_to_encode =
    if value.is_a?(::Protobuf::Message)
      value.encode
    else
      value.dup
    end

  value_to_encode.force_encoding(::Protobuf::Field::BytesField::BYTES_ENCODING)
  string_size = ::Protobuf::Field::VarintField.encode(value_to_encode.size)

  "#{string_size}#{value_to_encode}"
end

#wire_typeObject



49
50
51
# File 'lib/protobuf/field/bytes_field.rb', line 49

def wire_type
  ::Protobuf::WireType::LENGTH_DELIMITED
end