Skip to content

Commit

Permalink
code: Fix most clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
felinira committed Dec 9, 2023
1 parent 6b11a4c commit a584c16
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 96 deletions.
29 changes: 14 additions & 15 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ async fn main() -> eyre::Result<()> {
}
};

if with_dilation && peer_allows_dilation(&wormhole.peer_version()) {
if with_dilation && peer_allows_dilation(wormhole.peer_version()) {
log::debug!("dilate wormhole");
let mut dilated_wormhole = wormhole.dilate()?; // need to pass transit relay URL
dilated_wormhole.run().await;
Expand Down Expand Up @@ -570,7 +570,7 @@ async fn main() -> eyre::Result<()> {
out,
);

std::io::stdout().write_all(&out.as_bytes())?;
std::io::stdout().write_all(out.as_bytes())?;
},
shell => {
let mut out = std::io::stdout();
Expand Down Expand Up @@ -601,6 +601,8 @@ fn parse_transit_args(args: &CommonArgs) -> transit::Abilities {
}
}

type PrintCodeFn = dyn Fn(&mut Term, &magic_wormhole::Code, &Option<url::Url>) -> eyre::Result<()>;

/**
* Parse the necessary command line arguments to establish an initial server connection.
* This is used over and over again by the different subcommands.
Expand All @@ -616,9 +618,7 @@ async fn parse_and_connect(
code_length: Option<usize>,
is_send: bool,
mut app_config: magic_wormhole::AppConfig<impl serde::Serialize + Send + Sync + 'static>,
print_code: Option<
&dyn Fn(&mut Term, &magic_wormhole::Code, &Option<url::Url>) -> eyre::Result<()>,
>,
print_code: Option<&PrintCodeFn>,
clipboard: Option<&mut Clipboard>,
) -> eyre::Result<(Wormhole, magic_wormhole::Code, Vec<transit::RelayHint>)> {
// TODO handle relay servers with multiple endpoints better
Expand Down Expand Up @@ -1059,15 +1059,14 @@ async fn receive_inner_v1(
.truncate(true)
.open(&file_path)
.await?;
Ok(req
.accept(
&transit::log_transit_connection,
&mut file,
create_progress_handler(pb),
ctrl_c(),
)
.await
.context("Receive process failed")?)
req.accept(
&transit::log_transit_connection,
&mut file,
create_progress_handler(pb),
ctrl_c(),
)
.await
.context("Receive process failed")
}

async fn receive_inner_v2(
Expand Down Expand Up @@ -1107,7 +1106,7 @@ async fn receive_inner_v2(

/* Create a temporary directory for receiving */
use rand::Rng;
let tmp_dir = target_dir.join(&format!(
let tmp_dir = target_dir.join(format!(
"wormhole-tmp-{:06}",
rand::thread_rng().gen_range(0..1_000_000)
));
Expand Down
2 changes: 1 addition & 1 deletion cli/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub async fn ask_user(message: impl std::fmt::Display, default_answer: bool) ->
let mut answer = String::new();
stdin.read_line(&mut answer).await.unwrap();

match &*answer.to_lowercase().trim() {
match answer.to_lowercase().trim() {
"y" | "yes" => break true,
"n" | "no" => break false,
"" => break default_answer,
Expand Down
25 changes: 12 additions & 13 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ use crate::core::protocol::{WormholeProtocol, WormholeProtocolDefault};
use crate::dilation::DilatedWormhole;
use crypto_secretbox as secretbox;
use log::*;
use serde;
use serde_derive::{Deserialize, Serialize};
use serde_json::Value;

use self::rendezvous::*;
pub(self) use self::server_messages::EncryptedMessage;
use self::server_messages::EncryptedMessage;

pub(super) mod key;
pub(crate) mod protocol;
Expand Down Expand Up @@ -161,7 +160,7 @@ impl<V: serde::Serialize + Send + Sync + 'static> MailboxConnection<V> {
let (mut server, welcome) =
RendezvousServer::connect(&config.id, &config.rendezvous_url).await?;
let (nameplate, mailbox) = server.allocate_claim_open().await?;
let code = Code::new(&nameplate, &password);
let code = Code::new(&nameplate, password);

Ok(MailboxConnection {
config,
Expand Down Expand Up @@ -303,13 +302,13 @@ impl Wormhole {
) -> Result<(WormholeWelcome, Self), WormholeError> {
let mailbox_connection =
MailboxConnection::connect(config, code.clone(), !expect_claimed_nameplate).await?;
return Ok((
Ok((
WormholeWelcome {
welcome: mailbox_connection.welcome.clone(),
code: code,
code,
},
Self::connect(mailbox_connection).await?,
));
))
}

/// Set up a Wormhole which is the client-client part of the connection setup
Expand Down Expand Up @@ -469,7 +468,7 @@ impl Wormhole {
}

pub fn our_version(&self) -> &Box<dyn Any + Send + Sync> {
&self.protocol.our_version()
self.protocol.our_version()
}
}

Expand Down Expand Up @@ -643,7 +642,7 @@ impl<S: Into<String>> From<S> for EitherSide {

impl From<MySide> for TheirSide {
fn from(side: MySide) -> TheirSide {
TheirSide(side.0.into())
TheirSide(side.0)
}
}

Expand All @@ -660,7 +659,7 @@ impl Phase {
}

pub fn dilation(phase: u64) -> Self {
Phase(format!("dilate-{}", phase.to_string()).to_string().into())
Phase(format!("dilate-{}", phase).into())
}

pub fn is_version(&self) -> bool {
Expand Down Expand Up @@ -694,9 +693,9 @@ impl Nameplate {
}
}

impl Into<String> for Nameplate {
fn into(self) -> String {
self.0
impl From<Nameplate> for String {
fn from(value: Nameplate) -> Self {
value.0
}
}

Expand All @@ -723,7 +722,7 @@ impl Code {
}

pub fn nameplate(&self) -> Nameplate {
Nameplate::new(self.0.splitn(2, '-').next().unwrap())
Nameplate::new(self.0.split('-').next().unwrap())
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/core/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl Key<WormholeKey> {
*/
#[cfg(feature = "transit")]
pub fn derive_transit_key(&self, appid: &AppID) -> Key<crate::transit::TransitKey> {
let transit_purpose = format!("{}/transit-key", &*appid);
let transit_purpose = format!("{}/transit-key", appid);

let derived_key = self.derive_subkey_from_purpose(&transit_purpose);
trace!(
Expand All @@ -68,15 +68,15 @@ impl<P: KeyPurpose> Key<P> {
}

pub fn to_hex(&self) -> String {
hex::encode(&**self)
hex::encode(**self)
}

/**
* Derive a new sub-key from this one
*/
pub fn derive_subkey_from_purpose<NewP: KeyPurpose>(&self, purpose: &str) -> Key<NewP> {
Key(
Box::new(derive_key(&*self, purpose.as_bytes())),
Box::new(derive_key(self, purpose.as_bytes())),
std::marker::PhantomData,
)
}
Expand Down
2 changes: 2 additions & 0 deletions src/core/server_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ impl EncryptedMessage {
#[derive(Serialize, Debug, PartialEq, derive_more::Display)]
#[serde(rename_all = "kebab-case")]
#[serde(tag = "type")]
#[allow(dead_code)]
pub enum OutboundMessage {
#[display(fmt = "SubmitPermission({})", _0)]
SubmitPermission(SubmitPermission),
Expand Down Expand Up @@ -196,6 +197,7 @@ impl OutboundMessage {
OutboundMessage::Open { mailbox }
}

#[allow(dead_code)]
pub fn add(phase: Phase, body: Vec<u8>) -> Self {
OutboundMessage::Add { body, phase }
}
Expand Down
11 changes: 5 additions & 6 deletions src/core/wordlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ impl Wordlist {
let mut suffix: String = prefix.to_owned();
if word.starts_with(last_partial_word.unwrap()) {
if lp == 0 {
suffix.push_str(&word);
suffix.push_str(word);
} else {
let p = prefix.len() - lp;
suffix.truncate(p as usize);
suffix.push_str(&word);
suffix.truncate(p);
suffix.push_str(word);
}

if count_dashes + 1 < self.num_words {
suffix.push_str("-");
suffix.push('-');
}

completions.push(suffix);
Expand All @@ -56,8 +56,7 @@ impl Wordlist {

pub fn choose_words(&self) -> String {
let mut rng = OsRng;
let components: Vec<String>;
components = self
let components: Vec<String> = self
.words
.iter()
.cycle()
Expand Down
2 changes: 2 additions & 0 deletions src/dilation/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub enum IOEvent {

/// Commands to be executed
#[derive(Debug, Clone, PartialEq, Display)]
#[allow(dead_code)]
pub enum ManagerCommand {
// XXX: include API calls to IO layer
Protocol(ProtocolCommand),
Expand All @@ -28,6 +29,7 @@ pub enum ProtocolCommand {

/// Protocol level commands
#[derive(Debug, Clone, PartialEq, Display)]
#[allow(dead_code)]
pub enum IOCommand {
CloseConnection,
}
6 changes: 3 additions & 3 deletions src/dilation/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub enum Role {
}

#[derive(Debug, PartialEq, Clone, Copy, Display)]
#[allow(dead_code)]
pub enum State {
Waiting,
Wanting,
Expand All @@ -38,12 +39,11 @@ pub struct ManagerMachine {
#[cfg_attr(test, automock)]
impl ManagerMachine {
pub fn new(side: MySide) -> Self {
let machine = ManagerMachine {
ManagerMachine {
side,
role: Role::Follower,
state: Some(State::Wanting),
};
machine
}
}

pub fn current_state(&self) -> Option<State> {
Expand Down
4 changes: 2 additions & 2 deletions src/forwarding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ pub async fn serve(
.to_owned();
let peer_version: AppVersion = serde_json::from_value(wormhole.peer_version().to_owned())?;
let connector = transit::init(
our_version.transit_abilities.clone(),
Some(peer_version.transit_abilities.clone()),
our_version.transit_abilities,
Some(peer_version.transit_abilities),
relay_hints,
)
.await?;
Expand Down
14 changes: 6 additions & 8 deletions src/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,13 +457,11 @@ impl<T> Offer<T> {
"{name} and {} other files or directories",
self.content.len() - 1
)
} else if self.is_directory() {
let count = entry.iter_files().count();
format!("{name} with {count} files inside")
} else {
if self.is_directory() {
let count = entry.iter_files().count();
format!("{name} with {count} files inside")
} else {
name.clone()
}
name.clone()
}
}

Expand Down Expand Up @@ -731,11 +729,11 @@ impl<T> OfferEntry<T> {
match self {
OfferEntry::RegularFile { size, .. } => OfferEntry::RegularFile {
size: *size,
content: f(&base_path),
content: f(base_path),
},
OfferEntry::Directory { content } => OfferEntry::Directory {
content: content
.into_iter()
.iter()
.map(|(k, v)| {
base_path.push(k.clone());
let v = v.set_content(base_path, f);
Expand Down
19 changes: 8 additions & 11 deletions src/transfer/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,25 +265,22 @@ pub async fn send_folder(
};
use std::io::Result as IoResult;

type WrappedDataFut = BoxFuture<'static, IoResult<Box<dyn AsyncRead + Unpin + Send>>>;

/* Type tetris :) */
fn wrap(
buffer: impl AsRef<[u8]> + Unpin + Send + 'static,
) -> BoxFuture<'static, IoResult<Box<dyn AsyncRead + Unpin + Send>>> {
fn wrap(buffer: impl AsRef<[u8]> + Unpin + Send + 'static) -> WrappedDataFut {
Box::pin(ready(IoResult::Ok(
Box::new(Cursor::new(buffer)) as Box<dyn AsyncRead + Unpin + Send>
))) as _
}

/* Walk our offer recursively, concatenate all our readers into a stream that will build the tar file */
fn create_offer(
mut total_content: Vec<
BoxFuture<'static, IoResult<Box<dyn AsyncRead + Unpin + Send + 'static>>>,
>,
mut total_content: Vec<WrappedDataFut>,
total_size: &mut u64,
offer: OfferSendEntry,
path: &mut Vec<String>,
) -> IoResult<Vec<BoxFuture<'static, IoResult<Box<dyn AsyncRead + Unpin + Send + 'static>>>>>
{
) -> IoResult<Vec<WrappedDataFut>> {
match offer {
OfferSendEntry::Directory { content } => {
log::debug!("Adding directory {path:?}");
Expand All @@ -299,7 +296,7 @@ pub async fn send_folder(
},
OfferSendEntry::RegularFile { size, content } => {
log::debug!("Adding file {path:?}; {size} bytes");
let header = tar_helper::create_header_file(&path, size)?;
let header = tar_helper::create_header_file(path, size)?;
let padding = tar_helper::padding(size);
*total_size += header.len() as u64;
*total_size += padding.len() as u64;
Expand Down Expand Up @@ -330,7 +327,7 @@ pub async fn send_folder(
total_size += 1024;
content.push(wrap([0; 1024]));

let content = futures::stream::iter(content).then(|content| async { content.await });
let content = futures::stream::iter(content).then(|content| content);

/* Convert to stream */

Expand Down Expand Up @@ -773,7 +770,7 @@ mod tar_helper {
// long name extension by emitting an entry which indicates that it's the
// filename.
if let Err(e) = header.set_path(path) {
let data = path2bytes(&path);
let data = path2bytes(path);
let max = header.as_old().name.len();
// Since `e` isn't specific enough to let us know the path is indeed too
// long, verify it first before using the extension.
Expand Down
Loading

0 comments on commit a584c16

Please sign in to comment.