Sha256: 1ac6c0e404a43b10f473fbb3b1b0ef9c4329d93a8a0f6dcdc4f2ae8880260f59

Contents?: true

Size: 1.63 KB

Versions: 12

Compression:

Stored size: 1.63 KB

Contents

require 'protobuf/wire_type'

module Protobuf
  module Field
    class BytesField < BaseField

      ##
      # Constants
      #

      BYTES_ENCODING = Encoding::BINARY

      ##
      # Class Methods
      #

      def self.default
        ''
      end

      ##
      # Public Instance Methods
      #

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

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

      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

      def encode_to_stream(value, stream)
        value = value.encode if value.is_a?(::Protobuf::Message)
        byte_size = ::Protobuf::Field::VarintField.encode(value.bytesize)

        stream << tag_encoded << byte_size << value
      end

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

      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
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
protobuf-3.8.2 lib/protobuf/field/bytes_field.rb
protobuf-3.8.1 lib/protobuf/field/bytes_field.rb
protobuf-3.8.0 lib/protobuf/field/bytes_field.rb
protobuf-3.8.0.pre1 lib/protobuf/field/bytes_field.rb
protobuf-3.7.5 lib/protobuf/field/bytes_field.rb
protobuf-3.7.4 lib/protobuf/field/bytes_field.rb
protobuf-3.7.3 lib/protobuf/field/bytes_field.rb
protobuf-3.7.2 lib/protobuf/field/bytes_field.rb
protobuf-3.7.2.pre1 lib/protobuf/field/bytes_field.rb
protobuf-3.7.1 lib/protobuf/field/bytes_field.rb
protobuf-3.7.0 lib/protobuf/field/bytes_field.rb
protobuf-3.7.0.pre3 lib/protobuf/field/bytes_field.rb