class BareTypes::Struct

Public Class Methods

new(symbolToType) click to toggle source
# File lib/types.rb, line 456
def initialize(symbolToType)
  # Mapping from symbols to Bare types (or possibly symbols before finalizing)
  symbolToType.keys.each do |k|
    raise BareException.new("Struct keys must be symbols") unless k.is_a?(Symbol)
    if (!symbolToType[k].class.ancestors.include?(BaseType) && !symbolToType[k].is_a?(Symbol))
      raise BareException.new("Struct values must be a BareTypes::TYPE or a symbol with the same
            name as a user defined type\nInstead got: #{symbolToType[k].inspect}")
    end
    raise VoidUsedOutsideTaggedSet.new("Void types may only be used as members of the set of types in a tagged union. Void type used as struct key") if symbolToType.class == BareTypes::Void
  end
  raise("Struct must have at least one field") if symbolToType.keys.size == 0
  @mapping = symbolToType
end

Public Instance Methods

==(otherType) click to toggle source
# File lib/types.rb, line 432
def ==(otherType)
  return false unless otherType.class == BareTypes::Struct
  @mapping.each do |k, v|
    return false unless otherType.mapping[k] == v
  end
  return true
end
[](key) click to toggle source
# File lib/types.rb, line 428
def [](key)
  return @mapping[key]
end
decode(msg) click to toggle source
# File lib/types.rb, line 479
def decode(msg)
  hash = Hash.new
  rest = msg
  @mapping.keys.each do |symbol|
    value, rest = @mapping[symbol].decode(rest)
    hash[symbol] = value
  end
  return hash, rest
end
encode(msg) click to toggle source
# File lib/types.rb, line 470
def encode(msg)
  bytes = "".b
  @mapping.keys.each do |symbol|
    raise SchemaMismatch.new("All struct fields must be specified, missing: #{symbol.inspect}") unless msg.keys.include?(symbol)
    bytes << @mapping[symbol].encode(msg[symbol])
  end
  return bytes
end
finalize_references(schema) click to toggle source
# File lib/types.rb, line 440
def finalize_references(schema)
  return if @finalized
  @finalized = true
  @mapping.each do |key, val|
    if val.is_a?(Symbol)
      @mapping[key] = schema[val]
    else
      val.finalize_references(schema)
    end
  end
end
mapping() click to toggle source
# File lib/types.rb, line 452
def mapping
  @mapping
end