Class: Canoser::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/canoser/struct.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Struct

Returns a new instance of Struct.



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/canoser/struct.rb', line 24

def initialize(hash={})
	hash.each do |k,v|
		idx =  self.class.class_variable_get("@@names").find_index{|x| x==k}
		raise "#{k} is not a field of #{self}" unless idx
		type = self.class.class_variable_get("@@types")[idx]
     if type.class == ArrayT
       len = type.fixed_len
       raise "fix-length array #{k}: #{len} != #{v.size}" if len && v.size != len
     end
     instance_variable_set("@#{k}", v)
	end
end

Class Method Details

.decode(cursor) ⇒ Object



68
69
70
# File 'lib/canoser/struct.rb', line 68

def self.decode(cursor)
  self.new({}).decode(cursor)
end

.define_field(name, type, arr_len = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/canoser/struct.rb', line 5

def self.define_field(name, type, arr_len=nil)
   name = ":"+name.to_sym.to_s
   if type.class == Array
     type =  ArrayT.new(type[0], arr_len)
   elsif type.class == Hash
     type = HashT.new(type.keys[0], type.values[0])
   else
     raise "type #{type} doen't support arr_len param" if arr_len
   end
   str = %Q{
     @@names ||= []
     @@names << #{name}
     @@types ||= []
     @@types << type
     attr_accessor(#{name})
   }
   class_eval str
end

.deserialize(bytes) ⇒ Object

Raises:



61
62
63
64
65
66
# File 'lib/canoser/struct.rb', line 61

def self.deserialize(bytes)
   cursor = Canoser::Cursor.new(bytes)
   ret = decode(cursor)
   raise ParseError.new("bytes not all consumed.") unless cursor.finished?
   ret
end

.encode(value) ⇒ Object



47
48
49
# File 'lib/canoser/struct.rb', line 47

def self.encode(value)
  value.serialize
end

Instance Method Details

#==(other) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/canoser/struct.rb', line 37

def ==(other)
  return true if self.equal?(other)
  self.class.class_variable_get("@@names").each_with_index do |name, idx|
    unless instance_variable_get("@#{name}") == other.instance_variable_get("@#{name}")
      return false
    end
  end
  true
end

#decode(cursor) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/canoser/struct.rb', line 72

def decode(cursor)
  self.class.class_variable_get("@@names").each_with_index do |name, idx|
    type = self.class.class_variable_get("@@types")[idx]
    instance_variable_set("@#{name}", type.decode(cursor))
  end
  self
end

#serializeObject



51
52
53
54
55
56
57
58
59
# File 'lib/canoser/struct.rb', line 51

def serialize
   output = ""
	self.class.class_variable_get("@@names").each_with_index do |name, idx|
		type = self.class.class_variable_get("@@types")[idx]
     value = instance_variable_get("@#{name}")
     output << type.encode(value)
	end
   output
end