How to calculate data ops when using a variant in CloudEvent?

Hi,
Is there a way to get the size of a variant so I can know how many data ops this will consume?

In the following function I am printing the size of the json I' embedding, to give me an idea.
I believe json to cbor is ~ 70% to 60% less, so 1000 bytes in json migth end up being 700 in cbor.

Is my math correct? Is there a better way?
Thanks!

void publishFx()
{
    char buf[MAX_EVENT_DATA_SIZE];

    memset(publishStats, 0, MAX_EVENT_DATA_SIZE);
    JSONBufferWriter writer(publishStats, MAX_EVENT_DATA_SIZE);
    
    writer.beginObject();

    getJson(buf, sizeof(buf));

    writer.name("r").value(buf);

    writer.endObject();

    particle::Variant v = particle::Variant::fromJSON(publishStats);

    // is there a way to get the size of the variant so I can know how many data ops this will consume?
    String jsonStr = v.toJSON();
    Log.info("Variant JSON size: %d bytes", jsonStr.length());

    PublishQueueExt::instance().publish(EVENT_NAME_STATS, v, ContentType::BINARY);
}

You can create a CloudEvent object from a Variant. It's listed as a EventData in the docs but a EventData is just a Variant so you can pass a Variant to the constructor.

Then the size() method of CloudEvent will return the CBOR size.

The ConvertToCBOR tool also will allow you to paste JSON data into the tool and show how many bytes it will use in CBOR.

To calculate the number of data operations, divide the number of payload bytes by 1024 and roumd up.

1 Like