From b7d993dfa54ab69e8420a78ab449a2f88c12ebfe Mon Sep 17 00:00:00 2001 From: Mark Hoekveen Date: Fri, 11 Nov 2022 20:48:44 +0100 Subject: [PATCH] serialize from and to file --- .gitignore | 1 + src/main.rs | 25 +++++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 796499b..5261f60 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target debug.png +*.messagepack diff --git a/src/main.rs b/src/main.rs index 1cb7c53..5bd9dc0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,29 +8,30 @@ fn main() { //Init all descriptors: let desc = Median; - //Pre-allocate hashmap to right size: + //Initialize hashmap, empty or from cached file: let count = fs::read_dir("img").unwrap().count(); - let mut map: HashMap = HashMap::with_capacity(count); + let map_file = fs::read("map.messagepack"); + let mut map: HashMap = match map_file { + Ok(f) => rmp_serde::from_slice(&f).unwrap(), + Err(_e) => HashMap::with_capacity(count), + }; //Calculate phashes for all images for node in fs::read_dir("img").unwrap() { let file = node.expect("Error walking directory"); - let img = image::open(file.path()).expect("Unable to open file"); - let phash = desc.describe(img); let name = file.file_name().into_string().expect("Issue with filename"); - map.insert(name, phash); + if !map.contains_key(&name) { + let img = image::open(file.path()).expect("Unable to open file"); + let phash = desc.describe(img); + map.insert(name, phash); + } } for (key, val) in map.iter() { println!("{key}: {val}"); } - //Test (de)serialize to vector with MessagePack: + //Serialize hashmap with MessagePack: let serialized: Vec = rmp_serde::to_vec(&map).unwrap(); - - let x: HashMap = rmp_serde::from_slice(&serialized).unwrap(); - - for (key, val) in x.iter() { - println!("{key}: {val}"); - } + fs::write("map.messagepack",&serialized).unwrap(); }