fix more clippy lints (part 1)

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-01-14 22:39:08 -05:00 committed by June
parent 44440f745f
commit 59c7f93656
19 changed files with 77 additions and 80 deletions

View file

@ -188,47 +188,52 @@ codegen-units=1
workspace = true workspace = true
[workspace.lints.rust] [workspace.lints.rust]
# missing_abi = "warn" missing_abi = "warn"
# missing_docs = "warn" # missing_docs = "warn"
# noop_method_call = "warn" noop_method_call = "warn"
# pointer_structural_match = "warn" pointer_structural_match = "warn"
# unreachable_pub = "warn" # unreachable_pub = "warn"
# unused_extern_crates = "warn" unused_extern_crates = "warn"
# unused_import_braces = "warn" unused_import_braces = "warn"
# unused_lifetimes = "warn" # unused_lifetimes = "warn"
unused_qualifications = "warn" unused_qualifications = "warn"
# unused_tuple_struct_fields = "warn" unused_tuple_struct_fields = "warn"
[workspace.lints.clippy] [workspace.lints.clippy]
suspicious = "warn" # assume deny in practice suspicious = "warn" # assume deny in practice
perf = "warn" # assume deny in practice perf = "warn" # assume deny in practice
# redundant_clone = "warn" redundant_clone = "warn"
# cloned_instead_of_copied = "warn" cloned_instead_of_copied = "warn"
expl_impl_clone_on_copy = "warn" expl_impl_clone_on_copy = "warn"
# pedantic = "warn" # pedantic = "warn"
# as_conversions = "warn" unnecessary_cast = "warn"
cast_lossless = "warn"
ptr_as_ptr = "warn"
ref_to_mut = "warn"
char_lit_as_u8 = "warn"
dbg_macro = "warn" dbg_macro = "warn"
# empty_structs_with_brackets = "warn" empty_structs_with_brackets = "warn"
# get_unwrap = "warn" # get_unwrap = "warn"
# if_then_some_else_none = "warn" # if_then_some_else_none = "warn"
# let_underscore_must_use = "warn" # let_underscore_must_use = "warn"
# map_err_ignore = "warn" # map_err_ignore = "warn"
# missing_docs_in_private_items = "warn" # missing_docs_in_private_items = "warn"
# negative_feature_names = "warn" negative_feature_names = "warn"
# pub_without_shorthand = "warn" pub_without_shorthand = "warn"
rc_buffer = "warn" rc_buffer = "warn"
rc_mutex = "warn" rc_mutex = "warn"
# redundant_feature_names = "warn" redundant_feature_names = "warn"
# redundant_type_annotations = "warn" redundant_type_annotations = "warn"
# ref_patterns = "warn" # ref_patterns = "warn"
# rest_pat_in_fully_bound_structs = "warn" rest_pat_in_fully_bound_structs = "warn"
# str_to_string = "warn" str_to_string = "warn"
# string_add = "warn" # string_add = "warn"
# string_slice = "warn" # string_slice = "warn"
# string_to_string = "warn" # string_to_string = "warn"
tests_outside_test_module = "warn" tests_outside_test_module = "warn"
undocumented_unsafe_blocks = "warn" undocumented_unsafe_blocks = "warn"
# unneeded_field_pattern = "warn" unneeded_field_pattern = "warn"
# unseparated_literal_suffix = "warn" unseparated_literal_suffix = "warn"
# unwrap_used = "warn" # unwrap_used = "warn"
# wildcard_dependencies = "warn" # expect_used = "warn"
wildcard_dependencies = "warn"

View file

