Class: Protobug::Field::StringField

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

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

#binary_decode, #binary_encode, #define_adder, #json_decode, #json_encode, #json_key_encode, #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.



361
362
363
364
365
# File 'lib/protobug/field.rb', line 361

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



359
# File 'lib/protobug/field.rb', line 359

def self.type = :string

Instance Method Details

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

Raises:



372
373
374
375
376
377
378
379
# File 'lib/protobug/field.rb', line 372

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



367
368
369
370
# File 'lib/protobug/field.rb', line 367

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

#defaultObject



395
396
397
398
399
# File 'lib/protobug/field.rb', line 395

def default
  return [] if repeated?

  +""
end

#json_decode_one(value, _ignore_unknown_fields, _registry) ⇒ Object

Raises:



381
382
383
384
385
386
387
388
389
# File 'lib/protobug/field.rb', line 381

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



391
392
393
# File 'lib/protobug/field.rb', line 391

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