Skip to content

Commit 0aee822

Browse files
committed
Replace lazy_static with std::sync::OnceLock, bump MSRV to 1.71
1 parent d835bb2 commit 0aee822

8 files changed

Lines changed: 59 additions & 55 deletions

File tree

.github/workflows/rust.yml

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ jobs:
1717
rust:
1818
- stable
1919
- nightly
20-
- 1.65.0
20+
- 1.71.0
2121
os:
2222
- ubuntu-latest
2323
- macos-11
@@ -27,14 +27,6 @@ jobs:
2727

2828
steps:
2929
- uses: actions/checkout@v3
30-
- name: Install old nightly for minimal-versions (produces v3 lockfile)
31-
if: matrix.rust == '1.65.0'
32-
uses: dtolnay/rust-toolchain@stable
33-
with:
34-
toolchain: nightly-2024-02-01
35-
- name: Generate minimal-versions lockfile
36-
if: matrix.rust == '1.65.0'
37-
run: cargo +nightly-2024-02-01 -Z minimal-versions generate-lockfile
3830
- uses: dtolnay/rust-toolchain@stable
3931
with:
4032
toolchain: ${{ matrix.rust }}

cpp_build/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ docs-only = []
1818
parallel = ["cc/parallel"]
1919

2020
[dependencies]
21-
lazy_static = "1.0"
2221
cc = "1.0.38"
2322
cpp_common = { path = "../cpp_common", version = "=0.5.10" }
2423
syn = { version = "2.0", features=["full", "visit"] }

cpp_build/src/lib.rs

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99
mod strnom;
1010

1111
use cpp_common::*;
12-
use lazy_static::lazy_static;
1312
use std::collections::hash_map::{Entry, HashMap};
1413
use std::env;
1514
use std::fs::{create_dir, remove_dir_all, File};
1615
use std::io::prelude::*;
1716
use std::path::{Path, PathBuf};
17+
use std::sync::OnceLock;
1818

1919
mod parser;
2020

@@ -122,19 +122,27 @@ template<typename T> int compare_helper(const T &a, const T&b, int cmp) {
122122
}
123123
"#;
124124

125-
lazy_static! {
126-
static ref CPP_DIR: PathBuf = OUT_DIR.join("rust_cpp");
127-
static ref CARGO_MANIFEST_DIR: PathBuf = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect(
128-
r#"
125+
static CPP_DIR_LOCK: OnceLock<PathBuf> = OnceLock::new();
126+
static CARGO_MANIFEST_DIR_LOCK: OnceLock<PathBuf> = OnceLock::new();
127+
128+
fn cpp_dir() -> &'static PathBuf {
129+
CPP_DIR_LOCK.get_or_init(|| out_dir().join("rust_cpp"))
130+
}
131+
132+
fn cargo_manifest_dir() -> &'static PathBuf {
133+
CARGO_MANIFEST_DIR_LOCK.get_or_init(|| {
134+
PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect(
135+
r#"
129136
-- rust-cpp fatal error --
130137
131138
The CARGO_MANIFEST_DIR environment variable was not set.
132-
NOTE: rust-cpp's build function must be run in a build script."#
133-
));
139+
NOTE: rust-cpp's build function must be run in a build script."#,
140+
))
141+
})
134142
}
135143

