shamblett / cbor

A CBOR implementation for Dart
MIT License
36 stars 15 forks source link

CborFloat #44

Closed alexandrubulaidev closed 1 year ago

alexandrubulaidev commented 1 year ago

Instead of automatically converting double to float, halffloat or double the library should let the user chose, for example CborHalfFloat, CborDouble or CborFloat.

shamblett commented 1 year ago

The reason that this has not been implemented thus far is that the CBOR spec(RFC's 8949 and 7049) have an expectation that the most efficient form of encoding should be used if possible, for floats for instance from the spec -

If a protocol allows for IEEE floats, then additional
   canonicalization rules might need to be added.  One example rule
   might be to have all floats start as a 64-bit float, then do a test
   conversion to a 32-bit float; if the result is the same numeric
   value, use the shorter value and repeat the process with a test
   conversion to a 16-bit float.  (This rule selects 16-bit float for
   positive and negative Infinity as well.)  Also, there are many
   representations for NaN.  If NaN is an allowed value, it must always
   be represented as 0xf97e00.

That said I don't thinkmits unreasonable to allow users to chose how floats are encoded if they wish to do so.I'll have a look at this and see what can be done.

shamblett commented 1 year ago

Ok you can now do this with floats -

 final encoded = cbor.encode(CborFloat(0.0)..halfPrecision());

Similar for float and double precision. If the value supplied cannot be represented in the specified precision an ArgumentError is thrown.

Package re released at version 5.1.0

shamblett commented 1 year ago

Forgot to add, if you dont specify a precision you get current behaviour i.e. best fit.