From e67689813532878fbff5b53d9c60cbf384749285 Mon Sep 17 00:00:00 2001 From: Mikhail Mitrofanov Date: Sat, 15 Aug 2026 13:22:59 +0300 Subject: [PATCH] Clippy code cleanup --- Cargo.lock | 9 +++ Cargo.toml | 7 +- benches/map_bench.rs | 126 ++++++++++++++++++++++++++++++++ src/data_provider/card_sets.rs | 2 +- src/data_provider/card_stats.rs | 17 ++--- src/data_provider/history.rs | 2 +- src/data_provider/settings.rs | 11 ++- src/data_provider/web_api.rs | 7 +- src/data_provider/words.rs | 8 +- src/dictionary.rs | 59 ++++++++------- src/dictionary_test.rs | 4 +- src/import.rs | 19 +++-- src/lang.rs | 28 ++----- src/main.rs | 10 ++- src/navigation.rs | 44 +++++------ src/quiz.rs | 26 ++++--- src/repetition.rs | 34 ++++----- src/repetition_settings.rs | 4 +- src/repetitions.rs | 18 ++--- src/sync.rs | 2 +- src/word.rs | 14 ++-- src/writing.rs | 10 +-- 22 files changed, 290 insertions(+), 171 deletions(-) create mode 100644 benches/map_bench.rs diff --git a/Cargo.lock b/Cargo.lock index e2441ce..6f41fa7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,12 @@ dependencies = [ "cc", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "alsa" version = "0.11.0" @@ -1750,6 +1756,8 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.2.0", ] @@ -2306,6 +2314,7 @@ dependencies = [ "chrono", "criterion", "dirs", + "hashbrown 0.17.1", "hex", "iced", "iced_core", diff --git a/Cargo.toml b/Cargo.toml index 93a3e53..df9e21f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ zstd = "0.13.3" zip = "8.6.0" rfd = "0.17.2" mimalloc = "0.1.52" +hashbrown = "0.17.1" [profile.super-release] inherits = "release" @@ -32,10 +33,10 @@ strip = true panic = "abort" [dev-dependencies] -criterion = "0.8.2" +criterion = { version = "0.8.2", features = ["html_reports"] } [[bench]] -name = "split_bench" # Имя файла в benches/ без расширения -harness = false # Отключаем стандартный тестовый раннер +name = "map_bench" +harness = false diff --git a/benches/map_bench.rs b/benches/map_bench.rs new file mode 100644 index 0000000..9438bd5 --- /dev/null +++ b/benches/map_bench.rs @@ -0,0 +1,126 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use std::collections::HashMap as StdHashMap; +use std::hint::black_box; + +use hashbrown::HashMap as BrownHashMap; + +const SIZES: [usize; 3] = [5, 10, 50]; +const QUERY_COUNT: usize = 4096; + +/// Детерминированный ключ ~17 символов, например "key_9e3779b9_0042". +fn make_key(i: u64) -> String { + let h = i.wrapping_mul(0x9E37_79B9_7F4A_7C15); + format!("key_{:08x}_{:04}", h & 0xFFFF_FFFF, i) +} + +// Для длинных ключей (пути/URL) замени на: +// fn make_key(i: u64) -> String { +// format!( +// "/api/v2/users/{i}/settings/visibility_{:08x}", +// i.wrapping_mul(0x9E37_79B9) +// ) +// } + +fn make_vec(n: usize) -> Vec<(String, u64)> { + (0..n as u64).map(|i| (make_key(i), i)).collect() +} + +fn make_std_map(data: &[(String, u64)]) -> StdHashMap { + data.iter().map(|(k, v)| (k.clone(), *v)).collect() +} + +fn make_brown_map(data: &[(String, u64)]) -> BrownHashMap { + data.iter().map(|(k, v)| (k.clone(), *v)).collect() +} + +fn make_queries(n: usize, with_misses: bool) -> Vec { + let keys: Vec = (0..n as u64).map(make_key).collect(); + let missing = "__missing_key__".to_string(); + + (0..QUERY_COUNT) + .map(|i| { + if with_misses && i % 16 == 15 { + missing.clone() + } else { + let idx = i.wrapping_mul(2_654_435_761) % n; + keys[idx].clone() + } + }) + .collect() +} + +fn lookup_std(map: &StdHashMap, queries: &[String]) -> u64 { + let mut sum = 0u64; + for q in queries { + match map.get(black_box(q.as_str())) { + Some(v) => sum = sum.wrapping_add(*v), + None => sum = sum.wrapping_add(1), + } + } + black_box(sum) +} + +fn lookup_brown(map: &BrownHashMap, queries: &[String]) -> u64 { + let mut sum = 0u64; + for q in queries { + match map.get(black_box(q.as_str())) { + Some(v) => sum = sum.wrapping_add(*v), + None => sum = sum.wrapping_add(1), + } + } + black_box(sum) +} + +fn lookup_vec(data: &[(String, u64)], queries: &[String]) -> u64 { + let mut sum = 0u64; + for q in queries { + let q = black_box(q); + match data.iter().find(|(k, _)| k == q) { + Some((_, v)) => sum = sum.wrapping_add(*v), + None => sum = sum.wrapping_add(1), + } + } + black_box(sum) +} + +fn bench(c: &mut Criterion) { + let mut group = c.benchmark_group("map_vs_vec_str"); + + for n in SIZES { + let vec_data = make_vec(n); + let std_map = make_std_map(&vec_data); + let brown_map = make_brown_map(&vec_data); + + let queries_hit = make_queries(n, false); + let queries_mixed = make_queries(n, true); + + // std::collections::HashMap (SipHash) + group.bench_function(format!("std_hashmap_hit/{n}"), |b| { + b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_hit))) + }); + group.bench_function(format!("std_hashmap_mixed/{n}"), |b| { + b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_mixed))) + }); + + // hashbrown (SwissTable + foldhash) + group.bench_function(format!("hashbrown_hit/{n}"), |b| { + b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_hit))) + }); + group.bench_function(format!("hashbrown_mixed/{n}"), |b| { + b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_mixed))) + }); + + // Vec<(String, u64)>, линейный поиск + group.bench_function(format!("vec_linear_hit/{n}"), |b| { + b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_hit))) + }); + group.bench_function(format!("vec_linear_mixed/{n}"), |b| { + b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_mixed))) + }); + } + + group.finish(); +} + +criterion_group!(benches, bench); +criterion_main!(benches); \ No newline at end of file diff --git a/src/data_provider/card_sets.rs b/src/data_provider/card_sets.rs index 6b36f36..8a4f701 100644 --- a/src/data_provider/card_sets.rs +++ b/src/data_provider/card_sets.rs @@ -48,7 +48,7 @@ pub fn add_set(set: &mut CardSetSettings, connection: &Connection) { pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) { if set.id == 0 { - add_set(set, &connection); + add_set(set, connection); } else { connection .execute( diff --git a/src/data_provider/card_stats.rs b/src/data_provider/card_stats.rs index ef4a3bb..d7ae457 100644 --- a/src/data_provider/card_stats.rs +++ b/src/data_provider/card_stats.rs @@ -27,16 +27,16 @@ pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec< buffer } -pub fn add_stat_list(stat: &mut Vec, connection: &Connection) { +pub fn add_stat_list(stat: &mut [CardStatistics], connection: &Connection) { let inserting = stat .iter() .map(|stat| { format!( "({}, {}, {}, {})", - stat.word_id.to_string(), - stat.set_id.to_string(), - stat.score.to_string(), - stat.last_open.timestamp().to_string() + stat.word_id, + stat.set_id, + stat.score, + stat.last_open.timestamp() ) }) .collect::>() @@ -48,7 +48,6 @@ pub fn add_stat_list(stat: &mut Vec, connection: &Connection) { let count = connection.execute(query.as_str(), ()); if count.is_err() { - println!("{}", count.unwrap_err()); return; } @@ -60,12 +59,10 @@ pub fn add_stat_list(stat: &mut Vec, connection: &Connection) { ) .unwrap(); - let start_index = last_index - (count.unwrap() as u32) + 1; + let start_index = last_index - (stat.len() as u32) + 1; - let mut index = 0; - for id in start_index..=last_index { + for (index, id) in (start_index..=last_index).enumerate() { stat[index].id = id; - index += 1; } } diff --git a/src/data_provider/history.rs b/src/data_provider/history.rs index 8cf403a..e7329e9 100644 --- a/src/data_provider/history.rs +++ b/src/data_provider/history.rs @@ -70,7 +70,7 @@ pub fn push_note(set_id: u32, item: HistoryItem) { item.before, item.after ); - writeln!(&mut file, "{}", line_str.to_string()).unwrap(); + writeln!(&mut file, "{}", line_str).unwrap(); } pub fn history_dir() -> PathBuf { diff --git a/src/data_provider/settings.rs b/src/data_provider/settings.rs index 9a26c25..bae4ae1 100644 --- a/src/data_provider/settings.rs +++ b/src/data_provider/settings.rs @@ -4,14 +4,13 @@ pub fn get_setting(key: String, connection: &Connection) -> Option { let mut stmt = connection .prepare("SELECT value FROM settings WHERE id = ?1") .unwrap(); - let iter = stmt.query_map((key,), |row| row.get(0)).unwrap(); + let mut iter = stmt.query_map((key,), |row| row.get(0)).unwrap(); - for row in iter { - if let Ok(value) = row { - return Some(value); - } - return None; + if let Some(row) = iter.next() && let Ok(value) = row + { + return Some(value); } + None } diff --git a/src/data_provider/web_api.rs b/src/data_provider/web_api.rs index 460a93c..eae3653 100644 --- a/src/data_provider/web_api.rs +++ b/src/data_provider/web_api.rs @@ -24,8 +24,7 @@ pub async fn send_data(id: String) { fn compress(data: Vec) -> Vec { let mut encoder = Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).unwrap(); io::copy(&mut &data[..], &mut encoder).unwrap(); - let compressed = encoder.finish().unwrap(); - compressed + encoder.finish().unwrap() } pub async fn load_data(id: String, temp: bool) { @@ -84,7 +83,7 @@ pub async fn get_web_version(key: &str) -> Result { let id_url = format!("{API_URL}{key}/version"); let client = reqwest::Client::new(); let version = client.get(&id_url).send().await?.text().await?; - return Ok(version.parse::().unwrap()); + Ok(version.parse::().unwrap()) } pub async fn get_local_version() -> u32 { @@ -95,7 +94,7 @@ pub async fn get_local_version() -> u32 { return data.parse::().unwrap(); } - let mut file = OpenOptions::new().write(true).create(true).open(file).await.unwrap(); + let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file).await.unwrap(); file.write_all("0".as_bytes()).await.unwrap(); 0 } diff --git a/src/data_provider/words.rs b/src/data_provider/words.rs index 46ff5a5..6f53af0 100644 --- a/src/data_provider/words.rs +++ b/src/data_provider/words.rs @@ -50,16 +50,14 @@ pub fn add_words(words: &mut[WordData], connection: &mut Connection) { let start_index = last_index - (count as u32) + 1; - let mut index = 0; - for id in start_index..=last_index { + for (index, id) in (start_index..=last_index).enumerate() { words[index].id = id; - index += 1; } } pub fn update_word(word: &mut WordData, connection: &Connection) { if word.id == 0 { - add_word(word, &connection); + add_word(word, connection); } else { connection .execute( @@ -155,7 +153,7 @@ pub fn add_group(group: &mut WordGroup, connection: &Connection) { pub fn update_group(group: &mut WordGroup, connection: &Connection) { if group.id == 0 { - add_group(group, &connection); + add_group(group, connection); } else { connection .execute( diff --git a/src/dictionary.rs b/src/dictionary.rs index 7192f75..2be3440 100644 --- a/src/dictionary.rs +++ b/src/dictionary.rs @@ -69,25 +69,25 @@ impl NavigatedPage for DictionaryState { if let Back = message { return Some(Page::PreviousPage); } - if let Test = message { - if self.include_map.iter().any(|x| *x) { - let mut words = vec![]; - let dict = &self.state.lock().unwrap().dictionary; + if let Test = message + && self.include_map.iter().any(|x| *x) + { + let mut words = vec![]; + let dict = &self.state.lock().unwrap().dictionary; - words = self - .include_map - .iter() - .zip(0..self.include_map.len()) - .filter(|(flag, _)| **flag) - .map(|(_, index)| dict[index].clone()) - .collect(); + words = self + .include_map + .iter() + .zip(0..self.include_map.len()) + .filter(|(flag, _)| **flag) + .map(|(_, index)| dict[index].clone()) + .collect(); - return Some(Page::DictionaryQuiz(DictionaryQuizState::new( - words, - self.reverse, - self.no_typing, - ))); - } + return Some(Page::DictionaryQuiz(DictionaryQuizState::new( + words, + self.reverse, + self.no_typing, + ))); } if let WordAction(index) = message { let word: WordData; @@ -119,7 +119,7 @@ impl NavigatedPage for DictionaryState { NewWord => { let mut state = self.state.lock().unwrap(); let mut word = WordData::new(); - word.group_id = state.word_groups[self.selected_group_index].id.clone(); + word.group_id = state.word_groups[self.selected_group_index].id; let dict = &mut state.dictionary; dict.push(word); @@ -318,7 +318,7 @@ impl DictionaryState { let connection = &state.connection; let word = &mut state.dictionary.get(i).unwrap().clone(); - update_word(word, &connection); + update_word(word, connection); state.dictionary[i] = word.clone(); } @@ -353,13 +353,12 @@ impl DictionaryState { continue; } - if !self.search.is_empty() { - if word.key.contains(&self.search) == false - && word.value.contains(&self.search) == false - && word.tags.contains(&self.search) == false - { - continue; - } + if !self.search.is_empty() + && !word.key.contains(&self.search) + && !word.value.contains(&self.search) + && !word.tags.contains(&self.search) + { + continue; } let word_line_data = WordLineState { @@ -553,7 +552,9 @@ impl DictionaryState { .iter() .map(|word| (split_with_coma(word.tags.as_str()), word.group_id)) .map(|(tags, word_group_id)| { - tags.iter().all(|t| include_tags.contains(t)) && tags.len() != 0 && word_group_id == group_id + !tags.is_empty() + && tags.iter().all(|t| include_tags.contains(t)) + && word_group_id == group_id }) .collect(); @@ -567,14 +568,12 @@ impl DictionaryState { let state = &self.state.lock().unwrap(); let groups = &state.word_groups; - let mut index = 0; - for group in groups { + for (index, group) in groups.iter().enumerate() { row = row.push( button(text!("{}", group.name.clone())) .style(text) .on_press(SelectGroup(index)), ); - index = index + 1; } let group = state.word_groups[self.selected_group_index].clone(); diff --git a/src/dictionary_test.rs b/src/dictionary_test.rs index 9409bcf..e864dba 100644 --- a/src/dictionary_test.rs +++ b/src/dictionary_test.rs @@ -151,7 +151,7 @@ impl DictionaryQuizState { if self.answer == self.correct || split_with_coma(self.correct.as_str()).contains(&self.answer) { - if self.is_help == false { + if !self.is_help { self.score.correct += 1; } self.show_next() @@ -208,7 +208,7 @@ impl DictionaryQuizState { } fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> { - if self.is_help && self.no_typing == false { + if self.is_help && !self.no_typing { return button("Апелляция").style(jl_button).on_press(Appeal).into(); } space().into() diff --git a/src/import.rs b/src/import.rs index b195c80..664cedb 100644 --- a/src/import.rs +++ b/src/import.rs @@ -63,7 +63,7 @@ pub enum ImportMessage { impl NavigatedPage for ImportState { fn navigate(&self, message: &ImportMessage) -> Option { - if let Some(_) = self.progress { + if self.progress.is_some() { return None; } @@ -254,7 +254,7 @@ impl ImportState { } fn property_selector(&self) -> Element<'_, ImportMessage> { - if self.selected_property == None { + if self.selected_property.is_none() { return space().into(); } column![ @@ -360,7 +360,7 @@ impl ImportState { spawn_blocking(move || { Self::extract_import_file(path)?; let data = Self::read_import_file()?; - return Ok(data); + Ok(data) }) .await .unwrap() @@ -452,11 +452,11 @@ impl ImportState { let mut word = WordData::new(); word.tags = import.tags.trim().replace(" ", ", "); - word.group_id = group_id.clone(); + word.group_id = group_id; for (dest, indices) in &map_indices { let collected_string = Self::collect_strings( &import.fields, - &indices, + indices, &separator, skip_empty, ); @@ -525,15 +525,14 @@ impl ImportState { } fn collect_strings( - properties: &Vec, - indices: &Vec, + properties: &[String], + indices: &[usize], separator: &str, skip_empty: bool, ) -> String { let mut working_words = Vec::with_capacity(indices.len()); - for i in 0..indices.len() { - let index = indices[i]; - let str = properties.get(index).unwrap(); + for index in indices { + let str = properties.get(*index).unwrap(); if skip_empty && str.is_empty() { continue; } diff --git a/src/lang.rs b/src/lang.rs index da47709..6e09572 100644 --- a/src/lang.rs +++ b/src/lang.rs @@ -199,14 +199,6 @@ impl KanaSet { } } - /* pub fn next(&mut self) -> (String, String) { - let current_set = self.list(); - - let mut rand = rand::rng(); - let index: u32 = rand.random(); - current_set[index as usize % current_set.len()].clone() - }*/ - pub fn list(&self) -> Vec<(String, String)> { let mut current_set: Vec<(String, String)> = Vec::new(); @@ -286,11 +278,7 @@ impl CardStatistics { } } - if self.score < 1 { - self.score = 1 - } else if self.score > MAX_SCORE { - self.score = MAX_SCORE - } + self.score = self.score.clamp(1, MAX_SCORE); self.last_open = Utc::now(); } @@ -325,7 +313,7 @@ impl CardSet { let state_for = state.clone(); let state_locked = state.lock().unwrap(); - let mut current_set = load_stats_of_set(&settings, &state_locked.connection); + let mut current_set = load_stats_of_set(settings, &state_locked.connection); let last_list = settings.get_word_list(&state_locked); let saved_ids = current_set.iter().map(|l| l.word_id).collect::>(); let word_ids = last_list.iter().map(|l| l.id).collect::>(); @@ -335,10 +323,10 @@ impl CardSet { .filter(|word| !saved_ids.contains(&word.id)) .map(|word| CardStatistics { id: 0, - word_id: word.id.clone(), + word_id: word.id, last_open: Utc::now(), score: 1, - set_id: settings.id.clone(), + set_id: settings.id, }) .collect(); @@ -383,7 +371,7 @@ impl CardSet { pub fn next(&mut self) -> (WordData, CardStatistics) { let index = match self.order_module.clone() { OrderModule::SemiRandomSRS(mut module) => { - if module.initialized == false { + if !module.initialized { module.init(self) } let index = module.next(self); @@ -391,7 +379,7 @@ impl CardSet { index } OrderModule::RandomSRS(mut module) => { - if module.initialized == false { + if !module.initialized { module.init(self) } let index = module.next(self); @@ -399,7 +387,7 @@ impl CardSet { index } OrderModule::WorstWordsSRS(mut module) => { - if module.initialized == false { + if !module.initialized { module.init(self) } let index = module.next(self); @@ -413,7 +401,7 @@ impl CardSet { } pub fn open(&mut self, status: WordOpenMode) { - if let None = self.current_word_index { + if self.current_word_index.is_none() { return; } let index = self.current_word_index.unwrap(); diff --git a/src/main.rs b/src/main.rs index a3dbd4b..40d26ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -58,7 +58,7 @@ fn main() -> iced::Result { fn window_settings() -> window::Settings { let mut settings = window::Settings{ position: Position::Centered, - min_size: Some(Size::new(700.0_f32.into(), 700.0_f32.into())), + min_size: Some(Size::new(700.0_f32, 700.0_f32)), .. Default::default() }; @@ -75,7 +75,7 @@ fn window_settings() -> window::Settings { } fn subscription(_state: &ScreenState) -> Subscription { - keyboard::listen().map(|e| Keyboard(e)) + keyboard::listen().map(Keyboard) } pub struct AppState { @@ -87,6 +87,12 @@ pub struct AppState { pub activity: HashMap> } +impl Default for AppState { + fn default() -> Self { + Self::new() + } +} + impl AppState { pub fn new() -> Self { diff --git a/src/navigation.rs b/src/navigation.rs index cc14fd7..47688ea 100644 --- a/src/navigation.rs +++ b/src/navigation.rs @@ -1,9 +1,12 @@ use crate::data_provider::history::{get_history_of_set, history_dir}; use crate::data_provider::sqlite::{create_db, default_connection}; -use crate::data_provider::web_api::{get_local_version, get_web_version, load_data, set_local_version}; -use crate::dictionary::{app_data_dir, DictionaryMessage, DictionaryState}; +use crate::data_provider::web_api::{ + get_local_version, get_web_version, load_data, set_local_version, +}; +use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir}; use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState}; use crate::history::{HistoryMessage, HistoryState}; +use crate::import::{ImportMessage, ImportState}; use crate::message_navigation; use crate::navigation::Page::*; use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData}; @@ -27,7 +30,6 @@ use reqwest::Error; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Instant; -use crate::import::{ImportMessage, ImportState}; impl Default for ScreenState { fn default() -> Self { @@ -99,7 +101,9 @@ impl ScreenState { final_task = Task::batch([ reading_additional_task, Task::perform(Self::load_web_backup(key), |result| { - if let Ok(update) = result && update { + if let Ok(update) = result + && update + { UpdateData } else { RootMessage::None @@ -118,23 +122,21 @@ impl ScreenState { async fn load_additional_data() -> RootMessage { let directory = history_dir(); let mut map = HashMap::new(); - for file in directory.read_dir().unwrap() { - if let Ok(file) = file { - let mut vec = vec![]; - let history_file_name = file.file_name().into_string().unwrap(); - let id = history_file_name[4..history_file_name.len() - 12] - .parse::() - .unwrap(); + for file in directory.read_dir().unwrap().flatten() { + let mut vec = vec![]; + let history_file_name = file.file_name().into_string().unwrap(); + let id = history_file_name[4..history_file_name.len() - 12] + .parse::() + .unwrap(); - let history = get_history_of_set(id); - let by_date = history.chunk_by(|x, x1| { - x.timestamp.naive_local().date() == x1.timestamp.naive_local().date() - }); - for group in by_date { - vec.push((group[0].timestamp.naive_local().date(), group.len() as u32)); - } - map.insert(id, vec); + let history = get_history_of_set(id); + let by_date = history.chunk_by(|x, x1| { + x.timestamp.naive_local().date() == x1.timestamp.naive_local().date() + }); + for group in by_date { + vec.push((group[0].timestamp.naive_local().date(), group.len() as u32)); } + map.insert(id, vec); } DataLoaded(map) } @@ -146,7 +148,7 @@ impl ScreenState { println!("Web version is newer than local version"); load_data(string, true).await; set_local_version(web).await; - }else { + } else { return Ok(false); } Ok(true) @@ -164,7 +166,7 @@ impl ScreenState { return Task::none(); } - if let UpdateData = message{ + if let UpdateData = message { println!("Loading data"); let mut state = self.app_state.lock().unwrap(); let path = app_data_dir(); diff --git a/src/quiz.rs b/src/quiz.rs index 904f244..936116d 100644 --- a/src/quiz.rs +++ b/src/quiz.rs @@ -42,7 +42,7 @@ impl NavigatedPage for QuizState { } self.current_roman = content; if self.correct_roman == self.current_roman { - if self.is_help == false { + if !self.is_help { self.score.correct += 1; } @@ -84,16 +84,7 @@ impl NavigatedPage for QuizState { .size(28) .width(150) .on_input(ContentChanged), - row![ - text!("{}", self.score.total.to_string()).size(25), - text!("{}", self.score.correct.to_string()) - .size(25) - .color(iced::Color::from_rgb8(60, 170, 60)), - text!("{}", self.score.fail.to_string()) - .color(iced::Color::from_rgb8(255, 79, 0)) - .size(25), - ] - .spacing(DEFAULT_SPACING), + score_display(&self.score), button("Закончить").style(jl_button).on_press(Back), ] .spacing(DEFAULT_SPACING) @@ -105,6 +96,19 @@ impl NavigatedPage for QuizState { } } +fn score_display<'a, T: 'a>(score: &Score) -> Element<'a, T> { + row![ + text!("{}", score.total.to_string()).size(25), + text!("{}", score.correct.to_string()) + .size(25) + .color(iced::Color::from_rgb8(60, 170, 60)), + text!("{}", score.fail.to_string()) + .color(iced::Color::from_rgb8(255, 79, 0)) + .size(25), + ] + .spacing(DEFAULT_SPACING).into() +} + impl QuizState { pub(crate) fn new() -> QuizState { QuizState { diff --git a/src/repetition.rs b/src/repetition.rs index 9219910..00e19b9 100644 --- a/src/repetition.rs +++ b/src/repetition.rs @@ -37,8 +37,7 @@ impl NavigatedPage for RepetitionState { } } - fn navigated(&mut self) { - } + fn navigated(&mut self) {} fn update(&mut self, message: RepetitionMessage) -> Task { match message { RepetitionMessage::Back => {} @@ -88,9 +87,9 @@ impl NavigatedPage for RepetitionState { (self.opened.len() as f32 / self.set.len() as f32 * 10000.0).round() / 100.0 ) ] - .height(Fill) - .width(Fill) - .into(), + .height(Fill) + .width(Fill) + .into(), RepetitionMessage::Back, ) } @@ -117,8 +116,6 @@ impl RepetitionState { } impl RepetitionState { - - fn next(&mut self) -> Task { if self.open { self.answer(WordOpenMode::None) @@ -169,7 +166,6 @@ impl RepetitionState { } } - fn draw_forward(&self) -> Element<'_, RepetitionMessage> { self.draw_card_view(self.settings.forward.as_str()) } @@ -294,18 +290,18 @@ impl KeyPressedPage for RepetitionState { text: _, repeat: _, } = message + && let Code(code) = pk { - if let Code(code) = pk { - return match code { - keyboard::key::Code::Space => self.next(), - keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None), - keyboard::key::Code::Digit2 => self.answer(WordOpenMode::Hard), - keyboard::key::Code::Digit3 => self.answer(WordOpenMode::Ok), - keyboard::key::Code::Digit4 => self.answer(WordOpenMode::Easy), - _ => Task::none(), - }; - } + return match code { + keyboard::key::Code::Space => self.next(), + keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None), + keyboard::key::Code::Digit2 => self.answer(WordOpenMode::Hard), + keyboard::key::Code::Digit3 => self.answer(WordOpenMode::Ok), + keyboard::key::Code::Digit4 => self.answer(WordOpenMode::Easy), + _ => Task::none(), + }; } + Task::none() } } @@ -322,7 +318,7 @@ pub enum RepetitionMessage { async fn play_sound(sink: Arc, text: String) { let data = get_voice(text.as_str()).await; spawn_blocking(move || { - rodio::play(&sink.mixer(), data).unwrap().sleep_until_end(); + rodio::play(sink.mixer(), data).unwrap().sleep_until_end(); }) .await .unwrap(); diff --git a/src/repetition_settings.rs b/src/repetition_settings.rs index bf53d98..1ad0c4d 100644 --- a/src/repetition_settings.rs +++ b/src/repetition_settings.rs @@ -73,11 +73,11 @@ impl NavigatedPage for RepetitionSettingsState { self.set.count = Some(count); } DeleteSet => { - if self.real_delete == false { + if !self.real_delete { self.real_delete = true; return Task::future(async { tokio::time::sleep(Duration::from_millis(3000)).await; - return RootMessage::RepetitionSettings(RevertDeleteSet); + RootMessage::RepetitionSettings(RevertDeleteSet) }); } let mut state = self.state.lock().unwrap(); diff --git a/src/repetitions.rs b/src/repetitions.rs index c354d42..5ff2620 100644 --- a/src/repetitions.rs +++ b/src/repetitions.rs @@ -263,7 +263,6 @@ impl RepetitionsState { column![self.activity_bar(set)].align_x(Center) .width(Fill) .spacing(DEFAULT_SPACING) - .into() } fn activity_bar(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { const MAX_DAY_COUNT: f32 = 128.0; @@ -301,7 +300,7 @@ impl RepetitionsState { .spacing(QUARTER_SPACING); - let mut iter = counts.into_iter(); + let mut iter = counts.iter(); for i in 0..30 { let mut column = Column::new().spacing(QUARTER_SPACING); @@ -309,7 +308,7 @@ impl RepetitionsState { let value = *iter.next().unwrap() as f32; let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1; - let date = now.clone().checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1)).unwrap(); + let date = (*now).checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1)).unwrap(); column = column.push(tooltip( iced::widget::container(space().height(15).width(15)).style( @@ -340,7 +339,7 @@ impl RepetitionsState { fn words_words_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { column![ text!("Худшие слова"), - container(scrollable(self.worst_words_list(&set)).height(200)).style(bordered_box), + container(scrollable(self.worst_words_list(set)).height(200)).style(bordered_box), radio( "Начать с плохих слов", SetOrderMode::TrainWorstFirst, @@ -376,19 +375,19 @@ impl RepetitionsState { fn sets_list(&self) -> Column<'_, RepetitionsMessage> { let mut column = Column::new(); - let mut i = 0; + let sets = &self.state.lock().unwrap().card_sets; - for set in sets { + for (i, set) in sets.iter().enumerate() { column = column.push( button(text!("{}", set.name.clone())) - .on_press_with(move || SelectSet(i.clone())) + .on_press_with(move || SelectSet(i)) .style(move |_x: &Theme, status: Status| Style { background: if status == Status::Hovered { Some(Background::Color(Color::WHITE.scale_alpha(0.2))) } else { None }, - text_color: if self.correct_filters[i.clone()] { + text_color: if self.correct_filters[i] { _x.palette().primary } else { _x.palette().warning @@ -402,7 +401,6 @@ impl RepetitionsState { snap: false, }), ); - i += 1; } column @@ -507,7 +505,7 @@ impl CardSetSettings { } fn update_worst_words(&mut self, state: &AppState) { - if let Some(_) = self.worst_words_list { + if self.worst_words_list.is_some() { return; } diff --git a/src/sync.rs b/src/sync.rs index c6509db..ad2a695 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -67,7 +67,7 @@ impl NavigatedPage for SyncState { } KeyCopied => {} IdReceived(new_id) => { - if validate_id(&new_id) == false { + if !validate_id(&new_id) { return Task::none(); } let mut state = self.state.lock().unwrap(); diff --git a/src/word.rs b/src/word.rs index 897f71d..abcdbf2 100644 --- a/src/word.rs +++ b/src/word.rs @@ -49,10 +49,8 @@ impl NavigatedPage for WordState { SetValue(n) => { self.word.value = n; } - SetAdditional(key, value) => match key.as_str() { - _ => { - self.word.additional.insert(key, value.clone()); - } + SetAdditional(key, value) => { + self.word.additional.insert(key, value.clone()); }, AddAdditional(key) => { self.word.additional.insert(key, "".to_string()); @@ -145,20 +143,20 @@ impl WordState { } } - fn reading_field(&self, value: &String) -> Element<'_, WordMessage> { + fn reading_field(&self, value: &str) -> Element<'_, WordMessage> { self.additional_field(value, "Чтение слова".to_string(), "reading".to_string()) } - fn description_field(&self, value: &String) -> Element<'_, WordMessage> { + fn description_field(&self, value: &str) -> Element<'_, WordMessage> { self.additional_field(value, "Описание".to_string(), "description".to_string()) } - fn context_field(&self, value: &String) -> Element<'_, WordMessage> { + fn context_field(&self, value: &str) -> Element<'_, WordMessage> { self.additional_field(value, "В контексте".to_string(), "context".to_string()) } fn additional_field( &self, - value: &String, + value: &str, name: String, id: String, ) -> Element<'_, WordMessage> { diff --git a/src/writing.rs b/src/writing.rs index 050a887..851dac2 100644 --- a/src/writing.rs +++ b/src/writing.rs @@ -97,18 +97,18 @@ impl WritingState { } if self.show_all { - if self.set.is_empty() == false && self.kana_total.is_empty() == false { + if !self.set.is_empty() && !self.kana_total.is_empty() { self.set.clear(); } for pair in &self.set { self.kana = "---".to_string(); - self.roman_total += &*format!("{} ", &pair.1.clone()).to_string(); - self.kana_total += &*format!("{} ", &pair.0).to_string(); + self.roman_total += &*format!("{} ", pair.1.clone()).to_string(); + self.kana_total += &*format!("{} ", pair.0).to_string(); } } else { let current = self.set.pop().unwrap(); - self.kana_total += &*format!("{} ", ¤t.0).to_string(); - self.roman_total += &*format!("{} ", ¤t.1.clone()).to_string(); + self.kana_total += &*format!("{} ", current.0).to_string(); + self.roman_total += &*format!("{} ", current.1.clone()).to_string(); self.kana = current.1; } }