ciborium icon indicating copy to clipboard operation
ciborium copied to clipboard

Support BigFloat

Open fredfortier opened this issue 4 years ago • 2 comments

I just learned about this project after I asked the same question on serde_cbor. RFC 8949 section 3.4.4 specifies BigFloat. What do you think of implementing this using rust-decimal? If not, since this crate does support BigNum via i128, can I use serde(with = "") with this crate to scale/unstable them myself?

fredfortier avatar Jul 24 '21 16:07 fredfortier

I would accept a patch to implement this.

npmccallum avatar Jul 25 '21 15:07 npmccallum

I don't have the time to provide a patch right now, but this is what I'm using as a quick and dirty workaround:

           .and_then(|v: ciborium::value::Value| {
               // Workaround for https://github.com/enarx/ciborium/issues/21
               use ciborium::value::Value::{Tag, Array, Integer};
               match v {
                   Tag(5, b) => {
                       match b.as_ref() {
                           Array(v) => match v.as_slice() {
                               [Integer(v1), Integer(v2)] => {
                                   let exponent = i32::try_from(*v1)
                                       .map_err(|_| "Exponent exceeds i32 range")?;
                                   let mantissa = i32::try_from(*v2)
                                       .map_err(|_| "Mantissa exceeds i32 range")?
                                        as f32;
                                   Ok((2.0f32).powi(exponent) * mantissa)
                               },
                               _ => Err("Bigfloat tags array of wrong length"),
                           }
                           _ => Err("Bigfloat should tag array"),
                       }
                   }
                   _ => Err("Parsed but not a bigfloat"),
               }
           })

It's not pretty enough to even serve as a base for a patch (for this should be parsed right away rather than resulting in an allocated Value), but if someone finding this merely needs Something That Works Quickly, here you go. (Snippet published under terms of CC0 or whatever ciborium's license currently is, at your choice, in case the latter is not obvious from being code sent to a licensed project's issue).

[edit: fixed how I had swapped exponent and mantissa]

chrysn avatar Dec 10 '22 18:12 chrysn