Class: FFI::Generator::Struct

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

Direct Known Subclasses

Union

Constant Summary

Constants inherited from Type

Type::ArrayRE, Type::ArraySizeRE

Instance Attribute Summary

Attributes inherited from Type

#full_decl

Attributes inherited from Node

#symname

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#get_attr

Constructor Details

#initialize(params = { }) ⇒ Struct

Returns a new instance of Struct.



31
32
33
34
# File 'lib/generator/struct.rb', line 31

def initialize(params = { })
  super
  @name = self.class.camelcase(@symname)
end

Class Method Details

.callback_accessors(field_name, indent = 0) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/generator/struct.rb', line 16

def self.callback_accessors(field_name, indent = 0)
  result = <<-code
def #{field_name}=(cb)
  @#{field_name} = cb
  self[:#{field_name}] = @#{field_name}
end
def #{field_name}
  @#{field_name}
end
code
result.split("\n").collect { |line| ' ' * indent + line }.join("\n") << "\n"
end

.camelcase(name) ⇒ Object



28
29
30
# File 'lib/generator/struct.rb', line 28

def self.camelcase(name)
  name.gsub(/^_?\w|\_\w/) { |c| c.upcase }.delete('_')
end

.string_accessors(field_name, indent = 0) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/generator/struct.rb', line 4

def self.string_accessors(field_name, indent = 0)
  result = <<-code
def #{field_name}=(str)
  @#{field_name} = FFI::MemoryPointer.from_string(str)
  self[:#{field_name}] = @#{field_name}
end
def #{field_name}
  @#{field_name}.get_string(0)
end
code
result.split("\n").map { |line| ' ' * indent + line }.join("\n") << "\n"
end

Instance Method Details

#to_sObject



35
36
37
38
39
40
# File 'lib/generator/struct.rb', line 35

def to_s
  fields_str = fields.inject("") do |str, f|
    str << @indent_str + ' ' * 9 << f.join(', ') << ",\n"
  end
  code = klass_string + @indent_str + "  layout(\n" + fields_str.chomp.chomp(',') + "\n" + @indent_str + "  )\n" + accessors + @indent_str + "end\n"
end