Subject: Re: [Cbor] CBOR tag proposal for enumerated alternatives (tagged unions)

From: Emile Cormier <[email-masked]>
Date: Wed, 7 Apr 2021 18:37:19 -0300

On Wed, Mar 31, 2021 at 9:38 AM Carsten Bormann <[email-masked]> wrote:

> I’m not sure we discussed this one yet in detail:
>
>
> https://docs.google.com/document/d/16aiDEBhJj3kipj_7PVppEhxAr5E6QhQreN61eCxvBjU/edit#
>
> This is a (cbor-tags) registration request, so the WG does not have to
> have an opinion, but the designated expert would be interested in it
> nonetheless.
> (I’m personally pretty convinced of the use case; this is more of an issue
> of keeping tabs on available tag numbers and looking out for related use
> cases.)
>

As I had mentioned in the interim meeting, a related use case is
optional<T> (aka Nullable<T>). The meeting host (Christian?) was
questioning whether separate tags would be more appropriate to represent
the optional<T> semantic.

It would indeed be possible for the enumerated alternatives tags to be used
for representing an optional<T>. For instance, alternative 0 would
represent the "no value" state, followed by a null data item (0xF6),
whereas alternative 1 would represent the "has value" state followed by the
actual value. However, this is just an arbitrary convention and the
enumerated alternatives tags used in this fashion don't explicitly express
the "optional" semantic (it has to be assumed by the application). I
therefore agree that separate tags would be preferable for the optional<T>
use case.

I communicated with one of the co-authors of the enumerated alternatives
proposal about the possibility of including extra tags for the optional<T>
use case. They declined, not wanting to expand the scope of their proposal,
which is perfectly understandable.

My idea of tags for representing optional<T> might be overkill. One can
simply encode an optional value as either null (0xF6) or the actual value.
A contrived example where this would not work is encoding
optional<null_type> (i.e. "optional null").

Anyway, the idea of tags for optional values is out there for the
designated expert to consider. I cannot say if it's an idea actually worth
pursuing. I don't currently need them for encoding/decoding
std::optional<T> in my C++ work (I just check for null when deserializing
an optional value). However, I could definitely make use of the enumerated
alternatives tags for encoding/decoding std::variant<T0, T1, T2...>,
especially when the alternative types are ambiguous once converted to CBOR.

Cheers,
Emile Cormier