From 8c469f9aa45eaaf2bd8e5fc4a5767d48e03be307 Mon Sep 17 00:00:00 2001 From: Ishan Bhanuka Date: Wed, 17 Apr 2024 22:53:36 -0400 Subject: [PATCH] Refactor db --- spritefire/src/db.rs | 42 ++++++++++++++++------------------------- spritefire/src/emoji.rs | 3 ++- 2 files changed, 18 insertions(+), 27 deletions(-) diff --git a/spritefire/src/db.rs b/spritefire/src/db.rs index b4f385a..0738d4a 100644 --- a/spritefire/src/db.rs +++ b/spritefire/src/db.rs @@ -16,7 +16,7 @@ type Fxd = FixedU8; #[derive(Serialize, Deserialize, Debug)] pub struct EmojiDatabase { kdtree: KdTree, - symbols: Vec<(u64, String)>, + symbols: Vec, } impl EmojiDatabase { @@ -29,33 +29,20 @@ impl EmojiDatabase { } pub fn from_emojis(emojis: Vec) -> Self { - let (symbols, colors): (Vec<_>, Vec<_>) = emojis - .into_iter() - .map( - |Emoji { - symbol, - color, - density: transparent, - }| { - let [r, g, b] = color; - ( - (transparent, symbol), - [ - FixedU8::from_num(r), - FixedU8::from_num(g), - FixedU8::from_num(b), - ], - ) - }, - ) - .unzip(); - let mut kdtree = KdTree::new(); - colors.into_iter().enumerate().for_each(|(i, color)| { + emojis.iter().enumerate().for_each(|(i, emoji)| { + let color = [ + FixedU8::from_num(emoji.color[0]), + FixedU8::from_num(emoji.color[1]), + FixedU8::from_num(emoji.color[2]), + ]; kdtree.add(&color, i as u32); }); - Self { symbols, kdtree } + Self { + symbols: emojis, + kdtree, + } } pub fn lookup_closest_dense_emoji(&self, rgb: Rgb) -> &str { @@ -68,7 +55,10 @@ impl EmojiDatabase { let nearest = self.kdtree.nearest_n::(&point, 3); let (_, symbol) = nearest .iter() - .map(|item| &self.symbols[item.item as usize]) + .map(|item| { + let emoji = &self.symbols[item.item as usize]; + (emoji.density, &emoji.symbol) + }) .max() .unwrap(); symbol @@ -82,7 +72,7 @@ impl EmojiDatabase { ]; let index: usize = self.kdtree.nearest_one::(&point).item as usize; - &self.symbols[index].1 + &self.symbols[index].symbol } pub fn new_from_directory(dir_path: PathBuf) -> Self { diff --git a/spritefire/src/emoji.rs b/spritefire/src/emoji.rs index 056e25c..67a41b3 100644 --- a/spritefire/src/emoji.rs +++ b/spritefire/src/emoji.rs @@ -1,7 +1,8 @@ use image::{self, DynamicImage, GenericImageView}; +use serde::{Deserialize, Serialize}; /// Emoji symbol with the average color of its picture -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Emoji { /// Unicode symbol for the emoji pub symbol: String,