Просмотр исходного кода

[User] Migrate User::accounts from Vec to HashSet

Slava Barinov 2 лет назад
Родитель
Сommit
eeafd3a101
5 измененных файлов с 19 добавлено и 20 удалено
  1. 2 1
      src/categories.rs
  2. 4 4
      src/convert.rs
  3. 5 3
      src/main.rs
  4. 2 7
      src/telegram.rs
  5. 6 5
      src/user.rs

+ 2 - 1
src/categories.rs

@@ -4,6 +4,7 @@ use libc::isatty;
 use radix_trie::Trie;
 use serde::{Deserialize, Serialize};
 use std::cmp::Ordering;
+use std::collections::HashSet;
 
 /// Category statistics for single item
 #[derive(Serialize, Deserialize, Debug)]
@@ -75,7 +76,7 @@ pub fn get_top_category<'a>(item: &str, storage: &'a CatStats) -> Option<&'a str
 }
 
 /// Choose proper category or ask user
-pub fn get_category(item: &str, storage: &mut CatStats, accounts: &[String]) -> String {
+pub fn get_category(item: &str, storage: &mut CatStats, accounts: &HashSet<String>) -> String {
     let istty = unsafe { isatty(libc::STDOUT_FILENO) } != 0;
     if istty {
         let topcat = match get_top_category(item, storage) {

+ 4 - 4
src/convert.rs

@@ -5,7 +5,7 @@ use crate::receipt;
 use crate::user::User;
 use chrono::{DateTime, Utc};
 use qif_generator::{account::Account, split::Split, transaction::Transaction};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
 use std::fs;
 
 /// Read json file with receipt and convert it into `receipt::Purchase`
@@ -18,12 +18,12 @@ pub fn read_file(f: &str) -> receipt::Purchase {
 pub fn gen_splits<F, C>(
     items: &[receipt::Item],
     cs: &mut CatStats,
-    accounts: &[String],
+    accounts: &HashSet<String>,
     filter: F,
     categorizer: C,
 ) -> Vec<Split>
 where
-    C: Fn(&str, &mut CatStats, &[String]) -> String,
+    C: Fn(&str, &mut CatStats, &HashSet<String>) -> String,
     F: Fn(&str) -> &str,
 {
     let mut result: Vec<Split> = Vec::new();
@@ -99,7 +99,7 @@ pub fn convert<'a, F, C>(
 ) -> Result<Transaction<'a>, String>
 where
     F: Fn(&str) -> &str,
-    C: Fn(&str, &mut CatStats, &[String]) -> String,
+    C: Fn(&str, &mut CatStats, &HashSet<String>) -> String,
 {
     let purchase = &read_file(filename);
     let splits = &gen_splits(

+ 5 - 3
src/main.rs

@@ -1,5 +1,6 @@
 use qif_generator::account::{Account, AccountType};
 
+use std::collections::HashSet;
 use std::path::PathBuf;
 use structopt::StructOpt;
 
@@ -117,9 +118,10 @@ fn main() {
         .build();
 
     if let Some(filename) = &args.filename {
-        let cat = &|item: &str, stats: &mut categories::CatStats, acc: &[String]| -> String {
-            categories::get_category(filter(item), stats, acc)
-        };
+        let cat = &|item: &str,
+                    stats: &mut categories::CatStats,
+                    acc: &HashSet<String>|
+         -> String { categories::get_category(filter(item), stats, acc) };
         let t = convert::convert(filename, &args.memo, &mut user, &acc, filter, cat).unwrap();
         print!("{}", acc);
         println!("{}", t);

+ 2 - 7
src/telegram.rs

@@ -6,7 +6,7 @@ use qif_generator::account::{Account, AccountType};
 use crate::monitoring;
 use crate::tgusermanager::user_manager;
 use crate::user::User;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
 use std::fmt;
 
 use derive_more::From;
@@ -228,11 +228,6 @@ async fn handle_json(
 
     if is_file {
         log::info!("File {} received", file_id);
-        bot.send_message(msg.chat.id, format!("New file received!!!111 {}", file_id))
-            .await?;
-    } else {
-        bot.send_message(msg.chat.id, "Unsupported file format".to_string())
-            .await?;
     }
 
     if let Ok(newfile) = download_file(&bot, &file_id).await {
@@ -474,7 +469,7 @@ async fn handle_qif_ready(
     )
     .await?;
 
-    let cat = &|item: &str, _stats: &mut categories::CatStats, _acc: &[String]| -> String {
+    let cat = &|item: &str, _stats: &mut categories::CatStats, _acc: &HashSet<String>| -> String {
         item_categories.get(item).unwrap().to_owned()
     };
 

+ 6 - 5
src/user.rs

@@ -2,6 +2,7 @@ use crate::categories::CatStats;
 use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
 use radix_trie::Trie;
 use shellexpand::tilde;
+use std::collections::HashSet;
 use std::path::PathBuf;
 use std::time::Duration;
 
@@ -11,7 +12,7 @@ pub struct User {
     pub catmap: CatStats,
 
     /// Available accounts for the user
-    pub accounts: Vec<String>,
+    pub accounts: HashSet<String>,
 
     /// database with config
     db: PickleDb,
@@ -59,9 +60,9 @@ impl User {
             None => Trie::new(),
         };
 
-        let accounts = match db.get("accounts") {
-            Some(a) => a,
-            None => vec![],
+        let accounts = match db.get::<Vec<String>>("accounts") {
+            Some(a) => HashSet::from_iter(a),
+            None => HashSet::new(),
         };
 
         User {
@@ -72,7 +73,7 @@ impl User {
     }
 
     pub fn accounts(&mut self, acc: Vec<String>) {
-        self.accounts = acc;
+        self.accounts = HashSet::from_iter(acc);
     }
 
     pub fn save_data(&mut self) {