Skip to content

JSON encoder silently corrupts some 64-bit ints #18319

Closed
@kmcallister

Description

@kmcallister

_Because of JavaScript_™, the JSON number type can't represent all 64-bit numbers. This code

extern crate serialize;

use serialize::json;

fn main() {
    let n: u64 = 0x747865747a6f6d71;
    let j = json::encode(&n); 
    let m: u64 = json::decode(j.as_slice()).unwrap();
    assert_eq!(n, m);  
}

fails with

task '<main>' failed at 'assertion failed: `(left == right) && (right == left)` (left: `8392569456549653873`, right: `8392569456549654464`)', foo.rs:9

This is pretty surprising, especially when the u64 field is buried within a struct that's deriving Encodable. If the encoder is going to implement emit_u64 and emit_i64 at all, it should do something that doesn't silently corrupt data. There's no universal standard for 64-bit numbers in JSON but a decimal ASCII string seems like a reasonable default. emit_uint and emit_int should also switch to that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions