Class: Nl::DataTypes::Struct
Instance Method Summary collapse
- #coerce(value, context: nil) ⇒ Object
- #decode(decoder, context: nil, nlattr_type_flags: 0) ⇒ Object
- #encode(encoder, value, context: nil) ⇒ Object
-
#initialize(type, check: nil, consume_remaining: false) ⇒ Struct
constructor
A new instance of Struct.
Methods inherited from Base
Constructor Details
#initialize(type, check: nil, consume_remaining: false) ⇒ Struct
Returns a new instance of Struct.
153 154 155 156 157 |
# File 'nl/lib/nl/datatypes.rb', line 153 def initialize(type, check: nil, consume_remaining: false) super(check:) @type = type @consume_remaining = consume_remaining end |
Instance Method Details
#coerce(value, context: nil) ⇒ Object
159 160 161 162 163 164 165 166 |
# File 'nl/lib/nl/datatypes.rb', line 159 def coerce(value, context: nil) return value unless value.is_a?(Hash) unknown = value.keys - @type::MEMBERS.keys raise ArgumentError, "unknown struct members: #{unknown.join(', ')}" unless unknown.empty? @type.new(*@type::MEMBERS.map { |name, datatype| datatype.coerce(value[name], context:) }) end |
#decode(decoder, context: nil, nlattr_type_flags: 0) ⇒ Object
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'nl/lib/nl/datatypes.rb', line 182 def decode(decoder, context: nil, nlattr_type_flags: 0) unless @check value = @type.decode(decoder) decoder.skip if @consume_remaining return value end payload = checked(decoder.get_string) nested = Decoder.new(IO::Buffer.for(payload)) nested.limit(payload.bytesize) do value = @type.decode(it) it.skip if @consume_remaining value end end |
#encode(encoder, value, context: nil) ⇒ Object
168 169 170 171 172 173 174 175 176 177 178 179 180 |
# File 'nl/lib/nl/datatypes.rb', line 168 def encode(encoder, value, context: nil) unless value.is_a?(@type) raise TypeError, "value must be an instance of #{@type}" end if @check temporary = Encoder.new value.encode(temporary) encoder.put_string(checked(temporary.buffer.get_string)) else value.encode(encoder) end end |