Class: Codify::Rust::Struct

Inherits:
Definition show all
Defined in:
lib/codify/rust/struct.rb

Instance Attribute Summary collapse

Attributes inherited from Definition

#cfg_derives, #comment, #derives, #name

Instance Method Summary collapse

Methods inherited from Definition

#comment?, #primitive?, #to_rust_code, #to_s

Methods included from Type

#definition?, #each_subtype, #primitive?, #to_rust

Constructor Details

#initialize(name, fields: nil, **kwargs, &block) ⇒ Struct

Returns a new instance of Struct.

Parameters:

  • name (String, #to_s)
  • fields (Array<StructField>, #to_a) (defaults to: nil)
  • derives (Array<Symbol, #to_sym>, #to_a)
  • comment (String, #to_s)
  • block (Proc)


14
15
16
17
18
# File 'lib/codify/rust/struct.rb', line 14

def initialize(name, fields: nil, **kwargs, &block)
  super(name, **kwargs)
  @fields = (fields || []).to_a.dup
  block.call(self) if block_given?
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



6
7
8
# File 'lib/codify/rust/struct.rb', line 6

def fields
  @fields
end

Instance Method Details

#defaultible?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/codify/rust/struct.rb', line 22

def defaultible?
  @fields.all?(&:defaultible?)
end

#typesArray<Type>

Returns:



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

def types
  @fields.map(&:type).uniq.to_a
end

#write(out) ⇒ void

This method returns an undefined value.

Parameters:

  • out (IO)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/codify/rust/struct.rb', line 35

def write(out)
  super(out)
  if self.fields.empty?
    out.puts "pub struct #{@name};"
  else
    out.puts "pub struct #{@name} {"
    @fields.each_with_index do |field, i|
      out.puts if i > 0
      out.puts wrap_text(field.comment, 80-8).map { |s| s.prepend("    /// ") }.join("\n") if field.comment?
      out.puts "    #[cfg_attr(feature = \"serde\", serde(rename = \"#{k.id}\"))]" if false
      field.write(out)
    end
    out.puts "}"
  end
end