Skip to content

Commit 9644d4c

Browse files
authored
chore: move lazy_static to once_cell (#1022)
1 parent ec97288 commit 9644d4c

File tree

22 files changed

+255
-269
lines changed

22 files changed

+255
-269
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ futures-util = { version = "0.3.14", features = ["io"] }
103103
futures-executor = "0.3.14"
104104
hex = "0.4.0"
105105
hmac = "0.12.1"
106-
lazy_static = "1.4.0"
106+
once_cell = "1.19.0"
107107
log = { version = "0.4.17", optional = true }
108108
md-5 = "0.10.1"
109109
mongocrypt = { git = "https://github.com/mongodb/libmongocrypt-rust.git", branch = "main", optional = true }

benchmarks/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ async-std-runtime = ["async-std", "mongodb/async-std-runtime"]
1919
[dependencies]
2020
mongodb = { path = "..", default-features = false }
2121
serde_json = "1.0.59"
22-
lazy_static = "1.4.0"
22+
once_cell = "1.19.0"
2323
clap = "2.33.3"
2424
indicatif = "0.15.0"
2525
async-trait = "0.1.41"

benchmarks/src/bench.rs

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,34 +21,41 @@ use std::{
2121
use anyhow::{bail, Result};
2222
use futures::stream::TryStreamExt;
2323
use indicatif::{ProgressBar, ProgressStyle};
24-
use lazy_static::lazy_static;
2524
use mongodb::{
2625
bson::{doc, Bson, Document},
2726
options::{Acknowledgment, ClientOptions, SelectionCriteria, WriteConcern},
2827
Client,
2928
};
29+
use once_cell::sync::Lazy;
3030
use serde_json::Value;
3131

3232
use crate::fs::{BufReader, File};
3333

34-
lazy_static! {
35-
static ref DATABASE_NAME: String = option_env!("DATABASE_NAME")
34+
static DATABASE_NAME: Lazy<String> = Lazy::new(|| {
35+
option_env!("DATABASE_NAME")
3636
.unwrap_or("perftest")
37-
.to_string();
38-
static ref COLL_NAME: String = option_env!("COLL_NAME").unwrap_or("corpus").to_string();
39-
static ref MAX_EXECUTION_TIME: u64 = option_env!("MAX_EXECUTION_TIME")
37+
.to_string()
38+
});
39+
static COLL_NAME: Lazy<String> =
40+
Lazy::new(|| option_env!("COLL_NAME").unwrap_or("corpus").to_string());
41+
static MAX_EXECUTION_TIME: Lazy<u64> = Lazy::new(|| {
42+
option_env!("MAX_EXECUTION_TIME")
4043
.unwrap_or("300")
4144
.parse::<u64>()
42-
.expect("invalid MAX_EXECUTION_TIME");
43-
static ref MIN_EXECUTION_TIME: u64 = option_env!("MIN_EXECUTION_TIME")
45+
.expect("invalid MAX_EXECUTION_TIME")
46+
});
47+
static MIN_EXECUTION_TIME: Lazy<u64> = Lazy::new(|| {
48+
option_env!("MIN_EXECUTION_TIME")
4449
.unwrap_or("60")
4550
.parse::<u64>()
46-
.expect("invalid MIN_EXECUTION_TIME");
47-
pub static ref TARGET_ITERATION_COUNT: usize = option_env!("TARGET_ITERATION_COUNT")
51+
.expect("invalid MIN_EXECUTION_TIME")
52+
});
53+
pub static TARGET_ITERATION_COUNT: Lazy<usize> = Lazy::new(|| {
54+
option_env!("TARGET_ITERATION_COUNT")
4855
.unwrap_or("100")
4956
.parse::<usize>()
50-
.expect("invalid TARGET_ITERATION_COUNT");
51-
}
57+
.expect("invalid TARGET_ITERATION_COUNT")
58+
});
5259

5360
#[async_trait::async_trait]
5461
pub trait Benchmark: Sized {
@@ -145,13 +152,13 @@ pub async fn drop_database(uri: &str, database: &str) -> Result<()> {
145152
.run_command(doc! { "hello": true }, None)
146153
.await?;
147154

148-
client.database(&database).drop(None).await?;
155+
client.database(&database).drop().await?;
149156

150157
// in sharded clusters, take additional steps to ensure database is dropped completely.
151158
// see: https://www.mongodb.com/docs/manual/reference/method/db.dropDatabase/#replica-set-and-sharded-clusters
152159
let is_sharded = hello.get_str("msg").ok() == Some("isdbgrid");
153160
if is_sharded {
154-
client.database(&database).drop(None).await?;
161+
client.database(&database).drop().await?;
155162
for host in options.hosts {
156163
client
157164
.database("admin")

benchmarks/src/bench/gridfs_multi_download.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,16 @@ use std::{
55

66
use anyhow::{Context, Result};
77
use futures::AsyncWriteExt;
8-
use lazy_static::lazy_static;
98
use mongodb::{bson::oid::ObjectId, gridfs::GridFsBucket, Client};
9+
use once_cell::sync::Lazy;
1010

1111
use crate::{
1212
bench::{drop_database, Benchmark, DATABASE_NAME},
1313
fs::{open_async_read_compat, open_async_write_compat},
1414
};
1515

16-
lazy_static! {
17-
static ref DOWNLOAD_PATH: PathBuf =
18-
Path::new(env!("CARGO_MANIFEST_DIR")).join("gridfs_multi_download");
19-
}
16+
static DOWNLOAD_PATH: Lazy<PathBuf> =
17+
Lazy::new(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("gridfs_multi_download"));
2018

2119
pub struct GridFsMultiDownloadBenchmark {
2220
uri: String,

benchmarks/src/main.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ use clap::{App, Arg, ArgMatches};
4646
use futures::Future;
4747
#[cfg(feature = "tokio-runtime")]
4848
use futures::FutureExt;
49-
use lazy_static::lazy_static;
5049
use mongodb::options::ClientOptions;
50+
use once_cell::sync::Lazy;
5151

5252
use crate::{
5353
bench::{
@@ -69,9 +69,7 @@ use crate::{
6969
score::{score_test, BenchmarkResult, CompositeScore},
7070
};
7171

72-
lazy_static! {
73-
static ref DATA_PATH: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")).join("data");
74-
}
72+
static DATA_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("data"));
7573

7674
// benchmark names
7775
const FLAT_BSON_ENCODING: &'static str = "Flat BSON Encoding";

src/client/auth/aws.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::{fs::File, io::Read, time::Duration};
22

33
use chrono::{offset::Utc, DateTime};
44
use hmac::Hmac;
5-
use lazy_static::lazy_static;
5+
use once_cell::sync::Lazy;
66
use rand::distributions::{Alphanumeric, DistString};
77
use serde::Deserialize;
88
use sha2::{Digest, Sha256};
@@ -30,9 +30,7 @@ const AWS_EC2_IP: &str = "169.254.169.254";
3030
const AWS_LONG_DATE_FMT: &str = "%Y%m%dT%H%M%SZ";
3131
const MECH_NAME: &str = "MONGODB-AWS";
3232

33-
lazy_static! {
34-
static ref CACHED_CREDENTIAL: Mutex<Option<AwsCredential>> = Mutex::new(None);
35-
}
33+
static CACHED_CREDENTIAL: Lazy<Mutex<Option<AwsCredential>>> = Lazy::new(|| Mutex::new(None));
3634

3735
/// Performs MONGODB-AWS authentication for a given stream.
3836
pub(super) async fn authenticate_stream(

src/client/auth/scram.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ use hmac::{
1111
Hmac,
1212
Mac,
1313
};
14-
use lazy_static::lazy_static;
1514
use md5::Md5;
15+
use once_cell::sync::Lazy;
1616
use sha1::Sha1;
1717
use sha2::Sha256;
1818
use tokio::sync::RwLock;
1919

2020
use crate::{
21-
bson::{doc, Bson, Document},
21+
bson::{Bson, Document},
2222
client::{
2323
auth::{
2424
self,
@@ -48,12 +48,9 @@ const NO_CHANNEL_BINDING: char = 'n';
4848
/// The minimum number of iterations of the hash function that we will accept from the server.
4949
const MIN_ITERATION_COUNT: u32 = 4096;
5050

51-
lazy_static! {
52-
/// Cache of pre-computed salted passwords.
53-
static ref CREDENTIAL_CACHE: RwLock<HashMap<CacheEntry, Vec<u8>>> = {
54-
RwLock::new(HashMap::new())
55-
};
56-
}
51+
/// Cache of pre-computed salted passwords.
52+
static CREDENTIAL_CACHE: Lazy<RwLock<HashMap<CacheEntry, Vec<u8>>>> =
53+
Lazy::new(|| RwLock::new(HashMap::new()));
5754

5855
#[derive(Hash, Eq, PartialEq)]
5956
struct CacheEntry {

src/client/auth/test.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
use lazy_static::lazy_static;
1+
use once_cell::sync::Lazy;
22

33
use crate::{cmap::StreamDescription, options::AuthMechanism};
44

55
use super::sasl::SaslStart;
66

7-
lazy_static! {
8-
static ref MECHS: [String; 2] = [
7+
static MECHS: Lazy<[String; 2]> = Lazy::new(|| {
8+
[
99
AuthMechanism::ScramSha1.as_str().to_string(),
10-
AuthMechanism::ScramSha256.as_str().to_string()
11-
];
12-
}
10+
AuthMechanism::ScramSha256.as_str().to_string(),
11+
]
12+
});
1313

1414
#[test]
1515
fn negotiate_both_scram() {

src/client/executor.rs

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use bson::RawDocumentBuf;
33
use bson::{doc, RawBsonRef, RawDocument, Timestamp};
44
#[cfg(feature = "in-use-encryption-unstable")]
55
use futures_core::future::BoxFuture;
6-
use lazy_static::lazy_static;
6+
use once_cell::sync::Lazy;
77
use serde::de::DeserializeOwned;
88

99
use std::{
@@ -63,27 +63,25 @@ use crate::{
6363
ClusterTime,
6464
};
6565

66-
lazy_static! {
67-
pub(crate) static ref REDACTED_COMMANDS: HashSet<&'static str> = {
68-
let mut hash_set = HashSet::new();
69-
hash_set.insert("authenticate");
70-
hash_set.insert("saslstart");
71-
hash_set.insert("saslcontinue");
72-
hash_set.insert("getnonce");
73-
hash_set.insert("createuser");
74-
hash_set.insert("updateuser");
75-
hash_set.insert("copydbgetnonce");
76-
hash_set.insert("copydbsaslstart");
77-
hash_set.insert("copydb");
78-
hash_set
79-
};
80-
pub(crate) static ref HELLO_COMMAND_NAMES: HashSet<&'static str> = {
81-
let mut hash_set = HashSet::new();
82-
hash_set.insert("hello");
83-
hash_set.insert(LEGACY_HELLO_COMMAND_NAME_LOWERCASE);
84-
hash_set
85-
};
86-
}
66+
pub(crate) static REDACTED_COMMANDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
67+
let mut hash_set = HashSet::new();
68+
hash_set.insert("authenticate");
69+
hash_set.insert("saslstart");
70+
hash_set.insert("saslcontinue");
71+
hash_set.insert("getnonce");
72+
hash_set.insert("createuser");
73+
hash_set.insert("updateuser");
74+
hash_set.insert("copydbgetnonce");
75+
hash_set.insert("copydbsaslstart");
76+
hash_set.insert("copydb");
77+
hash_set
78+
});
79+
pub(crate) static HELLO_COMMAND_NAMES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
80+
let mut hash_set = HashSet::new();
81+
hash_set.insert("hello");
82+
hash_set.insert(LEGACY_HELLO_COMMAND_NAME_LOWERCASE);
83+
hash_set
84+
});
8785

8886
impl Client {
8987
/// Execute the given operation.

src/client/options.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use std::{
1717

1818
use bson::UuidRepresentation;
1919
use derivative::Derivative;
20-
use lazy_static::lazy_static;
20+
use once_cell::sync::Lazy;
2121
use serde::{de::Unexpected, Deserialize, Deserializer, Serialize};
2222
use serde_with::skip_serializing_none;
2323
use strsim::jaro_winkler;
@@ -83,18 +83,14 @@ const URI_OPTIONS: &[&str] = &[
8383
"zlibcompressionlevel",
8484
];
8585

86-
lazy_static! {
87-
/// Reserved characters as defined by [Section 2.2 of RFC-3986](https://tools.ietf.org/html/rfc3986#section-2.2).
88-
/// Usernames / passwords that contain these characters must instead include the URL encoded version of them when included
89-
/// as part of the connection string.
90-
static ref USERINFO_RESERVED_CHARACTERS: HashSet<&'static char> = {
91-
[':', '/', '?', '#', '[', ']', '@'].iter().collect()
92-
};
86+
/// Reserved characters as defined by [Section 2.2 of RFC-3986](https://tools.ietf.org/html/rfc3986#section-2.2).
87+
/// Usernames / passwords that contain these characters must instead include the URL encoded version
88+
/// of them when included as part of the connection string.
89+
static USERINFO_RESERVED_CHARACTERS: Lazy<HashSet<&'static char>> =
90+
Lazy::new(|| [':', '/', '?', '#', '[', ']', '@'].iter().collect());
9391

94-
static ref ILLEGAL_DATABASE_CHARACTERS: HashSet<&'static char> = {
95-
['/', '\\', ' ', '"', '$'].iter().collect()
96-
};
97-
}
92+
static ILLEGAL_DATABASE_CHARACTERS: Lazy<HashSet<&'static char>> =
93+
Lazy::new(|| ['/', '\\', ' ', '"', '$'].iter().collect());
9894

9995
/// An enum representing the address of a MongoDB server.
10096
#[derive(Clone, Debug, Eq, Serialize)]

0 commit comments

Comments
 (0)