Class: PacketGen::Types::Int Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/packetgen/types/int.rb

Overview

This class is abstract.

Base integer class to handle binary integers

Author:

  • Sylvain Daubert

Direct Known Subclasses

Enum, Int16, Int24, Int32, Int64, Int8, SInt8

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = nil, endian = nil, width = nil, default = 0) ⇒ Int

Returns a new instance of Int.

Parameters:

  • value (Integer, nil) (defaults to: nil)
  • endian (:little, :big, nil) (defaults to: nil)
  • width (Integer, nil) (defaults to: nil)
  • default (Integer) (defaults to: 0)


32
33
34
35
36
37
# File 'lib/packetgen/types/int.rb', line 32

def initialize(value=nil, endian=nil, width=nil, default=0)
  @value = value
  @endian = endian
  @width = width
  @default = default
end

Instance Attribute Details

#defaultInteger

Integer default value

Returns:

  • (Integer)


26
27
28
# File 'lib/packetgen/types/int.rb', line 26

def default
  @default
end

#endian:little, :big

Integer endianness

Returns:

  • (:little, :big)


20
21
22
# File 'lib/packetgen/types/int.rb', line 20

def endian
  @endian
end

#valueInteger

Integer value

Returns:

  • (Integer)


17
18
19
# File 'lib/packetgen/types/int.rb', line 17

def value
  @value
end

#widthInteger

Integer size, in bytes

Returns:

  • (Integer)


23
24
25
# File 'lib/packetgen/types/int.rb', line 23

def width
  @width
end

Instance Method Details

#read(value) ⇒ self

This method is abstract.

Read an Int from a binary string or an integer

Parameters:

Returns:

  • (self)


43
44
45
46
47
48
49
50
# File 'lib/packetgen/types/int.rb', line 43

def read(value)
  @value = if value.is_a?(Integer)
             value.to_i
           else
             value.to_s.unpack(@packstr[@endian]).first
           end
  self
end

#szInteger

Give size in bytes of self

Returns:

  • (Integer)


78
79
80
# File 'lib/packetgen/types/int.rb', line 78

def sz
  to_s.size
end

#to_fFloat

Convert Int to Float

Returns:

  • (Float)


72
73
74
# File 'lib/packetgen/types/int.rb', line 72

def to_f
  to_i.to_f
end

#to_iInteger Also known as: to_human

Convert Int to Integer

Returns:

  • (Integer)


65
66
67
# File 'lib/packetgen/types/int.rb', line 65

def to_i
  @value || @default
end

#to_s::String

This method is abstract.

Returns:

  • (::String)

Raises:

  • (StandardError)

    This is an abstrat method and must be redefined



55
56
57
58
59
60
61
# File 'lib/packetgen/types/int.rb', line 55

def to_s
  unless defined? @packstr
    raise StandardError, 'PacketGen::Types::Int#to_s is an abstract method'
  end

  [to_i].pack(@packstr[@endian])
end