Skip to content

Commit

Permalink
refactor: remove lazy_static crate
Browse files Browse the repository at this point in the history
The `lazy_static` crate was superseded by the `once_cell` crate which
has been included in Rust's standard library since version `1.70`.
Remove the `lazy_static` dependency and refactor all use cases to use
`std::sync::OnceLock` instead.

Co-authored-by: Henrik Friedrichsen <[email protected]>
  • Loading branch information
ThomasFrans and hrkfdn authored Oct 7, 2023
1 parent 2f365c1 commit 209d8e2
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 28 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ zbus = {version = "3.11.1", default-features = false, features = ["tokio"], opti
fern = "0.6"
futures = "0.3"
ioctl-rs = {version = "0.2", optional = true}
lazy_static = "1.3.0"
libc = "0.2.142"
librespot-core = "0.4.2"
librespot-playback = "0.4.2"
Expand Down
22 changes: 13 additions & 9 deletions src/application.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};

use cursive::traits::Nameable;
use cursive::{Cursive, CursiveRunner};
Expand Down Expand Up @@ -55,13 +55,8 @@ pub struct UserDataInner {
pub cmd: CommandManager,
}

lazy_static!(
/// The global Tokio runtime for running asynchronous tasks.
pub static ref ASYNC_RUNTIME: tokio::runtime::Runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
);
/// The global Tokio runtime for running asynchronous tasks.
pub static ASYNC_RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();

/// The representation of an ncspot application.
pub struct Application {
Expand Down Expand Up @@ -91,6 +86,15 @@ impl Application {
// Things here may cause the process to abort; we must do them before creating curses
// windows otherwise the error message will not be seen by a user

ASYNC_RUNTIME
.set(
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap(),
)
.unwrap();

let configuration = Arc::new(Config::new(configuration_file_path));
let credentials = authentication::get_credentials(&configuration)?;
let theme = configuration.build_theme();
Expand Down Expand Up @@ -134,7 +138,7 @@ impl Application {

#[cfg(unix)]
let ipc = ipc::IpcSocket::new(
ASYNC_RUNTIME.handle(),
ASYNC_RUNTIME.get().unwrap().handle(),
crate::config::cache_path("ncspot.sock"),
event_manager.clone(),
)
Expand Down
16 changes: 9 additions & 7 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::queue::RepeatSetting;
use crate::spotify_url::SpotifyUrl;
use std::collections::HashMap;
use std::fmt;
use std::sync::OnceLock;

use strum_macros::Display;

Expand Down Expand Up @@ -291,8 +292,12 @@ fn register_aliases(map: &mut HashMap<&str, &str>, cmd: &'static str, names: Vec
}
}

lazy_static! {
static ref ALIASES: HashMap<&'static str, &'static str> = {
fn handle_aliases(input: &str) -> &str {
// NOTE: There is probably a better way to write this than a static HashMap. The HashMap doesn't
// improve performance as there's far too few keys, and the use of static doesn't seem good.
static ALIASES: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();

let aliases = ALIASES.get_or_init(|| {
let mut m = HashMap::new();

register_aliases(&mut m, "quit", vec!["q", "x"]);
Expand All @@ -302,13 +307,10 @@ lazy_static! {
vec!["pause", "toggleplay", "toggleplayback"],
);
register_aliases(&mut m, "repeat", vec!["loop"]);

m
};
}
});

fn handle_aliases(input: &str) -> &str {
if let Some(cmd) = ALIASES.get(input) {
if let Some(cmd) = aliases.get(input) {
handle_aliases(cmd)
} else {
input
Expand Down
6 changes: 2 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,8 @@ impl Default for UserState {
}
}

lazy_static! {
/// Configuration files are read/written relative to this directory.
pub static ref BASE_PATH: RwLock<Option<PathBuf>> = RwLock::new(None);
}
/// Configuration files are read/written relative to this directory.
static BASE_PATH: RwLock<Option<PathBuf>> = RwLock::new(None);

/// The complete configuration (state + user configuration) of ncspot.
pub struct Config {
Expand Down
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
#[macro_use]
extern crate cursive;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde;

use std::path::PathBuf;
Expand Down
2 changes: 1 addition & 1 deletion src/mpris.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ impl MprisManager {

let (tx, rx) = mpsc::unbounded_channel::<()>();

ASYNC_RUNTIME.spawn(async {
ASYNC_RUNTIME.get().unwrap().spawn(async {
let result = Self::serve(UnboundedReceiverStream::new(rx), root, player).await;
if let Err(e) = result {
log::error!("MPRIS error: {e}");
Expand Down
6 changes: 4 additions & 2 deletions src/spotify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Spotify {

let (user_tx, user_rx) = oneshot::channel();
spotify.start_worker(Some(user_tx));
spotify.user = ASYNC_RUNTIME.block_on(user_rx).ok();
spotify.user = ASYNC_RUNTIME.get().unwrap().block_on(user_rx).ok();
let volume = cfg.state().volume;
spotify.set_volume(volume);

Expand All @@ -95,7 +95,7 @@ impl Spotify {
let events = self.events.clone();
let volume = self.volume();
let credentials = self.credentials.clone();
ASYNC_RUNTIME.spawn(Self::worker(
ASYNC_RUNTIME.get().unwrap().spawn(Self::worker(
worker_channel,
events,
rx,
Expand All @@ -122,6 +122,8 @@ impl Spotify {
pub fn test_credentials(credentials: Credentials) -> Result<Session, SessionError> {
let config = Self::session_config();
ASYNC_RUNTIME
.get()
.unwrap()
.block_on(Session::connect(config, credentials, None, true))
.map(|r| r.0)
}
Expand Down
2 changes: 1 addition & 1 deletion src/spotify_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl WebApi {
.as_ref()
{
channel.send(cmd).expect("can't send message to worker");
let token_option = ASYNC_RUNTIME.block_on(token_rx).unwrap();
let token_option = ASYNC_RUNTIME.get().unwrap().block_on(token_rx).unwrap();
if let Some(token) = token_option {
*self.api.token.lock().expect("can't writelock api token") = Some(Token {
access_token: token.access_token,
Expand Down

0 comments on commit 209d8e2

Please sign in to comment.