Skip to content

Instantly share code, notes, and snippets.

@DrJackilD
Created March 27, 2020 23:59
Show Gist options
  • Save DrJackilD/ad3e4e536190d9e73efde64ede354d1a to your computer and use it in GitHub Desktop.
Save DrJackilD/ad3e4e536190d9e73efde64ede354d1a to your computer and use it in GitHub Desktop.
use bson;
use bson::{decode_document, encode_document};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
#[derive(Serialize, Deserialize, Debug)]
struct Move {
x: i32,
y: i32,
}
fn write_to_file(fname: &str) {
let f = File::create(fname).unwrap();
let mut writer = BufWriter::new(f);
for i in 0..1000 {
let m = Move { x: i, y: i };
let m_bson = bson::to_bson(&m).unwrap();
let doc = m_bson.as_document().unwrap();
let mut serialized: Vec<u8> = Vec::new();
encode_document(&mut serialized, doc).unwrap();
writer.write(&serialized[..]).unwrap();
}
}
fn read_from_file(fname: &str) {
let mut f = File::open(fname).unwrap();
let mut values = String::new();
f.read_to_string(&mut values).unwrap();
let docs = bson::to_bson(&values);
println!("{:?}", docs);
}
fn main() {
let fname = "moves";
write_to_file(fname);
read_from_file(fname);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment