Class: Protobug::Field::StringField

Inherits:
BytesField show all
Defined in:
lib/protobug/field.rb

Constant Summary

Constants inherited from Protobug::Field

PACKABLE_WIRE_TYPES

Instance Attribute Summary

Attributes inherited from Protobug::Field

#adder, #cardinality, #clearer, #haser, #ivar, #json_name, #name, #number, #oneof, #setter

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BytesField

#wire_type

Methods inherited from Protobug::Field

#adder_method_definition, #binary_decode, #binary_encode, #json_decode, #json_encode, #json_key_encode, #method_definitions, #optional?, #packed?, #pretty_print, #proto3_optional?, #repeated?, #to_text, #validate!

Constructor Details

#initialize(number, name, cardinality:, json_name: name, oneof: nil, proto3_optional: cardinality == :optional) ⇒ StringField

Returns a new instance of StringField.



416
417
418
419
420
# File 'lib/protobug/field.rb', line 416

def initialize(number, name, cardinality:, json_name: name, oneof: nil,
               proto3_optional: cardinality == :optional)
  super(number, name, json_name: json_name, cardinality: cardinality, oneof: oneof,
                      proto3_optional: proto3_optional)
end

Class Method Details

.typeObject



412
413
414
# File 'lib/protobug/field.rb', line 412

def self.type
  :string
end

Instance Method Details

#binary_decode_one(io, _message, _registry, wire_type) ⇒ Object

Raises:



427
428
429
430
431
432
433
434
# File 'lib/protobug/field.rb', line 427

def binary_decode_one(io, _message, _registry, wire_type)
  value = super

  value.force_encoding("utf-8") if value.encoding != Encoding::UTF_8
  raise DecodeError, "invalid utf-8 for string" unless value.valid_encoding?

  value
end

#binary_encode_one(value, outbuf) ⇒ Object



422
423
424
425
# File 'lib/protobug/field.rb', line 422

def binary_encode_one(value, outbuf)
  value = value.encode("utf-8") if value.encoding != Encoding::UTF_8
  super
end

#defaultObject



450
451
452
453
454
# File 'lib/protobug/field.rb', line 450

def default
  return [] if repeated?

  +""
end

#json_decode_one(value, _ignore_unknown_fields, _registry) ⇒ Object

Raises:



436
437
438
439
440
441
442
443
444
# File 'lib/protobug/field.rb', line 436

def json_decode_one(value, _ignore_unknown_fields, _registry)
  return UNSET if value.nil?
  raise DecodeError, "expected string, got #{value.inspect}" unless value.is_a?(String)

  value.force_encoding("utf-8") if value.encoding != Encoding::UTF_8
  raise DecodeError, "invalid utf-8 for string" unless value.valid_encoding?

  value
end

#json_encode_one(value, print_unknown_fields:) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



446
447
448
# File 'lib/protobug/field.rb', line 446

def json_encode_one(value, print_unknown_fields:) # rubocop:disable Lint/UnusedMethodArgument
  value.encode("utf-8")
end