Uploaded image for project: 'Go Driver'
  1. Go Driver
  2. GODRIVER-2751

Make all BSON-to-Go numeric type conversions safe

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • 2.1.0
    • Affects Version/s: None
    • Component/s: BSON
    • None

      There are currently cases where the existing bson.RawValue As* conversion methods (i.e. methods that convert between numeric representations, not just unmarshal from BSON to Go values) will silently lose data. Additionally, there is currently no way to convert a bson.RawValue holding a BSON numeric value into Go float64 value.

      Safe conversion between int and float type values is available via bson.Unmarshal. The numeric conversion behavior of bson.Unmarshal matches json.Unmarshal. Note that JSON represents numbers as arbitrary precision unquoted strings, which always require parsing, but BSON numeric values use the same types as Go numeric values and can be directly converted without parsing. The only lossy case that is supported by both bson.Unmarshal and json.Unmarshal is conversion of integer values greater than 2^53 to float64, which retains the approximate magnitude but loses exact integer precision. Check out an example of numeric conversion on the Go Playground here.

      Definition of done:

      • Update AsInt64/AsInt64OK to match the behavior of bson.Unmarshal. That means panic/return ok=false on any lossy BSON "double" to Go int64 conversions. Unsafe-to-convert "double" values are:
        • Any value with a fractional part (truncates the fractional part)
        • Greater than math.MaxInt64 (returns math.MinInt64)
        • Less than math.MinInt64 (returns math.MinInt64)
        • NaN, +Inf, -Inf
      • Add AsFloat64 and AsFloat64OK functions that convert any BSON numeric value to a Go float64. Those functions should have the same conversion behavior as bson.Unmarshal.
      • Consider updating bson.Unmarshal and AsFloat64/AsFloat64OK to fail if there is a loss of precision when converting int64 values to float64 values. Lossy values are:
        • Greater than 2^53 (loses integer precision)
        • Less than -1 * 2^53 (loses integer precision)

            Assignee:
            Unassigned Unassigned
            Reporter:
            matt.dale@mongodb.com Matt Dale
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: