serialize from and to file

This commit is contained in:
2022-11-11 20:48:44 +01:00
parent cd97a70e0b
commit b7d993dfa5
2 changed files with 14 additions and 12 deletions
+1
View File
@@ -1,2 +1,3 @@
/target /target
debug.png debug.png
*.messagepack
+13 -12
View File
@@ -8,29 +8,30 @@ fn main() {
//Init all descriptors: //Init all descriptors:
let desc = Median; 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 count = fs::read_dir("img").unwrap().count();
let mut map: HashMap<String, u64> = HashMap::with_capacity(count); let map_file = fs::read("map.messagepack");
let mut map: HashMap<String, u64> = match map_file {
Ok(f) => rmp_serde::from_slice(&f).unwrap(),
Err(_e) => HashMap::with_capacity(count),
};
//Calculate phashes for all images //Calculate phashes for all images
for node in fs::read_dir("img").unwrap() { for node in fs::read_dir("img").unwrap() {
let file = node.expect("Error walking directory"); 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"); 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() { for (key, val) in map.iter() {
println!("{key}: {val}"); println!("{key}: {val}");
} }
//Test (de)serialize to vector with MessagePack: //Serialize hashmap with MessagePack:
let serialized: Vec<u8> = rmp_serde::to_vec(&map).unwrap(); let serialized: Vec<u8> = rmp_serde::to_vec(&map).unwrap();
fs::write("map.messagepack",&serialized).unwrap();
let x: HashMap<String, u64> = rmp_serde::from_slice(&serialized).unwrap();
for (key, val) in x.iter() {
println!("{key}: {val}");
}
} }