Class: RustyJson::RustStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/rusty_json/rust_struct.rb

Constant Summary collapse

@@types =
{
  String => 'String',
  Fixnum => 'i64',
  Float => 'f64',
  Array => 'Vec',
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, root = false) ⇒ RustStruct

Returns a new instance of RustStruct.



12
13
14
15
16
17
18
# File 'lib/rusty_json/rust_struct.rb', line 12

def initialize(name, root = false)
  @root = root
  @printed = false
  @name = name
  @values = {}
  @structs = Set.new
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/rusty_json/rust_struct.rb', line 3

def name
  @name
end

#valuesObject (readonly)

Returns the value of attribute values.



3
4
5
# File 'lib/rusty_json/rust_struct.rb', line 3

def values
  @values
end

Instance Method Details

#==(other) ⇒ Object



55
56
57
# File 'lib/rusty_json/rust_struct.rb', line 55

def == other
  self.values == other.values
end

#add_value(name, type, subtype = nil) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rusty_json/rust_struct.rb', line 27

def add_value(name, type, subtype = nil)
  if type.class == RustyJson::RustStruct || subtype.class == RustyJson::RustStruct
    struct = if type.class == RustyJson::RustStruct
      t = type
      type = type.name
      t
    elsif subtype.class == RustyJson::RustStruct
      s = subtype
      subtype = subtype.name
      s
    end
    @structs << struct
    RustStruct.add_type(struct.name, struct.name)
    @values[name] = [type, subtype]
  else
    @values[name] = [type, subtype]
  end
end

#required_structsObject



46
47
48
49
50
51
52
53
# File 'lib/rusty_json/rust_struct.rb', line 46

def required_structs
  struct = ""
  # binding.pry
  @structs.to_a.each do |nested_struct|
    struct << nested_struct.to_s + "\n"
  end
  struct
end

#resetObject



20
21
22
23
24
25
# File 'lib/rusty_json/rust_struct.rb', line 20

def reset
  @printed = false
  @structs.each do |s|
    s.reset
  end
end

#to_sObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/rusty_json/rust_struct.rb', line 59

def to_s
  return "" if @printed
  @printed = true
  struct = required_structs
  # binding.pry
  struct << <<-RUST
struct #{@name} {
  RUST
  @values.each do |attr_name, type|
    if type[1] == nil
      struct += "  #{attr_name}: #{RustStruct.type_name(type[0])}"
    else
      struct += "  #{attr_name}: #{RustStruct.type_name(type[0])}<#{RustStruct.type_name(type[1])}>"
    end
    struct += ",\n"
  end
  struct << <<-RUST
}
  RUST
  if @root
    reset
  end
  struct
end