From 99d1311d63184dd0b6064e8640b7831c8c17416f Mon Sep 17 00:00:00 2001 From: oxalica Date: Tue, 3 Sep 2024 16:01:12 -0400 Subject: [PATCH] Avoid unnecessary unwrap --- Cargo.lock | 49 +++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + blahd/Cargo.toml | 1 + blahd/src/config.rs | 2 +- blahd/src/database.rs | 4 ++-- blahd/src/event.rs | 14 ++++++------- blahd/src/main.rs | 18 +++++++--------- clippy.toml | 1 + src/types.rs | 4 ++-- 9 files changed, 72 insertions(+), 22 deletions(-) create mode 100644 clippy.toml diff --git a/Cargo.lock b/Cargo.lock index a8d0ee3..b62a7e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -291,6 +291,7 @@ dependencies = [ "futures-util", "hex", "humantime", + "parking_lot", "rusqlite", "sd-notify", "serde", @@ -941,6 +942,16 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + [[package]] name = "log" version = "0.4.22" @@ -1078,6 +1089,29 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -1198,6 +1232,15 @@ dependencies = [ "getrandom", ] +[[package]] +name = "redox_syscall" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +dependencies = [ + "bitflags", +] + [[package]] name = "reqwest" version = "0.12.7" @@ -1366,6 +1409,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "sd-notify" version = "0.4.2" diff --git a/Cargo.toml b/Cargo.toml index 5cfd42f..037ed92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ dbg_macro = "warn" print_stderr = "warn" print_stdout = "warn" todo = "warn" +unwrap_used = "warn" [package] name = "blah" diff --git a/blahd/Cargo.toml b/blahd/Cargo.toml index b273a3a..62ff783 100644 --- a/blahd/Cargo.toml +++ b/blahd/Cargo.toml @@ -13,6 +13,7 @@ ed25519-dalek = "2" futures-util = "0.3" hex = { version = "0.4", features = ["serde"] } humantime = "2" +parking_lot = "0.12" # Maybe no better performance, just that we hate poisoning. ¯\_(ツ)_/¯ rusqlite = { version = "0.32", features = ["uuid"] } sd-notify = "0.4" serde = { version = "1", features = ["derive"] } diff --git a/blahd/src/config.rs b/blahd/src/config.rs index 0758688..6d1dec9 100644 --- a/blahd/src/config.rs +++ b/blahd/src/config.rs @@ -31,7 +31,7 @@ pub struct ServerConfig { pub listen: String, pub base_url: Url, - #[serde_inline_default(1024.try_into().unwrap())] + #[serde_inline_default(1024.try_into().expect("not zero"))] pub max_page_len: NonZeroUsize, #[serde_inline_default(4096)] // 4KiB pub max_request_len: usize, diff --git a/blahd/src/database.rs b/blahd/src/database.rs index 2ae8a5a..2e7ab1d 100644 --- a/blahd/src/database.rs +++ b/blahd/src/database.rs @@ -1,7 +1,7 @@ use std::ops::DerefMut; -use std::sync::Mutex; use anyhow::{ensure, Context, Result}; +use parking_lot::Mutex; use rusqlite::{params, Connection, OpenFlags}; use crate::config::DatabaseConfig; @@ -57,7 +57,7 @@ impl Database { } pub fn get(&self) -> impl DerefMut + '_ { - self.conn.lock().unwrap() + self.conn.lock() } } diff --git a/blahd/src/event.rs b/blahd/src/event.rs index a0ac9b1..b1be384 100644 --- a/blahd/src/event.rs +++ b/blahd/src/event.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::convert::Infallible; use std::fmt; use std::pin::Pin; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::task::{Context, Poll}; use anyhow::{bail, Context as _, Result}; @@ -12,6 +12,7 @@ use blah::types::{AuthPayload, ChatItem, WithSig}; use futures_util::future::Either; use futures_util::stream::SplitSink; use futures_util::{stream_select, SinkExt as _, Stream, StreamExt}; +use parking_lot::Mutex; use rusqlite::{params, OptionalExtension}; use serde::{Deserialize, Serialize}; use tokio::sync::broadcast; @@ -81,11 +82,10 @@ struct UserEventReceiver { impl Drop for UserEventReceiver { fn drop(&mut self) { tracing::debug!(%self.uid, "user disconnected"); - if let Ok(mut map) = self.st.event.user_listeners.lock() { - if let Some(tx) = map.get_mut(&self.uid) { - if tx.receiver_count() == 1 { - map.remove(&self.uid); - } + let mut map = self.st.event.user_listeners.lock(); + if let Some(tx) = map.get_mut(&self.uid) { + if tx.receiver_count() == 1 { + map.remove(&self.uid); } } } @@ -133,7 +133,7 @@ pub async fn handle_ws(st: Arc, ws: &mut WebSocket) -> Result ent.get().subscribe(), Entry::Vacant(ent) => { let (tx, rx) = broadcast::channel(st.config.server.ws_event_queue_len); diff --git a/blahd/src/main.rs b/blahd/src/main.rs index 666bdb2..75079ef 100644 --- a/blahd/src/main.rs +++ b/blahd/src/main.rs @@ -1,6 +1,6 @@ use std::num::NonZeroUsize; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::{Duration, SystemTime}; use anyhow::{Context, Result}; @@ -19,6 +19,7 @@ use config::Config; use database::Database; use ed25519_dalek::SIGNATURE_LENGTH; use middleware::{ApiError, OptionalAuth, SignedJson}; +use parking_lot::Mutex; use rusqlite::{named_params, params, Connection, OptionalExtension, Row, ToSql}; use serde::{Deserialize, Serialize}; use url::Url; @@ -122,12 +123,7 @@ impl AppState { "invalid timestamp, off by {timestamp_diff}s" )); } - if !self - .used_nonces - .lock() - .unwrap() - .try_insert(data.signee.nonce) - { + if !self.used_nonces.lock().try_insert(data.signee.nonce) { return Err(error_response!( StatusCode::BAD_REQUEST, "duplicated_nonce", @@ -425,7 +421,7 @@ struct Pagination { impl Pagination { fn effective_page_len(&self, st: &AppState) -> usize { self.top - .unwrap_or(usize::MAX.try_into().unwrap()) + .unwrap_or(usize::MAX.try_into().expect("not zero")) .min(st.config.server.max_page_len) .get() } @@ -524,7 +520,9 @@ async fn room_get_feed( { let mut query = next_url.query_pairs_mut(); let ser = serde_urlencoded::Serializer::new(&mut query); - next_params.serialize(ser).unwrap(); + next_params + .serialize(ser) + .expect("serialization cannot fail"); query.finish(); } next_url @@ -737,7 +735,7 @@ async fn room_post_item( WHERE `rid` = :rid ", )?; - let listeners = st.event.user_listeners.lock().unwrap(); + let listeners = st.event.user_listeners.lock(); let txs = stmt .query_map(params![rid], |row| row.get::<_, u64>(0))? .filter_map(|ret| match ret { diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..154626e --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +allow-unwrap-in-tests = true diff --git a/src/types.rs b/src/types.rs index 349f9e5..9a4222d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -18,8 +18,8 @@ pub struct UserKey(#[serde(with = "hex::serde")] pub [u8; PUBLIC_KEY_LENGTH]); impl fmt::Display for UserKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut buf = [0u8; PUBLIC_KEY_LENGTH * 2]; - hex::encode_to_slice(self.0, &mut buf).unwrap(); - f.write_str(std::str::from_utf8(&buf).unwrap()) + hex::encode_to_slice(self.0, &mut buf).expect("buf size is correct"); + f.write_str(std::str::from_utf8(&buf).expect("hex must be UTF-8")) } }