Class: Protobuf::Field::VarintField

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

Constant Summary collapse

INT32_MAX =

Constants

2**31 - 1
INT32_MIN =
-2**31
INT64_MAX =
2**63 - 1
INT64_MIN =
-2**63
UINT32_MAX =
2**32 - 1
UINT64_MAX =
2**64 - 1

Constants inherited from BaseField

BaseField::PACKED_TYPES

Instance Attribute Summary

Attributes inherited from BaseField

#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?, #getter, #initialize, #message?, #optional?, #packed?, #repeated?, #repeated_message?, #required?, #set, #setter, #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



22
23
24
# File 'lib/protobuf/field/varint_field.rb', line 22

def self.default
  0
end

.encode(value) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/protobuf/field/varint_field.rb', line 26

def self.encode(value)
  bytes = []
  until value < 128
    bytes << (0x80 | (value & 0x7f))
    value >>= 7
  end
  (bytes << value).pack('C*')
end

Instance Method Details

#acceptable?(val) ⇒ Boolean

Public Instance Methods

Returns:

  • (Boolean)


39
40
41
42
43
44
# File 'lib/protobuf/field/varint_field.rb', line 39

def acceptable?(val)
  int_val = coerce!(val)
  int_val >= self.class.min && int_val <= self.class.max
rescue
  false
end

#coerce!(val) ⇒ Object



46
47
48
49
# File 'lib/protobuf/field/varint_field.rb', line 46

def coerce!(val)
  return val.to_i if val.is_a?(Numeric)
  Integer(val, 10)
end

#decode(value) ⇒ Object



51
52
53
# File 'lib/protobuf/field/varint_field.rb', line 51

def decode(value)
  value
end

#encode(value) ⇒ Object



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

def encode(value)
  return [value].pack('C') if value < 128

  bytes = []
  until value == 0
    bytes << (0x80 | (value & 0x7f))
    value >>= 7
  end
  bytes[-1] &= 0x7f
  bytes.pack('C*')
end

#wire_typeObject



67
68
69
# File 'lib/protobuf/field/varint_field.rb', line 67

def wire_type
  ::Protobuf::WireType::VARINT
end