Skip to content

JSON deserialization of empty HashMap results corrupted object #5998

Closed
@alexbers

Description

@alexbers

This code(saving an emtpy map as json file and loading it):

extern mod std;

use core::path::Path;
use core::hashmap::HashMap;

use std::serialize::{Encodable, Decodable};


fn save_db(queues: &HashMap<~str,~str>) {
    match io::buffered_file_writer(&Path("db.json")) {
        Ok(wr) => {
            let enc = ~std::json::Encoder(wr);
            queues.encode(enc);
        }
        Err(e) => {
            println(e);
        }
    }
}

fn load_db() -> HashMap<~str,~str> {
    match io::file_reader(&Path("db.json")) {
        Ok(rd) => {
            match std::json::from_reader(rd) {
                Ok(json) => {
                    let dec = ~std::json::Decoder(json);
                    return Decodable::decode(dec);
                },
                Err(_) => {
                    println("Db file is bad, using empty db");
                    return HashMap::new();
                }
            }
        }
        Err(e) => {
            println(e);
            return HashMap::new();
        }
    }
}

fn main() {
    let mut map : HashMap<~str,~str> = HashMap::new();

    save_db(&map);
    let mut map = load_db();

    map.insert(~"key", ~"val");
}

Gives on insert operation:

rust: task failed at 'modulo zero', json.rs:1

I think it is because the internal structure of map is wrong after loading.

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