136144
fn gen_cpp_lib(visitor: &parser::Parser) -> PathBuf {
137-
let result_path = CPP_DIR.join("cpp_closures.cpp");
145+
let result_path = cpp_dir().join("cpp_closures.cpp");
138146
let mut output = File::create(&result_path).expect("Unable to generate temporary C++ file");
139147

140148
write!(output, "{}", INTERNAL_CPP_STRUCTS).unwrap();
@@ -146,7 +154,7 @@ extern "C" {{
146154
void (*rust_cpp_callbacks{file_hash}[{callbacks_count}])() = {{}};
147155
}}
148156
"#,
149-
file_hash = *FILE_HASH,
157+
file_hash = file_hash(),
150158
callbacks_count = visitor.callbacks_count
151159
).unwrap();
152160
}
@@ -348,7 +356,7 @@ MetaData metadata_{hash} = {{
348356
349357
}} // namespace rustcpp
350358
"#,
351-
hash = *FILE_HASH,
359+
hash = file_hash(),
352360
data = sizealign.join(", "),
353361
length = sizealign.len(),
354362
magic = magic.join(", "),
@@ -364,16 +372,16 @@ MetaData metadata_{hash} = {{
364372
}
365373

366374
fn clean_artifacts() {
367-
if CPP_DIR.is_dir() {
368-
remove_dir_all(&*CPP_DIR).expect(
375+
if cpp_dir().is_dir() {
376+
remove_dir_all(cpp_dir()).expect(
369377
r#"
370378
-- rust-cpp fatal error --
371379
372380
Failed to remove existing build artifacts from output directory."#,
373381
);
374382
}
375383

376-
create_dir(&*CPP_DIR).expect(
384+
create_dir(cpp_dir()).expect(
377385
r#"
378386
-- rust-cpp fatal error --
379387
@@ -405,7 +413,7 @@ impl Default for Config {
405413
/// directories to work with `cpp`.
406414
impl From<cc::Build> for Config {
407415
fn from(mut cc: cc::Build) -> Self {
408-
cc.cpp(true).include(&*CARGO_MANIFEST_DIR);
416+
cc.cpp(true).include(cargo_manifest_dir());
409417
Self { cc, std_flag_set: false }
410418
}
411419
}

cpp_build/src/parser.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use cpp_common::{Class, Closure, Macro, RustInvocation};
2-
use lazy_static::lazy_static;
32
use regex::Regex;
43
use std::fmt;
54
use std::fs::File;
65
use std::io::Read;
76
use std::mem::swap;
87
use std::path::{Path, PathBuf};
8+
use std::sync::OnceLock;
99
use syn::visit::Visit;
1010

1111
#[allow(clippy::enum_variant_names)]
@@ -114,11 +114,11 @@ fn expand_sub_rust_macro(input: String, mut t: ExpandSubMacroType) -> Result<Str
114114
rust_invocation.id.clone().to_string()
115115
}
116116
ExpandSubMacroType::Closure(ref mut offset) => {
117-
use cpp_common::FILE_HASH;
117+
use cpp_common::file_hash;
118118
**offset += 1;
119119
format!(
120120
"rust_cpp_callbacks{file_hash}[{offset}]",
121-
file_hash = *FILE_HASH,
121+
file_hash = file_hash(),
122122
offset = **offset - 1
123123
)
124124
}
@@ -214,10 +214,9 @@ fn skip_literal(mut input: Cursor) -> PResult<bool> {
214214
}
215215
return Ok((input.advance(1), true));
216216
}
217-
lazy_static! {
218-
static ref RAW: Regex = Regex::new(r##"^b?r#*""##).unwrap();
219-
}
220-
if RAW.is_match(input.rest) {
217+
static RAW: OnceLock<Regex> = OnceLock::new();
218+
let raw = RAW.get_or_init(|| Regex::new(r##"^b?r#*""##).unwrap());
219+
if raw.is_match(input.rest) {
221220
let q = input.rest.find('r').unwrap();
222221
input = input.advance(q + 1);
223222
return raw_string(input).map(|x| (x.0, true));

cpp_common/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,4 @@ documentation = "https://docs.rs/cpp_common"
1313

1414
[dependencies]
1515
syn = { version = "2.0", features = ["full", "extra-traits"] }
16-
lazy_static = "1.0"
1716
proc-macro2 = "1.0"

cpp_common/src/lib.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,11 @@
77
extern crate syn;
88
extern crate proc_macro2;
99

10-
#[macro_use]
11-
extern crate lazy_static;
12-
1310
use std::collections::hash_map::DefaultHasher;
1411
use std::env;
1512
use std::hash::{Hash, Hasher};
1613
use std::path::PathBuf;
14+
use std::sync::OnceLock;
1715

1816
use proc_macro2::{Span, TokenStream, TokenTree};
1917
use syn::ext::IdentExt;
@@ -58,19 +56,27 @@ pub const STRUCT_METADATA_MAGIC: [u8; 128] = [
5856
134, 183, 212, 227, 31, 217, 12, 5, 65, 221, 150, 59, 230, 96, 73, 62,
5957
];
6058

61-
lazy_static! {
62-
pub static ref OUT_DIR: PathBuf = PathBuf::from(env::var("OUT_DIR").expect(
63-
r#"
59+
static OUT_DIR_LOCK: OnceLock<PathBuf> = OnceLock::new();
60+
static FILE_HASH_LOCK: OnceLock<u64> = OnceLock::new();
61+
62+
pub fn out_dir() -> &'static PathBuf {
63+
OUT_DIR_LOCK.get_or_init(|| {
64+
PathBuf::from(env::var("OUT_DIR").expect(
65+
r#"
6466
-- rust-cpp fatal error --
6567
6668
The OUT_DIR environment variable was not set.
67-
NOTE: rustc must be run by Cargo."#
68-
));
69-
pub static ref FILE_HASH: u64 = {
70-
let mut hasher = std::collections::hash_map::DefaultHasher::new();
71-
OUT_DIR.hash(&mut hasher);
69+
NOTE: rustc must be run by Cargo."#,
70+
))
71+
})
72+
}
73+
74+
pub fn file_hash() -> u64 {
75+
*FILE_HASH_LOCK.get_or_init(|| {
76+
let mut hasher = DefaultHasher::new();
77+
out_dir().hash(&mut hasher);
7278
hasher.finish()
73-
};
79+
})
7480
}
7581

7682
#[derive(Clone, Debug, Hash, PartialEq, Eq)]

cpp_macros/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ docs-only = []
2020
proc-macro = true
2121

2222
[dependencies]
23-
lazy_static = "1.0"
2423
cpp_common = { path = "../cpp_common", version = "=0.5.10" }
2524
syn = { version = "2.0", features=["full", "visit"] }
2625
quote = "1.0"

cpp_macros/src/lib.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ extern crate syn;
1010
extern crate proc_macro;
1111
use proc_macro2::Span;
1212

13-
use cpp_common::{flags, kw, RustInvocation, FILE_HASH, LIB_NAME, MSVC_LIB_NAME, OUT_DIR, VERSION};
13+
use cpp_common::{file_hash, flags, kw, out_dir, RustInvocation, LIB_NAME, MSVC_LIB_NAME, VERSION};
1414
use std::collections::HashMap;
1515
use std::iter::FromIterator;
16+
use std::sync::OnceLock;
1617
use syn::parse::Parser;
1718
use syn::Ident;
1819

1920
use byteorder::{BigEndian, ByteOrder, LittleEndian, ReadBytesExt};
20-
use lazy_static::lazy_static;
2121
use quote::{quote, quote_spanned};
2222
use std::fs::File;
2323
use std::io::{self, BufReader, Read, Seek, SeekFrom};
@@ -33,8 +33,10 @@ impl MetaData {
3333
}
3434
}
3535

36-
lazy_static! {
37-
static ref METADATA: HashMap<u64, Vec<MetaData>> = {
36+
static METADATA_LOCK: OnceLock<HashMap<u64, Vec<MetaData>>> = OnceLock::new();
37+
38+
fn metadata() -> &'static HashMap<u64, Vec<MetaData>> {
39+
METADATA_LOCK.get_or_init(|| {
3840
let file = match open_lib_file() {
3941
Ok(x) => x,
4042
Err(e) => {
@@ -62,7 +64,7 @@ NOTE: Did you make sure to add the rust-cpp build script?
6264
6365
I/O error while reading metadata from target library file."#,
6466
)
65-
};
67+
})
6668
}
6769

6870
/// NOTE: This panics when it can produce a better error message
@@ -126,10 +128,10 @@ fn read_metadata_rest<E: ByteOrder>(
126128
/// metadata. We check both `MSVC_LIB_NAME` and `LIB_NAME`, in case we are on
127129
/// or are targeting Windows.
128130
fn open_lib_file() -> io::Result<File> {
129-
if let Ok(file) = File::open(OUT_DIR.join(MSVC_LIB_NAME)) {
131+
if let Ok(file) = File::open(out_dir().join(MSVC_LIB_NAME)) {
130132
Ok(file)
131133
} else {
132-
File::open(OUT_DIR.join(LIB_NAME))
134+
File::open(out_dir().join(LIB_NAME))
133135
}
134136
}
135137

@@ -195,7 +197,7 @@ pub fn expand_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
195197
};
196198

197199
// Get the size data compiled by the build macro
198-
let size_data = match METADATA.get(&closure.sig.name_hash()) {
200+
let size_data = match metadata().get(&closure.sig.name_hash()) {
199201
Some(x) => x,
200202
None => {
201203
#[cfg(not(feature = "docs-only"))]
@@ -314,7 +316,7 @@ NOTE: They cannot be generated by macro expansion."#})
314316
let rust_invocations = find_all_rust_macro.parse2(input).expect("rust! macro");
315317
let init_callbacks = if !rust_invocations.is_empty() {
316318
let rust_cpp_callbacks =
317-
Ident::new(&format!("rust_cpp_callbacks{}", *FILE_HASH), Span::call_site());
319+
Ident::new(&format!("rust_cpp_callbacks{}", file_hash()), Span::call_site());
318320
let offset = (flags >> 32) as isize;
319321
let callbacks: Vec<Ident> = rust_invocations.iter().map(|x| x.id.clone()).collect();
320322
quote! {
@@ -370,7 +372,7 @@ pub fn expand_wrap_class(input: proc_macro::TokenStream) -> proc_macro::TokenStr
370372
let class_name = class.name.clone();
371373

372374
// Get the size data compiled by the build macro
373-
let size_data = match METADATA.get(&hash) {
375+
let size_data = match metadata().get(&hash) {
374376
Some(x) => x,
375377
None => {
376378
#[cfg(not(feature = "docs-only"))]

0 commit comments

Comments
 (0)