From bd202203844e96b61f917556dbb80eca88fe3f14 Mon Sep 17 00:00:00 2001 From: Chris Sellers Date: Mon, 18 Dec 2023 18:30:52 +1100 Subject: [PATCH] Fix clippy lints --- nautilus_core/backtest/src/engine.rs | 8 ++-- nautilus_core/core/src/datetime.rs | 4 +- nautilus_core/core/src/time.rs | 37 +++++++++++-------- nautilus_core/indicators/src/average/hma.rs | 2 +- nautilus_core/network/src/socket.rs | 2 +- nautilus_core/persistence/src/db/database.rs | 4 +- nautilus_core/persistence/src/db/sql.rs | 10 +++-- .../persistence/tests/test_catalog.rs | 8 ++-- 8 files changed, 42 insertions(+), 33 deletions(-) diff --git a/nautilus_core/backtest/src/engine.rs b/nautilus_core/backtest/src/engine.rs index 6950cf1e3ac4..1919438d7b14 100644 --- a/nautilus_core/backtest/src/engine.rs +++ b/nautilus_core/backtest/src/engine.rs @@ -133,7 +133,7 @@ mod tests { // Note: as_ptr returns a borrowed pointer. It is valid as long // as the object is in scope. In this case `callback_ptr` is valid // as long as `py_append` is in scope. - let callback_ptr = py_append.as_ptr() as *mut pyo3::ffi::PyObject; + let callback_ptr = py_append.as_ptr().cast::(); let handler1 = TimeEventHandler { event: time_event1.clone(), @@ -150,9 +150,9 @@ mod tests { callback_ptr, }; - accumulator.event_handlers.push(handler1.clone()); - accumulator.event_handlers.push(handler2.clone()); - accumulator.event_handlers.push(handler3.clone()); + accumulator.event_handlers.push(handler1); + accumulator.event_handlers.push(handler2); + accumulator.event_handlers.push(handler3); let drained_handlers = accumulator.drain(); diff --git a/nautilus_core/core/src/datetime.rs b/nautilus_core/core/src/datetime.rs index 03d35d954fee..bd2bc8a34826 100644 --- a/nautilus_core/core/src/datetime.rs +++ b/nautilus_core/core/src/datetime.rs @@ -98,11 +98,11 @@ pub fn last_weekday_nanos(year: i32, month: u32, day: u32) -> Result let current_weekday = date.weekday().number_from_monday(); // Calculate the offset in days for closest weekday (Mon-Fri) - let offset = match current_weekday { + let offset = i64::from(match current_weekday { 1..=5 => 0, // Monday to Friday, no adjustment needed 6 => 1, // Saturday, adjust to previous Friday _ => 2, // Sunday, adjust to previous Friday - } as i64; + }); // Calculate last closest weekday let last_closest = date - chrono::Duration::days(offset); diff --git a/nautilus_core/core/src/time.rs b/nautilus_core/core/src/time.rs index 4b8fe4dae79f..68f0ae94601b 100644 --- a/nautilus_core/core/src/time.rs +++ b/nautilus_core/core/src/time.rs @@ -45,17 +45,17 @@ pub enum ClockMode { STATIC, } -/// Atomic clock stores the last recorded time in nanoseconds +/// Atomic clock stores the last recorded time in nanoseconds. /// -/// It uses AtomicU64 to atomically update the value using only immutable +/// It uses `AtomicU64` to atomically update the value using only immutable /// references. /// -/// AtomicClock can act as a live clock and static clock based on its mode. +/// `AtomicClock` can act as a live clock and static clock based on its mode. #[derive(Debug, Clone)] pub struct AtomicTime { - /// Atomic clock is operating in live or static mode + /// Atomic clock is operating in live or static mode. mode: ClockMode, - /// The last recorded time in nanoseconds for the clock + /// The last recorded time in nanoseconds for the clock. timestamp_ns: Arc, } @@ -68,9 +68,10 @@ impl Deref for AtomicTime { } impl AtomicTime { - /// New atomic clock set with the given time + /// New atomic clock set with the given time. + #[must_use] pub fn new(mode: ClockMode, time: u64) -> Self { - AtomicTime { + Self { mode, timestamp_ns: Arc::new(AtomicU64::new(time)), } @@ -80,6 +81,7 @@ impl AtomicTime { /// /// * Live mode returns current wall clock time since UNIX epoch (unique and monotonic) /// * Static mode returns currently stored time. + #[must_use] pub fn get_time_ns(&self) -> u64 { match self.mode { ClockMode::LIVE => self.time_since_epoch(), @@ -87,34 +89,39 @@ impl AtomicTime { } } - /// Get time as microseconds + /// Get time as microseconds. + #[must_use] pub fn get_time_us(&self) -> u64 { self.get_time_ns() / NANOSECONDS_IN_MICROSECOND } - /// Get time as milliseconds + /// Get time as milliseconds. + #[must_use] pub fn get_time_ms(&self) -> u64 { self.get_time_ns() / NANOSECONDS_IN_MILLISECOND } - /// Get time as seconds + /// Get time as seconds. + #[must_use] pub fn get_time(&self) -> f64 { self.get_time_ns() as f64 / (NANOSECONDS_IN_SECOND as f64) } - /// Sets new time for the clock + /// Sets new time for the clock. pub fn set_time(&self, time: u64) { - self.store(time, Ordering::Relaxed) + self.store(time, Ordering::Relaxed); } - /// Increments current time with a delta and returns the updated time + /// Increments current time with a delta and returns the updated time. + #[must_use] pub fn increment_time(&self, delta: u64) -> u64 { self.fetch_add(delta, Ordering::Relaxed) + delta } - /// Stores and returns current time + /// Stores and returns current time. + #[must_use] pub fn time_since_epoch(&self) -> u64 { - // increment by 1 nanosecond to keep increasing time + // Increment by 1 nanosecond to keep increasing time let now = duration_since_unix_epoch().as_nanos() as u64 + 1; let last = self.load(Ordering::SeqCst) + 1; let new = now.max(last); diff --git a/nautilus_core/indicators/src/average/hma.rs b/nautilus_core/indicators/src/average/hma.rs index b9576ca61a1d..b853b5ffe8de 100644 --- a/nautilus_core/indicators/src/average/hma.rs +++ b/nautilus_core/indicators/src/average/hma.rs @@ -107,7 +107,7 @@ impl HullMovingAverage { let _ma2 = WeightedMovingAverage::new(period, w2, price_type)?; let _ma3 = WeightedMovingAverage::new(period_sqrt, w3, price_type)?; - Ok(HullMovingAverage { + Ok(Self { period, price_type: price_type.unwrap_or(PriceType::Last), value: 0.0, diff --git a/nautilus_core/network/src/socket.rs b/nautilus_core/network/src/socket.rs index 4add2750e139..03c9719468cd 100644 --- a/nautilus_core/network/src/socket.rs +++ b/nautilus_core/network/src/socket.rs @@ -392,7 +392,7 @@ impl SocketClient { (true, true) => { debug!("Shutting down inner client"); match inner.shutdown().await { - Ok(_) => debug!("Closed connection"), + Ok(()) => debug!("Closed connection"), Err(e) => error!("Error on `shutdown`: {e}"), } diff --git a/nautilus_core/persistence/src/db/database.rs b/nautilus_core/persistence/src/db/database.rs index bd1e7f1eac39..16a0b447f7b3 100644 --- a/nautilus_core/persistence/src/db/database.rs +++ b/nautilus_core/persistence/src/db/database.rs @@ -113,9 +113,9 @@ pub async fn init_db_schema(db: &Database, schema_dir: &str) -> Result<()> { let mut sql_files = std::fs::read_dir(schema_dir)?.collect::, std::io::Error>>()?; - for file in sql_files.iter_mut() { + for file in &mut sql_files { let file_name = file.file_name(); - println!("Executing SQL file: {:?}", file_name); + println!("Executing SQL file: {file_name:?}"); let file_path = file.path(); let sql_content = std::fs::read_to_string(file_path.clone())?; for sql_statement in sql_content.split(';').filter(|s| !s.trim().is_empty()) { diff --git a/nautilus_core/persistence/src/db/sql.rs b/nautilus_core/persistence/src/db/sql.rs index 59cc4693fa2a..1095cbca778e 100644 --- a/nautilus_core/persistence/src/db/sql.rs +++ b/nautilus_core/persistence/src/db/sql.rs @@ -24,30 +24,32 @@ pub struct SqlCacheDatabase { } impl SqlCacheDatabase { + #[must_use] pub fn new(trader_id: TraderId, database: Database) -> Self { Self { trader_id, db: database, } } + #[must_use] pub fn key_trader(&self) -> String { format!("trader-{}", self.trader_id) } + #[must_use] pub fn key_general(&self) -> String { format!("{}:general:", self.key_trader()) } pub async fn add(&self, key: String, value: String) -> Result { let query = format!( - "INSERT INTO general (key, value) VALUES ('{}', '{}') ON CONFLICT (key) DO NOTHING;", - key, value + "INSERT INTO general (key, value) VALUES ('{key}', '{value}') ON CONFLICT (key) DO NOTHING;" ); self.db.execute(query.as_str()).await } pub async fn get(&self, key: String) -> Vec { - let query = format!("SELECT * FROM general WHERE key = '{}'", key); + let query = format!("SELECT * FROM general WHERE key = '{key}'"); self.db .fetch_all::(query.as_str()) .await @@ -93,7 +95,7 @@ mod tests { .expect("Failed to add key"); let value = cache.get(String::from("key1")).await; assert_eq!(value.len(), 1); - let item = value.get(0).unwrap(); + let item = value.first().unwrap(); assert_eq!(item.key, "key1"); assert_eq!(item.value, "value1"); } diff --git a/nautilus_core/persistence/tests/test_catalog.rs b/nautilus_core/persistence/tests/test_catalog.rs index 658cc2cfcd9c..e1f8a7c62f7c 100644 --- a/nautilus_core/persistence/tests/test_catalog.rs +++ b/nautilus_core/persistence/tests/test_catalog.rs @@ -34,17 +34,17 @@ fn test_quote_tick_python_interface() { .add_file::("quote_005", file_path, None) .unwrap(); let query_result: QueryResult = catalog.get_query_result(); - let mut query_result = DataQueryResult::new(query_result, catalog.chunk_size); + let query_result = DataQueryResult::new(query_result, catalog.chunk_size); let mut count = 0; - while let Some(chunk) = query_result.next() { - if chunk.len() == 0 { + for chunk in query_result { + if chunk.is_empty() { break; } let chunk: CVec = chunk.into(); let ticks: &[Data] = unsafe { std::slice::from_raw_parts(chunk.ptr as *const Data, chunk.len) }; count += ticks.len(); - assert!(is_monotonically_increasing_by_init(&ticks)); + assert!(is_monotonically_increasing_by_init(ticks)); } assert_eq!(expected_length, count);