Fixing some code problems

This commit is contained in:
2026-08-19 17:33:22 +03:00
parent a4d77196d0
commit 98c8093961
9 changed files with 32 additions and 109 deletions
-43
View File
@@ -1,43 +0,0 @@
use std::hint::black_box;
use criterion::{Criterion, criterion_group, criterion_main};
fn bench_split(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
fn bench_split_new(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma gpt", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
pub fn split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|ts| ts.to_lowercase().trim().to_string())
.filter(|t| !t.is_empty())
.collect::<Vec<String>>()
}
pub fn new_split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|s| s.trim()) // 0 аллокаций, просто срез
.filter(|s| !s.is_empty()) // отбрасываем пустые до аллокации
.map(|s| s.to_lowercase()) // 1 аллокация на валидный токен
.collect()
}
// Можно добавить несколько бенчмарков в группу
criterion_group!(benches, bench_split, bench_split_new);
criterion_main!(benches);
+22 -48
View File
@@ -1,5 +1,5 @@
use crate::lang::{CardStatistics, DeckSettings};
use rusqlite::Connection;
use rusqlite::{params, Connection};
use std::time::Instant;
pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec<CardStatistics> {
@@ -26,67 +26,41 @@ pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec<Ca
buffer
}
pub fn add_stat_list(stat: &mut [CardStatistics], connection: &Connection) {
pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) {
let time = Instant::now();
let inserting = stat
.iter()
.map(|stat| {
format!(
"({}, {}, {}, {})",
let tx = connection.transaction().unwrap();
let count = stats.len();
{
let mut stmt = tx
.prepare(
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4)",
)
.unwrap();
for stat in stats.iter() {
stmt.execute(params![
stat.word_id,
stat.set_id,
stat.score,
stat.last_open.timestamp()
)
})
.collect::<Vec<_>>()
.join(", ");
let query = format!(
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES {}",
inserting
);
let count = connection.execute(query.as_str(), ());
if count.is_err() {
return;
])
.unwrap();
}
}
let last_index: u32 = connection
.query_one(
"SELECT seq from sqlite_sequence WHERE name == ?1",
("card_stats".to_string(),),
|row| row.get(0),
)
.unwrap();
let last_index: u32 = tx.last_insert_rowid() as u32;
tx.commit().unwrap();
let start_index = last_index - (stat.len() as u32) + 1;
let start_index = last_index - (count as u32) + 1;
for (index, id) in (start_index..=last_index).enumerate() {
stat[index].id = id.into();
stats[index].id = id.into();
}
println!("Added {} cards for {:?}", stat.len(), time.elapsed());
println!("Added {} cards for {:?}", stats.len(), time.elapsed());
}
// pub fn add_stat(stat: &mut CardStatistics, connection: &Connection) {
// let time = Instant::now();
// let index = connection
// .query_row(
// "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4) RETURNING id",
// (
// &stat.word_id,
// &stat.set_id,
// &stat.score,
// &stat.last_open.timestamp(),
// ),
// |row| row.get(0)
// )
// .unwrap_or_else(|e| {println!("{}", e); 0});
//
// stat.id = index;
// println!("Added stat: {}", time.elapsed().as_millis());
// }
pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
let time = Instant::now();
+1 -7
View File
@@ -46,15 +46,9 @@ pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
}
}
let last_index: u32 = tx.last_insert_rowid() as u32;
tx.commit().unwrap();
let last_index: u32 = connection
.query_one(
"SELECT seq from sqlite_sequence WHERE name == ?1",
("words".to_string(),),
|row| row.get(0),
)
.unwrap();
let start_index = last_index - (count as u32) + 1;
-1
View File
@@ -1 +0,0 @@
+1 -1
View File
@@ -452,7 +452,7 @@ impl DeckData {
HistoryItem {
timestamp: Utc::now(),
word_id: word.word_id.into(),
mode: WordOpenMode::Easy,
mode: status,
before: old_score,
after: new_score,
},
-1
View File
@@ -2,7 +2,6 @@
mod data_provider;
mod dictionary;
mod dictionary_test;
pub mod helpers;
mod history;
pub mod import;
mod lang;
+1 -1
View File
@@ -54,7 +54,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
self.update_showed()
}
}
Back => todo!(),
Back => {},
}
Task::none()
}
+6 -6
View File
@@ -47,7 +47,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
let selected_set = self.selected_deck_mut().unwrap();
if selected_set.append_mode == AppendMode::Full {
Self::append_all_words(&clone.lock().unwrap(), selected_set);
Self::append_all_words(&mut clone.lock().unwrap(), selected_set);
selected_set.existing_words_indices = selected_set.available_words_indices.clone();
} else {
if selected_set
@@ -220,8 +220,8 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
}
let deck = self.selected_deck().unwrap();
let state = self.state.lock().unwrap();
Self::append_words(&state, &deck.general_settings, adding.into_iter());
let mut state = self.state.lock().unwrap();
Self::append_words(&mut state, &deck.general_settings, adding.into_iter());
}
}
Task::none()
@@ -565,7 +565,7 @@ impl RepetitionsState {
}
impl RepetitionsState {
fn append_all_words(state: &AppState, deck: &DeckViewData) {
fn append_all_words(state: &mut AppState, deck: &DeckViewData) {
let existing = deck.existing_words_indices.as_ref().unwrap();
let mut created_set = HashSet::with_capacity(existing.len());
existing.iter().for_each(|c| {
@@ -580,7 +580,7 @@ impl RepetitionsState {
.cloned();
Self::append_words(state, deck, required);
}
fn append_words(state: &AppState, deck: &DeckSettings, indices: impl Iterator<Item = usize>) {
fn append_words(state: &mut AppState, deck: &DeckSettings, indices: impl Iterator<Item = usize>) {
let words = &state.dictionary;
let stats = &mut indices
.map(|i| {
@@ -596,7 +596,7 @@ impl RepetitionsState {
.collect::<Vec<_>>();
if !stats.is_empty() {
add_stat_list(stats, &state.connection);
add_stat_list(stats, &mut state.connection);
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ impl NavigatedPage<WritingMessage> for WritingState {
fn navigated(&mut self) {}
fn update(&mut self, message: WritingMessage) -> Task<RootMessage> {
match message {
WritingMessage::Back => todo!(),
WritingMessage::Back => {},
WritingMessage::Next => self.next(),
WritingMessage::SwitchShowMode(b) => self.show_all = b,
}