Skip to content

Commit

Permalink
style(all): Fix rust clippy issues (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
fioncat authored Feb 22, 2024
1 parent 558b118 commit d4b3a6f
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 220 deletions.
315 changes: 160 additions & 155 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion clipboard/examples/clipboard_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async fn main() {

fn handle_read(data_frame: Option<DataFrame>) {
println!("Clipboard changed");
if let None = data_frame {
if data_frame.is_none() {
println!();
return;
}
Expand Down
37 changes: 20 additions & 17 deletions clipboard/src/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ impl ClipboardManager {
const INCORRECT_CLIPBOARD_TYPE_ERROR: &'static str = "incorrect type received from clipboard";

async fn main_loop(&mut self) {
if let None = self.read_tx {
if let None = self.write_rx {
if self.read_tx.is_none() {
if self.write_rx.is_none() {
unreachable!();
}
return self.writeonly_loop().await;
}

if let None = self.write_rx {
if self.write_rx.is_none() {
return self.readonly_loop().await;
}

Expand Down Expand Up @@ -161,14 +161,16 @@ impl ClipboardManager {
fn read(&mut self) -> Result<Option<DataFrame>> {
match self.driver.get_text() {
Ok(text) => {
let digest = Some(digest(&text));
if digest == self.digest {
return Ok(None);
let digest = digest(&text);
if let Some(current_digest) = self.digest.as_ref() {
if current_digest == &digest {
return Ok(None);
}
}
self.digest = digest.clone();
self.digest = Some(digest.clone());
return Ok(Some(DataFrame {
from: None,
digest: digest.unwrap(),
digest,
data: ClipboardFrame::Text(text),
}));
}
Expand All @@ -183,14 +185,16 @@ impl ClipboardManager {
Ok(image) => {
let (width, height) = (image.width as u64, image.height as u64);
let data = image.bytes.into_owned();
let digest = Some(digest::<&[u8]>(&data));
if digest == self.digest {
return Ok(None);
let digest = digest::<&[u8]>(&data);
if let Some(current_digest) = self.digest.as_ref() {
if current_digest == &digest {
return Ok(None);
}
}
self.digest = digest.clone();
self.digest = Some(digest.clone());
Ok(Some(DataFrame {
from: None,
digest: digest.unwrap(),
digest,
data: ClipboardFrame::Image(ClipboardImage {
width,
height,
Expand Down Expand Up @@ -280,10 +284,9 @@ impl ClipboardNotify {
let mut master = ClipboardMaster::new(notify);

std::thread::spawn(move || {
match master.run() {
// We would never stop watching, so the function should never be returned.
_ => unreachable!(),
}
let _ = master.run();
// We would never stop watching, so the function should never be returned.
unreachable!();
});

rx
Expand Down
18 changes: 8 additions & 10 deletions csync/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ impl Target {
None => bail!("invalid target format '{}'", s.as_ref()),
};

if let None = caps.get(0) {
if caps.get(0).is_none() {
bail!("invalid target '{}', did not match regex", s.as_ref());
}

let mut publish = None;
if let Some(publish_name) = caps.get(1) {
let name = publish_name
.as_str()
.strip_suffix("@")
.strip_suffix('@')
.unwrap_or(publish_name.as_str());
publish = Some(name.to_string());
}
Expand All @@ -90,7 +90,7 @@ impl Target {
if let Some(sub_names) = caps.get(3) {
let sub_names = sub_names
.as_str()
.strip_prefix("/")
.strip_prefix('/')
.unwrap_or(sub_names.as_str());
subs = Some(
sub_names
Expand All @@ -100,13 +100,11 @@ impl Target {
);
}

if let None = publish {
if let None = subs {
bail!(
"invalid target '{}', you must provide publish or subs in target",
s.as_ref()
);
}
if publish.is_none() && subs.is_none() {
bail!(
"invalid target '{}', you must provide publish or subs in target",
s.as_ref()
);
}

Ok(Target {
Expand Down
16 changes: 8 additions & 8 deletions csync/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ impl Sync {
pub async fn new(cfg: &Config) -> Result<Sync> {
let target = Target::parse(&cfg.target)?;
let mut readonly = false;
if let None = target.subs {
if target.subs.is_none() {
readonly = true;
}

let mut writeonly = false;
if let None = target.publish {
if target.publish.is_none() {
writeonly = true;
}

let cb = Clipboard::new(readonly, writeonly).context("init clipboard")?;

let output = Output::new(&cfg, &target);
let client = target.build_client(&cfg).await?;
let output = Output::new(cfg, &target);
let client = target.build_client(cfg).await?;

if cfg.pull_interval < 100 || cfg.pull_interval > 20000 {
bail!("invalid pull_interval, should be in range [100, 20000]")
Expand All @@ -55,7 +55,7 @@ impl Sync {
}

pub async fn start(&mut self) -> Result<()> {
if let None = self.cb.read_rx {
if self.cb.read_rx.is_none() {
let mut write_tx = self.cb.write_tx.take().unwrap();
let mut pull_intv = time::interval_at(self.start, self.pull_intv);

Expand All @@ -71,7 +71,7 @@ impl Sync {
}
}

if let None = self.cb.write_tx {
if self.cb.write_tx.is_none() {
let mut read_rx = self.cb.read_rx.take().unwrap();
loop {
select! {
Expand Down Expand Up @@ -105,7 +105,7 @@ impl Sync {
}

async fn handle_publish(&mut self, frame: Option<DataFrame>) -> Result<()> {
if let None = frame {
if frame.is_none() {
return Ok(());
}
let frame = frame.unwrap();
Expand All @@ -120,7 +120,7 @@ impl Sync {

async fn handle_sub(&mut self, write_tx: &mut Sender<DataFrame>) -> Result<()> {
let frame = self.client.pull().await.context("pull data from server")?;
if let None = frame {
if frame.is_none() {
return Ok(());
}
let frame = frame.unwrap();
Expand Down
12 changes: 5 additions & 7 deletions csyncd/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,8 @@ impl ChannelHandler {
publish: Option<Arc<String>>,
subs: Option<Arc<Vec<String>>>,
) -> Result<()> {
if let None = publish {
if let None = subs {
return Ok(());
}
if publish.is_none() && subs.is_none() {
return Ok(());
}
let (resp_tx, resp_rx) = oneshot::channel::<()>();
let req = CloseRequest {
Expand Down Expand Up @@ -227,7 +225,7 @@ impl ChannelManager {
Some(channel) => channel,
None => continue,
};
if let None = channel.data {
if channel.data.is_none() {
continue;
}
if let Some(update) = channel.subs.get_mut(req.addr.as_ref()) {
Expand All @@ -239,7 +237,7 @@ impl ChannelManager {
channel.subs.insert(req.addr.as_ref().to_string(), false);
}

if let None = result {
if result.is_none() {
let frame = channel.data.as_ref().unwrap();
let frame = Arc::clone(frame);
result = Some(frame);
Expand Down Expand Up @@ -276,7 +274,7 @@ impl ChannelManager {
if cfg!(test) {
self.assert_addr_remove(addr.as_ref());
if let Some(publish) = publish.as_ref() {
if let Some(_) = self.channels.get(publish.as_ref()) {
if self.channels.get(publish.as_ref()).is_some() {
panic!("unexpect channel exists: {publish}");
}
}
Expand Down
6 changes: 3 additions & 3 deletions csyncd/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ impl Worker {
}
}

let publish = self.publish.as_ref().map(|p| Arc::clone(p));
let subs = self.subs.as_ref().map(|s| Arc::clone(s));
let publish = self.publish.as_ref().map(Arc::clone);
let subs = self.subs.as_ref().map(Arc::clone);

if let Err(err) = self
.ch
Expand Down Expand Up @@ -138,7 +138,7 @@ impl Worker {
async fn handle_push(&mut self, frame: Frame) -> Result<()> {
if let Some(publish) = self.publish.as_ref() {
let mut data = frame.expect_data().unwrap().unwrap();
if let None = data.from {
if data.from.is_none() {
data.from = Some(publish.to_string());
}

Expand Down
14 changes: 7 additions & 7 deletions proto/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Auth {
const PBKDF2_ROUNDS: u32 = 600_000;

pub fn new<S: AsRef<str>>(password: S) -> Auth {
let mut rng = OsRng::default();
let mut rng = OsRng;
let nonce = Self::generate_nonce(&mut rng);
let salt = Self::generate_salt(&mut rng);
let key = Self::generate_key(password, &salt);
Expand Down Expand Up @@ -59,7 +59,7 @@ impl Auth {
}

pub fn build_frame(&self) -> Result<AuthFrame, AuthError> {
let mut rng = OsRng::default();
let mut rng = OsRng;
let check_plain = Self::generate_check_plain(&mut rng);
let check = self.encrypt(&check_plain)?;

Expand All @@ -73,27 +73,27 @@ impl Auth {

pub fn encrypt(&self, plain_data: &[u8]) -> Result<Vec<u8>, AuthError> {
let key = Key::<Aes256Gcm>::from_slice(&self.key);
let mut cipher = Aes256Gcm::new(&key);
let mut cipher = Aes256Gcm::new(key);
let nonce = Nonce::<Aes256Gcm>::from_slice(&self.nonce);
match cipher.encrypt(&nonce, plain_data) {
match cipher.encrypt(nonce, plain_data) {
Ok(data) => Ok(data),
Err(err) => Err(AuthError::AesError(err)),
}
}

pub fn decrypt(&self, cipher_data: &[u8]) -> Result<Vec<u8>, AuthError> {
let key = Key::<Aes256Gcm>::from_slice(&self.key);
let mut cipher = Aes256Gcm::new(&key);
let mut cipher = Aes256Gcm::new(key);
let nonce = Nonce::<Aes256Gcm>::from_slice(&self.nonce);
match cipher.decrypt(&nonce, cipher_data) {
match cipher.decrypt(nonce, cipher_data) {
Ok(data) => Ok(data),
Err(_) => Err(AuthError::IncorrectPassword),
}
}

#[inline]
fn generate_key<S: AsRef<str>>(password: S, salt: &[u8]) -> [u8; Self::KEY_LENGTH] {
pbkdf2_hmac_array::<Sha256, 32>(password.as_ref().as_bytes(), &salt, Self::PBKDF2_ROUNDS)
pbkdf2_hmac_array::<Sha256, 32>(password.as_ref().as_bytes(), salt, Self::PBKDF2_ROUNDS)
}

#[inline]
Expand Down
11 changes: 4 additions & 7 deletions proto/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,8 @@ impl<P: Password> Client<P> {
subs: Option<Vec<String>>,
password: P,
) -> Result<Client<P>> {
if let None = publish {
if let None = subs {
bail!("publish and subs cannot be empty at the same time");
}
if publish.is_none() && subs.is_none() {
bail!("publish and subs cannot be empty at the same time");
}

let addr = Self::parse_addr(addr).await?;
Expand All @@ -85,9 +83,8 @@ impl<P: Password> Client<P> {
}

async fn parse_addr<S: AsRef<str>>(addr: S) -> Result<SocketAddr> {
match addr.as_ref().parse::<SocketAddr>() {
Ok(addr) => return Ok(addr),
Err(_) => {}
if let Ok(addr) = addr.as_ref().parse::<SocketAddr>() {
return Ok(addr);
}

let addrs: Vec<SocketAddr> = lookup_host(addr.as_ref())
Expand Down
2 changes: 1 addition & 1 deletion proto/src/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl Connection {
}
.context("create tcp socket")?;
let stream = socket
.connect(addr.clone())
.connect(*addr)
.await
.with_context(|| format!("connect to '{}'", addr))?;
Ok(Self::new(stream, auth))
Expand Down
6 changes: 3 additions & 3 deletions proto/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ impl Frame {
}

let from = match get_data_option(src, auth)? {
Some(data) => Some(parse_string(&data.to_vec())?),
Some(data) => Some(parse_string(&data)?),
None => None,
};

Expand Down Expand Up @@ -404,7 +404,7 @@ fn skip(src: &mut Cursor<&[u8]>, n: usize) -> Result<(), FrameError> {
fn parse_string(data: &[u8]) -> Result<String, FrameError> {
match String::from_utf8(data.to_vec()) {
Ok(text) => Ok(text),
Err(_) => return Err(FrameError::Protocol("invalid text, not uft-8 encoded")),
Err(_) => Err(FrameError::Protocol("invalid text, not uft-8 encoded")),
}
}

Expand Down Expand Up @@ -434,6 +434,6 @@ fn decode_object<T: DeserializeOwned>(data: &[u8]) -> Result<T, FrameError> {
fn encode_object<T: Serialize>(value: &T) -> Result<Vec<u8>, FrameError> {
match bincode::serialize(value) {
Ok(data) => Ok(data),
Err(_) => return Err(FrameError::Protocol("encode frame failed")),
Err(_) => Err(FrameError::Protocol("encode frame failed")),
}
}
2 changes: 1 addition & 1 deletion utils/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use vergen::EmitBuilder;

fn uncommitted_count() -> Result<usize, Box<dyn Error>> {
let output = exec_git(&["status", "-s"])?;
let lines = output.trim().split("\n");
let lines = output.trim().split('\n');
Ok(lines.filter(|line| !line.trim().is_empty()).count())
}

Expand Down

0 comments on commit d4b3a6f

Please sign in to comment.