Compute the number of object properties to serialize.

dev
Karchnu 2020-11-10 20:14:50 +01:00
parent 3ab21c9616
commit 5f838d36cc
1 changed files with 35 additions and 16 deletions

View File

@ -136,6 +136,7 @@ module CBOR
end end
private def self.new_from_cbor_decoder(decoder : ::CBOR::Decoder) private def self.new_from_cbor_decoder(decoder : ::CBOR::Decoder)
# puts "self.new_from_cbor_decoder"
instance = allocate instance = allocate
instance.initialize(__decoder_for_cbor_serializable: decoder) instance.initialize(__decoder_for_cbor_serializable: decoder)
GC.add_finalizer(instance) if instance.responds_to?(:finalize) GC.add_finalizer(instance) if instance.responds_to?(:finalize)
@ -268,9 +269,27 @@ module CBOR
{% end %} {% end %}
{% end %} {% end %}
cbor.object do # Compute the size of the final list of properties to serialize.
{% for name, value in properties %} # This allows a more compact encoding, and a faster decoding.
nb_properties_to_serialize = 0
{% for name, value in properties %}
_{{name}} = @{{name}} _{{name}} = @{{name}}
{% unless value[:emit_null] %}
unless _{{name}}.nil?
nb_properties_to_serialize += 1
end
{% else %}
nb_properties_to_serialize += 1
{% end %} # macro unless value[:emit_null]
{% end %} # macro for properties
{% if properties.size > 0 %}
cbor.write_object_start nb_properties_to_serialize
{% for name, value in properties %}
_{{name}} = @{{name}}
{% unless value[:emit_null] %} {% unless value[:emit_null] %}
unless _{{name}}.nil? unless _{{name}}.nil?
@ -279,23 +298,23 @@ module CBOR
# Write the key of the map # Write the key of the map
cbor.write({{value[:key]}}) cbor.write({{value[:key]}})
{% if value[:converter] %} {% if value[:converter] %}
if _{{name}} if _{{name}}
{{ value[:converter] }}.to_cbor(_{{name}}, cbor) {{ value[:converter] }}.to_cbor(_{{name}}, cbor)
else else
cbor.write(nil, use_undefined: value[:nil_as_undefined]) cbor.write(nil, use_undefined: value[:nil_as_undefined])
end end
{% else %} {% else %} # macro if value[:converter]
_{{name}}.to_cbor(cbor) _{{name}}.to_cbor(cbor)
{% end %} {% end %} # macro if value[:converter]
{% unless value[:emit_null] %} {% unless value[:emit_null] %}
end end # unless _{{name}}.nil?
{% end %} {% end %} # macro unless value[:emit_null]
{% end %} {% end %} # macro for properties
on_to_cbor(cbor) on_to_cbor(cbor)
end {% end %} # macro if properties.size > 0
{% end %} {% end %} # begin
end end
module Unmapped module Unmapped