Skip to content

Commit

Permalink
Fix some clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
DogLooksGood committed Dec 6, 2023
1 parent 75cf8ee commit 726e0fc
Show file tree
Hide file tree
Showing 27 changed files with 115 additions and 134 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

4 changes: 2 additions & 2 deletions api/src/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ impl Effect {
}

pub fn __checkpoint(&mut self) -> Option<Vec<u8>> {
std::mem::replace(&mut self.checkpoint, None)
self.checkpoint.take()
}

/// Set error.
Expand All @@ -332,7 +332,7 @@ impl Effect {
///
/// This is an internal function, DO NOT use in game handler.
pub fn __take_error(&mut self) -> Option<HandleError> {
std::mem::replace(&mut self.error, None)
self.error.take()
}
}

Expand Down
2 changes: 1 addition & 1 deletion api/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ impl std::fmt::Display for Event {
Event::DrawTimeout => write!(f, "DrawTimeout"),
Event::ActionTimeout { player_addr } => write!(f, "ActionTimeout for {}", player_addr),
Event::SecretsReady { random_ids } => {
write!(f, "SecretsReady for {}", format!("{:?}", random_ids))
write!(f, "SecretsReady for {:?}", random_ids)
}
Event::ServerLeave {
server_addr,
Expand Down
15 changes: 7 additions & 8 deletions api/src/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ impl RandomState {
size,
masks,
owners: owners.to_owned(),
options: options.clone(),
options,
status,
ciphertexts,
revealed: HashMap::new(),
Expand Down Expand Up @@ -466,15 +466,14 @@ impl RandomState {
}

fn add_secret_share(&mut self, share: Share) {
if self
if !self
.secret_shares
.iter()
.find(|ss| {
.any(|ss| {
ss.from_addr.eq(&share.from_addr)
&& ss.to_addr.eq(&share.to_addr)
&& ss.index == share.index
})
.is_none()
{
self.secret_shares.push(share);
}
Expand Down Expand Up @@ -516,7 +515,7 @@ impl RandomState {
from_addr: ss.from_addr.clone(),
to_addr: ss.to_addr.clone(),
random_id: self.id,
index: ss.index as usize,
index: ss.index,
})
.collect()
}
Expand All @@ -530,7 +529,7 @@ impl RandomState {
.iter()
.filter(|ss| ss.to_addr.is_none())
.fold(HashMap::new(), |mut acc, ss| {
acc.entry(ss.index as usize)
acc.entry(ss.index)
.and_modify(|v: &mut Vec<SecretKey>| {
v.push(ss.secret.as_ref().unwrap().clone())
})
Expand All @@ -548,7 +547,7 @@ impl RandomState {
.enumerate()
.filter_map(|(i, c)| {
if matches!(&c.owner, CipherOwner::Assigned(a) if a.eq(addr)) {
Some((i as usize, c.ciphertext.clone()))
Some((i, c.ciphertext.clone()))
} else {
None
}
Expand All @@ -562,7 +561,7 @@ impl RandomState {
.enumerate()
.filter_map(|(i, c)| {
if c.owner == CipherOwner::Revealed {
Some((i as usize, c.ciphertext.clone()))
Some((i, c.ciphertext.clone()))
} else {
None
}
Expand Down
27 changes: 10 additions & 17 deletions core/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;

use crate::types::GameAccount;
use crate::types::{GameAccount, SettleTransferCheckpoint};
use borsh::{BorshDeserialize, BorshSerialize};
use race_api::decision::DecisionState;
use race_api::effect::{Ask, Assign, Effect, Release, Reveal};
Expand Down Expand Up @@ -400,22 +400,22 @@ impl GameContext {
if id == 0 {
return Err(Error::RandomStateNotFound(id));
}
if let Some(rnd_st) = self.random_states.get(id as usize - 1) {
if let Some(rnd_st) = self.random_states.get(id - 1) {
Ok(rnd_st)
} else {
Err(Error::RandomStateNotFound(id))
}
}

pub fn get_random_state_unchecked(&self, id: RandomId) -> &RandomState {
&self.random_states[id as usize - 1]
&self.random_states[id - 1]
}

pub fn get_decision_state_mut(&mut self, id: DecisionId) -> Result<&mut DecisionState> {
if id == 0 {
return Err(Error::InvalidDecisionId);
}
if let Some(st) = self.decision_states.get_mut(id as usize - 1) {
if let Some(st) = self.decision_states.get_mut(id - 1) {
Ok(st)
} else {
Err(Error::InvalidDecisionId)
Expand All @@ -426,7 +426,7 @@ impl GameContext {
if id == 0 {
return Err(Error::RandomStateNotFound(id));
}
if let Some(rnd_st) = self.random_states.get_mut(id as usize - 1) {
if let Some(rnd_st) = self.random_states.get_mut(id - 1) {
Ok(rnd_st)
} else {
Err(Error::RandomStateNotFound(id))
Expand Down Expand Up @@ -516,8 +516,7 @@ impl GameContext {
if self
.servers
.iter()
.find(|s| s.addr.eq(&server.addr))
.is_some()
.any(|s| s.addr.eq(&server.addr))
{
Err(Error::ServerAlreadyJoined(server.addr.clone()))
} else {
Expand Down Expand Up @@ -690,7 +689,7 @@ impl GameContext {

pub fn take_settles_and_transfers(
&mut self,
) -> Result<Option<(Vec<Settle>, Vec<Transfer>, Vec<u8>)>> {
) -> Result<Option<SettleTransferCheckpoint>> {
if let Some(checkpoint) = self.get_checkpoint() {
let mut settles = None;
std::mem::swap(&mut settles, &mut self.settles);
Expand Down Expand Up @@ -814,11 +813,7 @@ impl GameContext {
.list_decision_states()
.iter()
.filter_map(|st| {
if let Some(a) = st.get_revealed() {
Some((st.id, a.to_owned()))
} else {
None
}
st.get_revealed().map(|a| (st.id, a.to_owned()))
})
.collect();

Expand Down Expand Up @@ -914,10 +909,8 @@ impl GameContext {
self.checkpoint = Some(checkpoint_state);
self.settle(settles);
self.transfer(transfers);
} else {
if (!settles.is_empty()) || (!transfers.is_empty()) {
return Err(Error::SettleWithoutCheckpoint);
}
} else if (!settles.is_empty()) || (!transfers.is_empty()) {
return Err(Error::SettleWithoutCheckpoint);
}

if let Some(state) = handler_state {
Expand Down
5 changes: 2 additions & 3 deletions core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,10 @@ pub fn general_handle_event(
Event::Leave { player_addr } => {
if !context.allow_exit {
Err(Error::CantLeave)
} else if context
} else if !context
.players
.iter()
.find(|p| p.addr.eq(player_addr))
.is_none()
.any(|p| p.addr.eq(player_addr))
{
Err(Error::InvalidPlayerAddress)
} else {
Expand Down
2 changes: 1 addition & 1 deletion core/src/types/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl GameAccount {
access_version: game_account.access_version,
settle_version: game_account.settle_version,
max_players: game_account.max_players,
checkpoint: game_account.checkpoint.clone(),
checkpoint: game_account.checkpoint,
}
}

Expand Down
2 changes: 2 additions & 0 deletions core/src/types/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
pub use race_api::types::*;

pub type SettleTransferCheckpoint = (Vec<Settle>, Vec<Transfer>, Vec<u8>);

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ClientMode {
Player,
Expand Down
2 changes: 1 addition & 1 deletion encryptor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ impl EncryptorT for Encryptor {
} = signature;
// TODO: We should check timestamp here.
let message = [message, &u64::to_le_bytes(*timestamp)].concat();
self.verify_raw(Some(&signer), &message, &signature)
self.verify_raw(Some(signer), &message, signature)
}

fn apply(&self, secret: &SecretKey, buffer: &mut [u8]) {
Expand Down
3 changes: 1 addition & 2 deletions transactor/src/blacklist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ impl Blacklist {
let lines = std::io::BufReader::new(file).lines();
if let Ok(addrs) = lines
.into_iter()
.map(|l| l)
.collect::<Result<Vec<String>, _>>()
{
return Blacklist {
Expand Down Expand Up @@ -63,6 +62,6 @@ impl Blacklist {
}

pub fn contains_addr(&self, addr: &str) -> bool {
self.addrs.iter().find(|a| *a == addr).is_some()
self.addrs.iter().any(|a| *a == addr)
}
}
6 changes: 2 additions & 4 deletions transactor/src/component/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl Attachable for PortsHandle {
}
fn output(&mut self) -> Option<mpsc::Receiver<EventFrame>> {
if self.output_rx.is_some() {
std::mem::replace(&mut self.output_rx, None)
self.output_rx.take()
} else {
None
}
Expand Down Expand Up @@ -211,9 +211,7 @@ where
fn start(&self, context: C) -> PortsHandle {
info!("Starting component: {}", self.name());
let (ports, ports_handle_inner) = P::create();
let join_handle = tokio::spawn(async move {
Self::run(ports, context).await
});
let join_handle = tokio::spawn(async move { Self::run(ports, context).await });
PortsHandle::from_inner(ports_handle_inner, join_handle)
}
async fn run(ports: P, context: C) -> CloseReason;
Expand Down
2 changes: 1 addition & 1 deletion transactor/src/component/event_bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Default for EventBus {
while let Some(msg) = rx.recv().await {
let txs = attached_txs.lock().await;
for t in txs.iter() {
if let Err(_) = t.send(msg.clone()).await {
if t.send(msg.clone()).await.is_err() {
warn!("Failed to send message");
}
}
Expand Down
25 changes: 11 additions & 14 deletions transactor/src/component/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use crate::frame::EventFrame;
use crate::utils::addr_shorthand;
use race_core::types::{ClientMode, GameAccount};


fn log_execution_context(ctx: &GameContext, evt: &Event) {
info!("Execution context");
info!("===== State =====");
Expand Down Expand Up @@ -48,7 +47,7 @@ async fn handle(
) -> Option<CloseReason> {
info!(
"{} Handle event: {}",
addr_shorthand(&game_context.get_game_addr()),
addr_shorthand(game_context.get_game_addr()),
event
);

Expand Down Expand Up @@ -77,15 +76,15 @@ async fn handle(

ports
.send(EventFrame::ContextUpdated {
context: game_context.clone(),
context: Box::new(game_context.clone()),
})
.await;

// We do optimistic updates here
if let Some(effects) = effects {
info!(
"{} Send settlements: {:?}",
addr_shorthand(&game_context.get_game_addr()),
addr_shorthand(game_context.get_game_addr()),
effects
);
ports
Expand All @@ -101,10 +100,10 @@ async fn handle(
Err(e) => {
warn!(
"{} Handle event error: {}",
addr_shorthand(&game_context.get_game_addr()),
addr_shorthand(game_context.get_game_addr()),
e.to_string()
);
log_execution_context(&game_context, &event);
log_execution_context(game_context, &event);
match e {
Error::WasmExecutionError(_) | Error::WasmMemoryOverflow => {
return Some(CloseReason::Fault(e))
Expand All @@ -113,7 +112,7 @@ async fn handle(
}
}
}
return None;
None
}

/// Take the event from clients or the pending dispatched event.
Expand Down Expand Up @@ -241,13 +240,11 @@ impl Component<PipelinePorts, EventLoopContext> for EventLoop {
if matches!(event, Event::Shutdown) {
ports.send(EventFrame::Shutdown).await;
return CloseReason::Complete;
} else {
if let Some(close_reason) =
handle(&mut handler, &mut game_context, event, &ports, ctx.mode).await
{
ports.send(EventFrame::Shutdown).await;
return close_reason;
}
} else if let Some(close_reason) =
handle(&mut handler, &mut game_context, event, &ports, ctx.mode).await
{
ports.send(EventFrame::Shutdown).await;
return close_reason;
}
}
EventFrame::Shutdown => {
Expand Down
8 changes: 4 additions & 4 deletions transactor/src/component/submitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn squash_settles(mut prev: SettleParams, next: SettleParams) -> SettleParams {
} = next;
prev.settles.extend(settles);
prev.transfers.extend(transfers);
return SettleParams {
SettleParams {
addr,
settles: prev.settles,
transfers: prev.transfers,
Expand All @@ -33,7 +33,7 @@ fn squash_settles(mut prev: SettleParams, next: SettleParams) -> SettleParams {
// Use the old settle_version
settle_version: prev.settle_version,
next_settle_version: prev.next_settle_version + 1,
};
}
}

/// Read at most 3 settle events from channel.
Expand Down Expand Up @@ -65,7 +65,7 @@ async fn read_settle_params(rx: &mut mpsc::Receiver<SettleParams>) -> Vec<Settle
}
}

return v;
v
}

pub struct SubmitterContext {
Expand Down Expand Up @@ -150,7 +150,7 @@ impl Component<ConsumerPorts, SubmitterContext> for Submitter {
join_handle.await.unwrap_or_else(|e| {
CloseReason::Fault(Error::InternalError(format!(
"Submitter await join handle error: {}",
e.to_string()
e
)))
})
}
Expand Down
Loading

0 comments on commit 726e0fc

Please sign in to comment.