laurencelundblade / QCBOR

Comprehensive, powerful, commercial-quality CBOR encoder/ decoder that is still suited for small devices.
Other
187 stars 47 forks source link

Preferred Serialization support #130

Closed cyberphone closed 8 months ago

cyberphone commented 2 years ago

Although QCBOR does not do map sorting there is actually no problem generating preferred serialization:

Just for fun I patched example.c like the following:

    QCBOREncode_OpenMap(&EncodeCtx);
    QCBOREncode_AddBoolToMap(&EncodeCtx, "Turbo", pEngine->bTurboCharged);
    QCBOREncode_OpenArrayInMap(&EncodeCtx, "Cylinders");
#ifndef USEFULBUF_DISABLE_ALL_FLOAT
    for(int64_t i = 0 ; i < pEngine->uNumCylinders; i++) {
        QCBOREncode_AddDouble(&EncodeCtx,
                              pEngine->cylinders[i].dMeasuredCompression);
    }
#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
    QCBOREncode_CloseArray(&EncodeCtx);
    QCBOREncode_AddInt64ToMap(&EncodeCtx, "Horsepower", pEngine->uHorsePower);
    QCBOREncode_AddInt64ToMap(&EncodeCtx, "Displacement", pEngine->uDisplacement);
    QCBOREncode_AddTextToMap(&EncodeCtx, "Manufacturer", pEngine->Manufacturer);
    QCBOREncode_AddInt64ToMap(&EncodeCtx, "NumCylinders", pEngine->uNumCylinders);
#ifndef USEFULBUF_DISABLE_ALL_FLOAT
    QCBOREncode_AddDoubleToMap(&EncodeCtx, "DesignedCompression", pEngine->dDesignedCompresion);
#endif /* USEFULBUF_DISABLE_ALL_FLOAT */
    QCBOREncode_CloseMap(&EncodeCtx);

This returned

a765547572626ff46943796c696e6465727386f94880fb4022666666666666fb4021cccccccccccdfb4021cccccccccccdfb4022333333333333f948806a486f727365706f77657218d26c446973706c6163656d656e74190ce06c4d616e75666163747572657267506f72736368656c4e756d43796c696e64657273067344657369676e6564436f6d7072657373696f6efb4022333333333333

which according to my on-line parser https://test.webpki.org/csf-lab/convert is correct (it doesn't accept anything but CBOR using preferred serialization).

When I changed one of the cylinder arguments to 5.9604644775390625e-8 it failed but that was expected since QCBOR does not yet offer full support for preferred serialization of floating point values.

laurencelundblade commented 8 months ago

There's now a preferred serialization mode. See #193. This is for QCBOR 2.x and thus in the dev branch.