@ -132,9 +132,7 @@ pub async fn get_content_as_filename_route(
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta { if let Some(FileMeta {
content_disposition: _, content_type, file, ..
content_type,
file,
}) = services().media.get(mxc.clone()).await? }) = services().media.get(mxc.clone()).await?
{ {
Ok(get_content_as_filename::v3::Response { Ok(get_content_as_filename::v3::Response {

View file

@ -1221,7 +1221,7 @@ fn validate_and_add_event_id(
Ok((event_id, value)) Ok((event_id, value))
} }
pub(crate) async fn invite_helper<'a>( pub(crate) async fn invite_helper(
sender_user: &UserId, sender_user: &UserId,
user_id: &UserId, user_id: &UserId,
room_id: &RoomId, room_id: &RoomId,

View file

@ -41,7 +41,7 @@ pub async fn report_event_route(
services().admin services().admin
.send_message(message::RoomMessageEventContent::text_html( .send_message(message::RoomMessageEventContent::text_html(
format!( format!(
"Report received from: {}\n\n\ "@room Report received from: {}\n\n\
Event ID: {:?}\n\ Event ID: {:?}\n\
Room ID: {:?}\n\ Room ID: {:?}\n\
Sent By: {:?}\n\n\ Sent By: {:?}\n\n\

View file

@ -95,7 +95,7 @@ impl FedDest {
fn into_uri_string(self) -> String { fn into_uri_string(self) -> String {
match self { match self {
Self::Literal(addr) => addr.to_string(), Self::Literal(addr) => addr.to_string(),
Self::Named(host, ref port) => host + port, Self::Named(host, port) => host + &port,
} }
} }

View file

@ -218,10 +218,7 @@ impl fmt::Display for Config {
"Allow device name federation", "Allow device name federation",
&self.allow_device_name_federation.to_string(), &self.allow_device_name_federation.to_string(),
), ),
( ("Notification push path", &self.notification_push_path),
"Notification push path",
&self.notification_push_path.to_string(),
),
("Allow room creation", &self.allow_room_creation.to_string()), ("Allow room creation", &self.allow_room_creation.to_string()),
( (
"Allow public room directory over federation", "Allow public room directory over federation",
@ -280,10 +277,7 @@ impl fmt::Display for Config {
"zstd Response Body Compression", "zstd Response Body Compression",
&self.zstd_compression.to_string(), &self.zstd_compression.to_string(),
), ),
( ("RocksDB database log level", &self.rocksdb_log_level),
"RocksDB database log level",
&self.rocksdb_log_level.to_string(),
),
( (
"RocksDB database log time-to-roll", "RocksDB database log time-to-roll",
&self.rocksdb_log_time_to_roll.to_string(), &self.rocksdb_log_time_to_roll.to_string(),
@ -393,11 +387,11 @@ fn default_rocksdb_log_time_to_roll() -> usize {
} }
// I know, it's a great name // I know, it's a great name
pub fn default_default_room_version() -> RoomVersionId { pub(crate) fn default_default_room_version() -> RoomVersionId {
RoomVersionId::V10 RoomVersionId::V10
} }
pub fn default_rocksdb_max_log_file_size() -> usize { fn default_rocksdb_max_log_file_size() -> usize {
// 4 megabytes // 4 megabytes
4 * 1024 * 1024 4 * 1024 * 1024
} }

View file

@ -95,20 +95,20 @@ impl PartialProxyConfig {
/// A domain name, that optionally allows a * as its first subdomain. /// A domain name, that optionally allows a * as its first subdomain.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum WildCardedDomain { enum WildCardedDomain {
WildCard, WildCard,
WildCarded(String), WildCarded(String),
Exact(String), Exact(String),
} }
impl WildCardedDomain { impl WildCardedDomain {
pub fn matches(&self, domain: &str) -> bool { fn matches(&self, domain: &str) -> bool {
match self { match self {
WildCardedDomain::WildCard => true, WildCardedDomain::WildCard => true,
WildCardedDomain::WildCarded(d) => domain.ends_with(d), WildCardedDomain::WildCarded(d) => domain.ends_with(d),
WildCardedDomain::Exact(d) => domain == d, WildCardedDomain::Exact(d) => domain == d,
} }
} }
pub fn more_specific_than(&self, other: &Self) -> bool { fn more_specific_than(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false, (WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false,
(_, WildCardedDomain::WildCard) => true, (_, WildCardedDomain::WildCard) => true,

View file

@ -7,12 +7,12 @@ use std::{future::Future, pin::Pin, sync::Arc};
pub mod sqlite; pub mod sqlite;
#[cfg(feature = "rocksdb")] #[cfg(feature = "rocksdb")]
pub mod rocksdb; pub(crate) mod rocksdb;
#[cfg(any(feature = "sqlite", feature = "rocksdb"))] #[cfg(any(feature = "sqlite", feature = "rocksdb"))]
pub mod watchers; pub(crate) mod watchers;
pub trait KeyValueDatabaseEngine: Send + Sync { pub(crate) trait KeyValueDatabaseEngine: Send + Sync {
fn open(config: &Config) -> Result<Self> fn open(config: &Config) -> Result<Self>
where where
Self: Sized; Self: Sized;
@ -27,7 +27,7 @@ pub trait KeyValueDatabaseEngine: Send + Sync {
fn clear_caches(&self) {} fn clear_caches(&self) {}
} }
pub trait KvTree: Send + Sync { pub(crate) trait KvTree: Send + Sync {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>; fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>; fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;

View file

@ -8,14 +8,14 @@ use std::{
use rocksdb::LogLevel::{Debug, Error, Fatal, Info, Warn}; use rocksdb::LogLevel::{Debug, Error, Fatal, Info, Warn};
pub struct Engine { pub(crate) struct Engine {
rocks: rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>, rocks: rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>,
cache: rocksdb::Cache, cache: rocksdb::Cache,
old_cfs: Vec<String>, old_cfs: Vec<String>,
config: Config, config: Config,
} }
pub struct RocksDbEngineTree<'a> { struct RocksDbEngineTree<'a> {
db: Arc<Engine>, db: Arc<Engine>,
name: &'a str, name: &'a str,
watchers: Watchers, watchers: Watchers,

View file

@ -11,8 +11,8 @@ use ruma::{
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
pub const COUNTER: &[u8] = b"c"; const COUNTER: &[u8] = b"c";
pub const LAST_CHECK_FOR_UPDATES_COUNT: &[u8] = b"u"; const LAST_CHECK_FOR_UPDATES_COUNT: &[u8] = b"u";
#[async_trait] #[async_trait]
impl service::globals::Data for KeyValueDatabase { impl service::globals::Data for KeyValueDatabase {

View file

@ -1,5 +1,5 @@
pub mod abstraction; pub(crate) mod abstraction;
pub mod key_value; pub(crate) mod key_value;
use crate::{ use crate::{
service::rooms::{edus::presence::presence_handler, timeline::PduCount}, service::rooms::{edus::presence::presence_handler, timeline::PduCount},
@ -1094,7 +1094,7 @@ impl KeyValueDatabase {
use tokio::time::Instant; use tokio::time::Instant;
let timer_interval = let timer_interval =
Duration::from_secs(services().globals.config.cleanup_second_interval as u64); Duration::from_secs(u64::from(services().globals.config.cleanup_second_interval));
fn perform_cleanup() { fn perform_cleanup() {
let start = Instant::now(); let start = Instant::now();

View file

@ -53,7 +53,7 @@ static GLOBAL: Jemalloc = Jemalloc;
#[derive(Parser)] #[derive(Parser)]
#[clap(version, about, long_about = None)] #[clap(version, about, long_about = None)]
struct Args {} struct Args;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {

View file

@ -1,6 +1,6 @@
mod data; mod data;
pub use data::Data; pub(crate) use data::Data;
use ruma::{ use ruma::{
events::{AnyEphemeralRoomEvent, RoomAccountDataEventType}, events::{AnyEphemeralRoomEvent, RoomAccountDataEventType},

View file

@ -1,6 +1,6 @@
mod data; mod data;
pub use data::Data; pub(crate) use data::Data;
use crate::Result; use crate::Result;

View file

@ -75,7 +75,7 @@ pub struct Service<'a> {
pub roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer pub roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer
pub roomid_federationhandletime: RwLock<HashMap<OwnedRoomId, (OwnedEventId, Instant)>>, pub roomid_federationhandletime: RwLock<HashMap<OwnedRoomId, (OwnedEventId, Instant)>>,
pub stateres_mutex: Arc<Mutex<()>>, pub stateres_mutex: Arc<Mutex<()>>,
pub rotate: RotationHandler, pub(crate) rotate: RotationHandler,
pub shutdown: AtomicBool, pub shutdown: AtomicBool,
pub argon: Argon2<'a>, pub argon: Argon2<'a>,
@ -84,12 +84,12 @@ pub struct Service<'a> {
/// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like. /// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like.
/// ///
/// This is utilized to have sync workers return early and release read locks on the database. /// This is utilized to have sync workers return early and release read locks on the database.
pub struct RotationHandler(broadcast::Sender<()>, broadcast::Receiver<()>); pub(crate) struct RotationHandler(broadcast::Sender<()>, ());
impl RotationHandler { impl RotationHandler {
pub fn new() -> Self { pub fn new() -> Self {
let (s, r) = broadcast::channel(1); let (s, _r) = broadcast::channel(1);
Self(s, r) Self(s, ())
} }
pub fn watch(&self) -> impl Future<Output = ()> { pub fn watch(&self) -> impl Future<Output = ()> {
@ -113,13 +113,13 @@ impl Default for RotationHandler {
type DnsOverrides = Box<dyn Fn(&str) -> Option<SocketAddr> + Send + Sync>; type DnsOverrides = Box<dyn Fn(&str) -> Option<SocketAddr> + Send + Sync>;
pub struct Resolver { struct Resolver {
inner: GaiResolver, inner: GaiResolver,
overrides: DnsOverrides, overrides: DnsOverrides,
} }
impl Resolver { impl Resolver {
pub fn new(overrides: DnsOverrides) -> Resolver { fn new(overrides: DnsOverrides) -> Resolver {
Resolver { Resolver {
inner: GaiResolver::new(), inner: GaiResolver::new(),
overrides, overrides,

View file

@ -1,5 +1,5 @@
mod data; mod data;
pub use data::Data; pub(crate) use data::Data;
use crate::Result; use crate::Result;
use ruma::{ use ruma::{

View file

@ -1,7 +1,7 @@
mod data; mod data;
use std::io::Cursor; use std::io::Cursor;
pub use data::Data; pub(crate) use data::Data;
use crate::{services, Result}; use crate::{services, Result};
use image::imageops::FilterType; use image::imageops::FilterType;

View file

@ -7,19 +7,19 @@ use lru_cache::LruCache;
use crate::{Config, Result}; use crate::{Config, Result};
pub mod account_data; pub(crate) mod account_data;
pub mod admin; pub(crate) mod admin;
pub mod appservice; pub(crate) mod appservice;
pub mod globals; pub(crate) mod globals;
pub mod key_backups; pub(crate) mod key_backups;
pub mod media; pub(crate) mod media;
pub mod pdu; pub(crate) mod pdu;
pub mod pusher; pub(crate) mod pusher;
pub mod rooms; pub(crate) mod rooms;
pub mod sending; pub(crate) mod sending;
pub mod transaction_ids; pub(crate) mod transaction_ids;
pub mod uiaa; pub(crate) mod uiaa;
pub mod users; pub(crate) mod users;
pub struct Services<'a> { pub struct Services<'a> {
pub appservice: appservice::Service, pub appservice: appservice::Service,

View file

@ -1,4 +1,4 @@
pub mod error; pub(crate) mod error;
use crate::{services, Error, Result}; use crate::{services, Error, Result};
use argon2::{password_hash::SaltString, PasswordHasher}; use argon2::{password_hash::SaltString, PasswordHasher};
@ -14,14 +14,14 @@ use std::{
time::{SystemTime, UNIX_EPOCH}, time::{SystemTime, UNIX_EPOCH},
}; };
pub fn millis_since_unix_epoch() -> u64 { pub(crate) fn millis_since_unix_epoch() -> u64 {
SystemTime::now() SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.expect("time is valid") .expect("time is valid")
.as_millis() as u64 .as_millis() as u64
} }
pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> { pub(crate) fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
let number = match old.map(|bytes| bytes.try_into()) { let number = match old.map(|bytes| bytes.try_into()) {
Some(Ok(bytes)) => { Some(Ok(bytes)) => {
let number = u64::from_be_bytes(bytes); let number = u64::from_be_bytes(bytes);
@ -89,7 +89,7 @@ pub fn calculate_hash(keys: &[&[u8]]) -> Vec<u8> {
hash.as_ref().to_owned() hash.as_ref().to_owned()
} }
pub fn common_elements( pub(crate) fn common_elements(
mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>, mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>,
check_order: impl Fn(&[u8], &[u8]) -> Ordering, check_order: impl Fn(&[u8], &[u8]) -> Ordering,
) -> Option<impl Iterator<Item = Vec<u8>>> { ) -> Option<impl Iterator<Item = Vec<u8>>> {
@ -116,7 +116,7 @@ pub fn common_elements(
/// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`. /// Fallible conversion from any value that implements `Serialize` to a `CanonicalJsonObject`.
/// ///
/// `value` must serialize to an `serde_json::Value::Object`. /// `value` must serialize to an `serde_json::Value::Object`.
pub fn to_canonical_object<T: serde::Serialize>( pub(crate) fn to_canonical_object<T: serde::Serialize>(
value: T, value: T,
) -> Result<CanonicalJsonObject, CanonicalJsonError> { ) -> Result<CanonicalJsonObject, CanonicalJsonError> {
use serde::ser::Error; use serde::ser::Error;
@ -129,7 +129,7 @@ pub fn to_canonical_object<T: serde::Serialize>(
} }
} }
pub fn deserialize_from_str< pub(crate) fn deserialize_from_str<
'de, 'de,
D: serde::de::Deserializer<'de>, D: serde::de::Deserializer<'de>,
T: FromStr<Err = E>, T: FromStr<Err = E>,
@ -160,7 +160,7 @@ pub fn deserialize_from_str<
/// Wrapper struct which will emit the HTML-escaped version of the contained /// Wrapper struct which will emit the HTML-escaped version of the contained
/// string when passed to a format string. /// string when passed to a format string.
pub struct HtmlEscape<'a>(pub &'a str); pub(crate) struct HtmlEscape<'a>(pub(crate) &'a str);
impl<'a> fmt::Display for HtmlEscape<'a> { impl<'a> fmt::Display for HtmlEscape<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {