Skip to content

Commit abaa795

Browse files
committed
Anki: Replace once_cell with stabilized LazyCell / LazyLock as far as possible
Since 1.80: rust-lang/rust#109736 and rust-lang/rust#98165 Non-Thread-Safe Lazy → std::cell::LazyCell https://doc.rust-lang.org/nightly/std/cell/struct.LazyCell.html Thread-safe SyncLazy → std::sync::LazyLock https://doc.rust-lang.org/nightly/std/sync/struct.LazyLock.html The compiler accepted LazyCell only in minilints. The final use in rslib/src/log.rs couldn't be replaced since get_or_try_init has not yet been standardized: rust-lang/rust#109737
1 parent e9b7268 commit abaa795

File tree

32 files changed

+101
-107
lines changed

32 files changed

+101
-107
lines changed

Cargo.lock

-5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

build/ninja_gen/Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,5 @@ globset.workspace = true
1616
itertools.workspace = true
1717
maplit.workspace = true
1818
num_cpus.workspace = true
19-
once_cell.workspace = true
2019
walkdir.workspace = true
2120
which.workspace = true

build/ninja_gen/src/input.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33

44
use std::collections::HashMap;
55
use std::fmt::Display;
6+
use std::sync::LazyLock;
67

78
use camino::Utf8PathBuf;
8-
use once_cell::sync::Lazy;
99

1010
#[derive(Debug, Clone, Hash, Default)]
1111
pub enum BuildInput {
@@ -119,7 +119,7 @@ pub struct Glob {
119119
pub exclude: Option<String>,
120120
}
121121

122-
static CACHED_FILES: Lazy<Vec<Utf8PathBuf>> = Lazy::new(|| cache_files());
122+
static CACHED_FILES: LazyLock<Vec<Utf8PathBuf>> = LazyLock::new(cache_files());
123123

124124
/// Walking the source tree once instead of for each glob yields ~4x speed
125125
/// improvements.

ftl/Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ camino.workspace = true
1616
clap.workspace = true
1717
fluent-syntax.workspace = true
1818
itertools.workspace = true
19-
once_cell.workspace = true
2019
regex.workspace = true
2120
serde_json.workspace = true
2221
snafu.workspace = true

ftl/src/garbage_collection.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::fs;
66
use std::io::BufReader;
77
use std::iter::FromIterator;
88
use std::path::PathBuf;
9+
use std::sync::LazyLock;
910

1011
use anki_io::create_file;
1112
use anyhow::Context;
@@ -14,7 +15,6 @@ use clap::Args;
1415
use fluent_syntax::ast;
1516
use fluent_syntax::ast::Resource;
1617
use fluent_syntax::parser;
17-
use once_cell::sync::Lazy;
1818
use regex::Regex;
1919
use walkdir::DirEntry;
2020
use walkdir::WalkDir;
@@ -144,7 +144,8 @@ fn extract_nested_messages_and_terms(
144144
ftl_roots: &[impl AsRef<str>],
145145
used_ftls: &mut HashSet<String>,
146146
) {
147-
static REFERENCE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\{\s*-?([-0-9a-z]+)\s*\}").unwrap());
147+
static REFERENCE: LazyLock<Regex> =
148+
LazyLock::new(|| Regex::new(r"\{\s*-?([-0-9a-z]+)\s*\}").unwrap());
148149
for_files_with_ending(ftl_roots, ".ftl", |entry| {
149150
let source = fs::read_to_string(entry.path()).expect("file not readable");
150151
for caps in REFERENCE.captures_iter(&source) {
@@ -196,12 +197,12 @@ fn entry_use_check(used_ftls: &HashSet<String>) -> impl Fn(&ast::Entry<&str>) ->
196197
}
197198

198199
fn extract_references_from_file(refs: &mut HashSet<String>, entry: &DirEntry) {
199-
static SNAKECASE_TR: Lazy<Regex> =
200-
Lazy::new(|| Regex::new(r"\Wtr\s*\.([0-9a-z_]+)\W").unwrap());
201-
static CAMELCASE_TR: Lazy<Regex> =
202-
Lazy::new(|| Regex::new(r"\Wtr2?\.([0-9A-Za-z_]+)\W").unwrap());
203-
static DESIGNER_STYLE_TR: Lazy<Regex> =
204-
Lazy::new(|| Regex::new(r"<string>([0-9a-z_]+)</string>").unwrap());
200+
static SNAKECASE_TR: LazyLock<Regex> =
201+
LazyLock::new(|| Regex::new(r"\Wtr\s*\.([0-9a-z_]+)\W").unwrap());
202+
static CAMELCASE_TR: LazyLock<Regex> =
203+
LazyLock::new(|| Regex::new(r"\Wtr2?\.([0-9A-Za-z_]+)\W").unwrap());
204+
static DESIGNER_STYLE_TR: LazyLock<Regex> =
205+
LazyLock::new(|| Regex::new(r"<string>([0-9a-z_]+)</string>").unwrap());
205206

206207
let file_name = entry.file_name().to_str().expect("non-unicode filename");
207208

rslib/linkchecker/Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ anki.workspace = true
1212
futures.workspace = true
1313
itertools.workspace = true
1414
linkcheck.workspace = true
15-
once_cell.workspace = true
1615
regex.workspace = true
1716
reqwest.workspace = true
1817
strum.workspace = true

rslib/linkchecker/tests/links.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
use std::borrow::Cow;
77
use std::env;
88
use std::iter;
9+
use std::sync::LazyLock;
910
use std::time::Duration;
1011

1112
use anki::links::help_page_link_suffix;
1213
use anki::links::help_page_to_link;
1314
use anki::links::HelpPage;
1415
use futures::StreamExt;
1516
use itertools::Itertools;
16-
use once_cell::sync::Lazy;
1717
use linkcheck::validation::check_web;
1818
use linkcheck::validation::Context;
1919
use linkcheck::validation::Reason;
@@ -70,9 +70,7 @@ impl From<&'static str> for CheckableUrl {
7070
}
7171

7272
fn ts_help_pages() -> impl Iterator<Item = &'static str> {
73-
static QUOTED_URL: Lazy<Regex> = Lazy::new(|| {
74-
Regex::new("\"(http.+)\"").unwrap()
75-
});
73+
static QUOTED_URL: LazyLock<Regex> = LazyLock::new(|| Regex::new("\"(http.+)\"").unwrap());
7674

7775
QUOTED_URL
7876
.captures_iter(include_str!("../../../ts/lib/tslib/help-page.ts"))

rslib/proto_gen/Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ anyhow.workspace = true
1515
camino.workspace = true
1616
inflections.workspace = true
1717
itertools.workspace = true
18-
once_cell.workspace = true
1918
prost-reflect.workspace = true
2019
prost-types.workspace = true
2120
regex.workspace = true

rslib/proto_gen/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use std::collections::HashMap;
88
use std::env;
99
use std::path::PathBuf;
10+
use std::sync::LazyLock;
1011

1112
use anki_io::read_to_string;
1213
use anki_io::write_file_if_changed;
@@ -16,7 +17,6 @@ use camino::Utf8Path;
1617
use inflections::Inflect;
1718
use itertools::Either;
1819
use itertools::Itertools;
19-
use once_cell::sync::Lazy;
2020
use prost_reflect::DescriptorPool;
2121
use prost_reflect::MessageDescriptor;
2222
use prost_reflect::MethodDescriptor;
@@ -238,8 +238,8 @@ pub fn add_must_use_annotations_to_file<E>(path: &Utf8Path, is_empty: E) -> Resu
238238
where
239239
E: Fn(&Utf8Path, &str) -> bool,
240240
{
241-
static MESSAGE_OR_ENUM_RE: Lazy<Regex> =
242-
Lazy::new(|| Regex::new(r"pub (struct|enum) ([[:alnum:]]+?)\s").unwrap());
241+
static MESSAGE_OR_ENUM_RE: LazyLock<Regex> =
242+
LazyLock::new(|| Regex::new(r"pub (struct|enum) ([[:alnum:]]+?)\s").unwrap());
243243
let contents = read_to_string(path)?;
244244
let contents = MESSAGE_OR_ENUM_RE.replace_all(&contents, |caps: &Captures| {
245245
let is_enum = caps.get(1).unwrap().as_str() == "enum";

rslib/src/ankidroid/db.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::collections::HashMap;
55
use std::mem::size_of;
66
use std::sync::atomic::AtomicI32;
77
use std::sync::atomic::Ordering;
8+
use std::sync::LazyLock;
89
use std::sync::Mutex;
910

1011
use anki_proto::ankidroid::sql_value::Data;
@@ -16,7 +17,6 @@ use itertools::FoldWhile;
1617
use itertools::FoldWhile::Continue;
1718
use itertools::FoldWhile::Done;
1819
use itertools::Itertools;
19-
use once_cell::sync::Lazy;
2020
use rusqlite::ToSql;
2121
use serde::Deserialize;
2222

@@ -110,8 +110,8 @@ fn select_slice_of_size<'a>(
110110

111111
type SequenceNumber = i32;
112112

113-
static HASHMAP: Lazy<Mutex<HashMap<CollectionId, HashMap<SequenceNumber, DbResponse>>>> =
114-
Lazy::new(|| Mutex::new(HashMap::new()));
113+
static HASHMAP: LazyLock<Mutex<HashMap<CollectionId, HashMap<SequenceNumber, DbResponse>>>> =
114+
LazyLock::new(|| Mutex::new(HashMap::new()));
115115

116116
pub(crate) fn flush_single_result(col: &Collection, sequence_number: i32) {
117117
HASHMAP
@@ -244,7 +244,7 @@ pub(crate) fn next_sequence_number() -> i32 {
244244

245245
// same as we get from
246246
// io.requery.android.database.CursorWindow.sCursorWindowSize
247-
static DB_COMMAND_PAGE_SIZE: Lazy<Mutex<usize>> = Lazy::new(|| Mutex::new(1024 * 1024 * 2));
247+
static DB_COMMAND_PAGE_SIZE: LazyLock<Mutex<usize>> = LazyLock::new(|| Mutex::new(1024 * 1024 * 2));
248248

249249
pub(crate) fn set_max_page_size(size: usize) {
250250
let mut state = DB_COMMAND_PAGE_SIZE.lock().expect("Could not lock mutex");

rslib/src/ankihub/login.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// Copyright: Ankitects Pty Ltd and contributors
22
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
33

4-
use once_cell::sync::Lazy;
4+
use std::sync::LazyLock;
5+
56
use regex::Regex;
67
use reqwest::Client;
78
use serde;
@@ -31,7 +32,7 @@ pub async fn ankihub_login<S: Into<String>>(
3132
client: Client,
3233
) -> Result<LoginResponse> {
3334
let client = HttpAnkiHubClient::new("", client);
34-
static EMAIL_RE: Lazy<Regex> = Lazy::new(|| {
35+
static EMAIL_RE: LazyLock<Regex> = LazyLock::new(|| {
3536
Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap()
3637
});
3738
let mut request = LoginRequest {

rslib/src/backend/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ use std::ops::Deref;
1919
use std::result;
2020
use std::sync::Arc;
2121
use std::sync::Mutex;
22+
use std::sync::OnceLock;
2223
use std::thread::JoinHandle;
2324

2425
use futures::future::AbortHandle;
25-
use once_cell::sync::OnceCell;
2626
use prost::Message;
2727
use reqwest::Client;
2828
use tokio::runtime;
@@ -53,7 +53,7 @@ pub struct BackendInner {
5353
server: bool,
5454
sync_abort: Mutex<Option<AbortHandle>>,
5555
progress_state: Arc<Mutex<ProgressState>>,
56-
runtime: OnceCell<Runtime>,
56+
runtime: OnceLock<Runtime>,
5757
state: Mutex<BackendState>,
5858
backup_task: Mutex<Option<JoinHandle<Result<()>>>>,
5959
media_sync_task: Mutex<Option<JoinHandle<Result<()>>>>,
@@ -88,7 +88,7 @@ impl Backend {
8888
want_abort: false,
8989
last_progress: None,
9090
})),
91-
runtime: OnceCell::new(),
91+
runtime: OnceLock::new(),
9292
state: Mutex::new(BackendState::default()),
9393
backup_task: Mutex::new(None),
9494
media_sync_task: Mutex::new(None),

rslib/src/cloze.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::borrow::Cow;
55
use std::collections::HashMap;
66
use std::collections::HashSet;
77
use std::fmt::Write;
8+
use std::sync::LazyLock;
89

910
use anki_proto::image_occlusion::get_image_occlusion_note_response::ImageOcclusion;
1011
use anki_proto::image_occlusion::get_image_occlusion_note_response::ImageOcclusionShape;
@@ -14,7 +15,6 @@ use nom::bytes::complete::tag;
1415
use nom::bytes::complete::take_while;
1516
use nom::combinator::map;
1617
use nom::IResult;
17-
use once_cell::sync::Lazy;
1818
use regex::Captures;
1919
use regex::Regex;
2020

@@ -24,7 +24,7 @@ use crate::latex::contains_latex;
2424
use crate::template::RenderContext;
2525
use crate::text::strip_html_preserving_entities;
2626

27-
static MATHJAX: Lazy<Regex> = Lazy::new(|| {
27+
static MATHJAX: LazyLock<Regex> = LazyLock::new(|| {
2828
Regex::new(
2929
r"(?xsi)
3030
(\\[(\[]) # 1 = mathjax opening tag

rslib/src/import_export/text/csv/export.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ use std::collections::HashMap;
66
use std::fs::File;
77
use std::io::Write;
88
use std::sync::Arc;
9+
use std::sync::LazyLock;
910

1011
use anki_proto::import_export::ExportNoteCsvRequest;
1112
use itertools::Itertools;
12-
use once_cell::sync::Lazy;
1313
use regex::Regex;
1414

1515
use super::metadata::Delimiter;
@@ -156,7 +156,7 @@ fn field_to_record_field(field: &str, with_html: bool) -> Cow<str> {
156156
}
157157

158158
fn strip_redundant_sections(text: &str) -> Cow<str> {
159-
static RE: Lazy<Regex> = Lazy::new(|| {
159+
static RE: LazyLock<Regex> = LazyLock::new(|| {
160160
Regex::new(
161161
r"(?isx)
162162
<style>.*?</style> # style elements
@@ -170,7 +170,8 @@ fn strip_redundant_sections(text: &str) -> Cow<str> {
170170
}
171171

172172
fn strip_answer_side_question(text: &str) -> Cow<str> {
173-
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?is)^.*<hr id=answer>\n*").unwrap());
173+
static RE: LazyLock<Regex> =
174+
LazyLock::new(|| Regex::new(r"(?is)^.*<hr id=answer>\n*").unwrap());
174175
RE.replace_all(text.as_ref(), "")
175176
}
176177

rslib/src/latex.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
33

44
use std::borrow::Cow;
5+
use std::sync::LazyLock;
56

6-
use once_cell::sync::Lazy;
77
use regex::Captures;
88
use regex::Regex;
99

1010
use crate::cloze::expand_clozes_to_reveal_latex;
1111
use crate::media::files::sha1_of_data;
1212
use crate::text::strip_html;
1313

14-
pub(crate) static LATEX: Lazy<Regex> = Lazy::new(|| {
14+
pub(crate) static LATEX: LazyLock<Regex> = LazyLock::new(|| {
1515
Regex::new(
1616
r"(?xsi)
1717
\[latex\](.+?)\[/latex\] # 1 - standard latex
@@ -23,7 +23,7 @@ pub(crate) static LATEX: Lazy<Regex> = Lazy::new(|| {
2323
)
2424
.unwrap()
2525
});
26-
static LATEX_NEWLINES: Lazy<Regex> = Lazy::new(|| {
26+
static LATEX_NEWLINES: LazyLock<Regex> = LazyLock::new(|| {
2727
Regex::new(
2828
r#"(?xi)
2929
<br( /)?>

rslib/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub mod undo;
5252
pub mod version;
5353

5454
use std::env;
55+
use std::sync::LazyLock;
5556

56-
use once_cell::sync::Lazy;
57-
58-
pub(crate) static PYTHON_UNIT_TESTS: Lazy<bool> = Lazy::new(|| env::var("ANKI_TEST_MODE").is_ok());
57+
pub(crate) static PYTHON_UNIT_TESTS: LazyLock<bool> =
58+
LazyLock::new(|| env::var("ANKI_TEST_MODE").is_ok());

rslib/src/media/check.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ use std::collections::HashMap;
66
use std::collections::HashSet;
77
use std::fs;
88
use std::io;
9+
use std::sync::LazyLock;
910

1011
use anki_i18n::without_unicode_isolation;
1112
use anki_io::write_file;
1213
use data_encoding::BASE64;
13-
use once_cell::sync::Lazy;
1414
use regex::Regex;
1515
use tracing::debug;
1616
use tracing::info;
@@ -459,7 +459,7 @@ impl MediaChecker<'_> {
459459
}
460460

461461
fn maybe_extract_inline_image<'a>(&mut self, fname_decoded: &'a str) -> Result<Cow<'a, str>> {
462-
static BASE64_IMG: Lazy<Regex> = Lazy::new(|| {
462+
static BASE64_IMG: LazyLock<Regex> = LazyLock::new(|| {
463463
Regex::new("(?i)^data:image/(jpg|jpeg|png|gif|webp|avif);base64,(.+)$").unwrap()
464464
});
465465

0 commit comments

Comments
 (0)