diff options
author | Manos Pitsidianakis <el13635@mail.ntua.gr> | 2018-08-23 15:36:52 +0300 |
---|---|---|
committer | Manos Pitsidianakis <el13635@mail.ntua.gr> | 2019-06-10 19:40:31 +0300 |
commit | 2b6d1e0dbf47750ee4377d532fb6b38496e4b336 (patch) | |
tree | 4d0dbb939d66ececb4629c00caa5f301d9930098 | |
parent | b617fc013681f3c2a9b6f49fa6e2af8261bf99c7 (diff) |
Run clippy lints
29 files changed, 860 insertions, 655 deletions
diff --git a/melib/src/async.rs b/melib/src/async.rs index b9ba191f..627ed6bd 100644 --- a/melib/src/async.rs +++ b/melib/src/async.rs @@ -58,6 +58,12 @@ pub struct Async<T> { rx: chan::Receiver<AsyncStatus>, } +impl Default for AsyncBuilder { + fn default() -> Self { + AsyncBuilder::new() + } +} + impl AsyncBuilder { pub fn new() -> Self { let (sender, receiver) = chan::sync(::std::mem::size_of::<AsyncStatus>()); @@ -117,6 +123,6 @@ impl<T> Async<T> { } let v = self.worker.take().unwrap().join().unwrap(); self.value = Some(v); - return Ok(AsyncStatus::Finished); + Ok(AsyncStatus::Finished) } } diff --git a/melib/src/mailbox/backends/maildir.rs b/melib/src/mailbox/backends/maildir.rs index 2863ca89..a045d267 100644 --- a/melib/src/mailbox/backends/maildir.rs +++ b/melib/src/mailbox/backends/maildir.rs @@ -19,15 +19,14 @@ * along with meli. If not, see <http://www.gnu.org/licenses/>. */ -extern crate xdg; extern crate bincode; +extern crate xdg; use async::*; use conf::AccountSettings; use error::{MeliError, Result}; use mailbox::backends::{ - BackendFolder, BackendOp, Folder, MailBackend, RefreshEvent, - RefreshEventConsumer, + BackendFolder, BackendOp, Folder, MailBackend, RefreshEvent, RefreshEventConsumer, }; use mailbox::email::parser; use mailbox::email::{Envelope, Flag}; @@ -46,11 +45,11 @@ extern crate crossbeam; use memmap::{Mmap, Protection}; use std::collections::hash_map::DefaultHasher; use std::fs; +use std::hash::{Hash, Hasher}; use std::io; use std::io::Read; -use std::sync::{Mutex, Arc}; -use std::hash::{Hasher, Hash}; use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; extern crate fnv; use self::fnv::FnvHashMap; @@ -66,7 +65,7 @@ impl Clone for MaildirOp { fn clone(&self) -> Self { MaildirOp { hash_index: self.hash_index.clone(), - hash: self.hash.clone(), + hash: self.hash, slice: None, } } @@ -89,7 +88,7 @@ impl MaildirOp { impl<'a> BackendOp for MaildirOp { fn description(&self) -> String { - format!("Path of file:")// self.0ipath) + format!("Path of file: {}", self.path()) } fn as_bytes(&mut self) -> Result<&[u8]> { if self.slice.is_none() { @@ -133,10 +132,10 @@ impl<'a> BackendOp for MaildirOp { fn set_flag(&mut self, envelope: &mut Envelope, f: &Flag) -> Result<()> { let path = self.path(); - let idx: usize = path.rfind(":2,").ok_or(MeliError::new(format!( - "Invalid email filename: {:?}", - self - )))? + 3; + let idx: usize = path + .rfind(":2,") + .ok_or_else(|| MeliError::new(format!("Invalid email filename: {:?}", self)))? + + 3; let mut new_name: String = path[..idx].to_string(); let mut flags = self.fetch_flags(); if !(flags & *f).is_empty() { @@ -212,24 +211,24 @@ impl MailBackend for MaildirType { match rx.recv() { Ok(event) => match event { DebouncedEvent::Create(mut pathbuf) - | DebouncedEvent::Remove(mut pathbuf) => { - if pathbuf.is_dir() { - if pathbuf.ends_with("cur") | pathbuf.ends_with("new") { - pathbuf.pop(); - } - } else { - pathbuf.pop(); + | DebouncedEvent::Remove(mut pathbuf) => { + if pathbuf.is_dir() { + if pathbuf.ends_with("cur") | pathbuf.ends_with("new") { pathbuf.pop(); - }; - eprintln!(" got event in {}", pathbuf.display()); + } + } else { + pathbuf.pop(); + pathbuf.pop(); + }; + eprintln!(" got event in {}", pathbuf.display()); - let mut hasher = DefaultHasher::new(); - pathbuf.hash(&mut hasher); - sender.send(RefreshEvent { - folder: format!("{}", pathbuf.display()), - hash: hasher.finish(), - }); - } + let mut hasher = DefaultHasher::new(); + pathbuf.hash(&mut hasher); + sender.send(RefreshEvent { + folder: format!("{}", pathbuf.display()), + hash: hasher.finish(), + }); + } _ => {} }, Err(e) => eprintln!("watch error: {:?}", e), @@ -261,7 +260,7 @@ impl MaildirType { path.to_str().unwrap().to_string(), path.file_name().unwrap().to_str().unwrap().to_string(), path_children, - ) { + ) { folders.push(f); children.push(folders.len() - 1); } @@ -277,7 +276,7 @@ impl MaildirType { path.to_str().unwrap().to_string(), path.file_name().unwrap().to_str().unwrap().to_string(), Vec::with_capacity(0), - ) { + ) { folders.push(f); } } @@ -285,7 +284,10 @@ impl MaildirType { MaildirType { name: f.name().to_string(), folders, - hash_index: Arc::new(Mutex::new(FnvHashMap::with_capacity_and_hasher(0, Default::default()))), + hash_index: Arc::new(Mutex::new(FnvHashMap::with_capacity_and_hasher( + 0, + Default::default(), + ))), path: f.root_folder().to_string(), } } @@ -342,28 +344,33 @@ impl MaildirType { let s = scope.builder().name(name.clone()).spawn(move || { let len = chunk.len(); let size = if len <= 100 { 100 } else { (len / 100) * 100 }; - let mut local_r: Vec<Envelope> = Vec::with_capacity(chunk.len()); + let mut local_r: Vec< + Envelope, + > = Vec::with_capacity(chunk.len()); for c in chunk.chunks(size) { let map = map.clone(); let len = c.len(); for file in c { - let ri = file.rfind("/").unwrap() + 1; + let ri = file.rfind('/').unwrap() + 1; let file_name = &file[ri..]; - if let Some(cached) = cache_dir.find_cache_file(file_name) { + if let Some(cached) = + cache_dir.find_cache_file(file_name) + { // TODO:: error checking - let reader = io::BufReader::new(fs::File::open(cached).unwrap()); + let reader = io::BufReader::new( + fs::File::open(cached).unwrap(), + ); let env: Envelope = bincode::deserialize_from(reader).unwrap(); - { - let mut map = map.lock().unwrap(); - let hash = env.hash(); - if (*map).contains_key(&hash) { - continue; - } - (*map).insert(hash, (0, file.to_string())); - local_r.push(env); + { + let mut map = map.lock().unwrap(); + let hash = env.hash(); + if (*map).contains_key(&hash) { continue; } - + (*map).insert(hash, (0, file.to_string())); + local_r.push(env); + continue; + } } let e_copy = file.to_string(); /* @@ -376,41 +383,48 @@ impl MaildirType { */ { let mut hasher = DefaultHasher::new(); - let hash = { - let mut buf = Vec::new(); - let mut f = fs::File::open(&e_copy).expect(&format!("Can't open {}", e_copy)); - f.read_to_end(&mut buf).expect(&format!("Can't read {}", e_copy)); - /* Unwrap is safe since we use ? above. */ - hasher.write(&buf); - hasher.finish() - }; - { - let mut map = map.lock().unwrap(); - if (*map).contains_key(&hash) { - continue; - } - (*map).insert(hash, (0, e_copy)); - } - // TODO: Check cache - let op = Box::new(MaildirOp::new(hash, map.clone())); - if let Some(mut e) = Envelope::from_token(op, hash) { - if let Ok(cached) = cache_dir.place_cache_file(file_name) { - let f = match fs::File::create(cached) { - Ok(f) => f, - Err(e) => { - panic!("{}",e); - } + let hash = { + let mut buf = Vec::new(); + let mut f = fs::File::open(&e_copy) + .unwrap_or_else(|_| { + panic!("Can't open {}", e_copy) + }); + f.read_to_end(&mut buf).unwrap_or_else(|_| { + panic!("Can't read {}", e_copy) + }); + /* Unwrap is safe since we use ? above. */ + hasher.write(&buf); + hasher.finish() }; - let writer = io::BufWriter::new(f); - bincode::serialize_into(writer, &e).unwrap(); - } - local_r.push(e); - - - } else { + { + let mut map = map.lock().unwrap(); + if (*map).contains_key(&hash) { continue; } - + (*map).insert(hash, (0, e_copy)); + } + // TODO: Check cache + let op = + Box::new(MaildirOp::new(hash, map.clone())); + if let Some(mut e) = Envelope::from_token(op, hash) + { + if let Ok(cached) = + cache_dir.place_cache_file(file_name) + { + let f = match fs::File::create(cached) { + Ok(f) => f, + Err(e) => { + panic!("{}", e); + } + }; + let writer = io::BufWriter::new(f); + bincode::serialize_into(writer, &e) + .unwrap(); + } + local_r.push(e); + } else { + continue; + } } } tx.send(AsyncStatus::ProgressReport(len)); @@ -429,16 +443,15 @@ impl MaildirType { for (idx, e) in r.iter().enumerate() { let mut y = (*map)[&e.hash()].clone(); y.0 = idx; - (*map).insert(e.hash(),y); + (*map).insert(e.hash(), y); } tx.send(AsyncStatus::Finished); Ok(r) }) - .unwrap() + .unwrap() }; w.build(handle) } - } #[derive(Debug, Default)] @@ -459,7 +472,7 @@ impl MaildirFolder { hash: h.finish(), name: file_name, path: pathbuf, - children: children, + children, }; ret.is_valid()?; Ok(ret) @@ -474,9 +487,9 @@ impl MaildirFolder { p.push(d); if !p.is_dir() { return Err(MeliError::new(format!( - "{} is not a valid maildir folder", - path.display() - ))); + "{} is not a valid maildir folder", + path.display() + ))); } p.pop(); } diff --git a/melib/src/mailbox/backends/mod.rs b/melib/src/mailbox/backends/mod.rs index 31f93c9c..bd3205c7 100644 --- a/melib/src/mailbox/backends/mod.rs +++ b/melib/src/mailbox/backends/mod.rs @@ -44,6 +44,12 @@ pub struct Backends { map: FnvHashMap<std::string::String, Box<Fn() -> BackendCreator>>, } +impl Default for Backends { + fn default() -> Self { + Backends::new() + } +} + impl Backends { pub fn new() -> Self { let mut b = Backends { diff --git a/melib/src/mailbox/email/attachment_types.rs b/melib/src/mailbox/email/attachment_types.rs index d4c3c770..e4946955 100644 --- a/melib/src/mailbox/email/attachment_types.rs +++ b/melib/src/mailbox/email/attachment_types.rs @@ -1,5 +1,5 @@ -use mailbox::email::parser::BytesExt; use mailbox::email::attachments::Attachment; +use mailbox::email::parser::BytesExt; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::str; @@ -20,13 +20,11 @@ impl SliceBuild { //fn length(&self) -> usize { // self.end - self.offset + 1 //} - pub fn get<'a>(&self, slice:&'a [u8]) -> &'a [u8] { + pub fn get<'a>(&self, slice: &'a [u8]) -> &'a [u8] { &slice[self.offset..self.end] } } - - #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub enum Charset { Ascii, @@ -72,7 +70,7 @@ impl<'a> From<&'a [u8]> for Charset { _ => { eprintln!("unknown tag is {:?}", str::from_utf8(b)); Charset::Ascii - }, + } } } } @@ -102,10 +100,19 @@ impl Display for MultipartType { #[derive(Clone, Debug, Serialize, Deserialize)] pub enum ContentType { - Text { kind: Text, charset: Charset }, - Multipart { boundary: SliceBuild, kind: MultipartType, subattachments: Vec<Attachment>}, + Text { + kind: Text, + charset: Charset, + }, + Multipart { + boundary: SliceBuild, + kind: MultipartType, + subattachments: Vec<Attachment>, + }, MessageRfc822, - Unsupported { tag: Vec<u8> }, + Unsupported { + tag: Vec<u8>, + }, } impl Default for ContentType { @@ -137,7 +144,10 @@ impl ContentType { } } pub fn is_text_html(&self) -> bool { - if let ContentType::Text { kind: Text::Html, .. } = self { + if let ContentType::Text { + kind: Text::Html, .. + } = self + { true } else { false diff --git a/melib/src/mailbox/email/attachments.rs b/melib/src/mailbox/email/attachments.rs index e050c72a..6ce3d13b 100644 --- a/melib/src/mailbox/email/attachments.rs +++ b/melib/src/mailbox/email/attachments.rs @@ -19,9 +19,9 @@ * along with meli. If not, see <http://www.gnu.org/licenses/>. */ use data_encoding::BASE64_MIME; -use mailbox::email::EnvelopeWrapper; use mailbox::email::parser; use mailbox::email::parser::BytesExt; +use mailbox::email::EnvelopeWrapper; use std::fmt; use std::str; @@ -84,7 +84,7 @@ impl AttachmentBuilder { let offset = (_boundary.as_ptr() as usize).wrapping_sub(value.as_ptr() as usize); let boundary = SliceBuild::new(offset, _boundary.len()); let subattachments = Self::subattachments(&self.raw, boundary.get(&value)); - assert!(subattachments.len() > 0); + assert!(!subattachments.is_empty()); self.content_type = ContentType::Multipart { boundary, kind: if cst.eq_ignore_ascii_case(b"mixed") { @@ -96,7 +96,7 @@ impl AttachmentBuilder { } else { Default::default() }, - subattachments + subattachments, }; } else if ct.eq_ignore_ascii_case(b"text") { self.content_type = ContentType::Text { @@ -105,28 +105,28 @@ impl AttachmentBuilder { }; for (n, v) in params { if n.eq_ignore_ascii_case(b"charset") { - match self.content_type { - ContentType::Text { charset: ref mut c, .. } => { - *c = Charset::from(v); - }, - _ => {}, + if let ContentType::Text { + charset: ref mut c, .. + } = self.content_type + { + *c = Charset::from(v); } - break; + break; } } if cst.eq_ignore_ascii_case(b"html") { - match self.content_type { - ContentType::Text { kind: ref mut k, .. } => { - *k = Text::Html; - }, - _ => {}, + if let ContentType::Text { + kind: ref mut k, .. + } = self.content_type + { + *k = Text::Html; } } else if !cst.eq_ignore_ascii_case(b"plain") { - match self.content_type { - ContentType::Text { kind: ref mut k, .. } => { - *k = Text::Other { tag: cst.into() }; - }, - _ => {}, + if let ContentType::Text { + kind: ref mut k, .. + } = self.content_type + { + *k = Text::Other { tag: cst.into() }; } } } else if ct.eq_ignore_ascii_case(b"message") && cst.eq_ignore_ascii_case(b"rfc822") { @@ -136,9 +136,7 @@ impl AttachmentBuilder { tag.extend(ct); tag.push(b'/'); tag.extend(cst); - self.content_type = ContentType::Unsupported { - tag - }; + self.content_type = ContentType::Unsupported { tag }; }, Err(v) => { eprintln!("parsing error in content_type: {:?} {:?}", value, v); @@ -197,8 +195,7 @@ impl AttachmentBuilder { } pub fn subattachments(raw: &[u8], boundary: &[u8]) -> Vec<Attachment> { - match parser::attachments(raw, boundary).to_full_result() - { + match parser::attachments(raw, boundary).to_full_result() { Ok(attachments) => { let mut vec = Vec::with_capacity(attachments.len()); for a in attachments { @@ -246,37 +243,29 @@ impl AttachmentBuilder { impl fmt::Display for Attachment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.content_type { - ContentType::MessageRfc822 => { - match EnvelopeWrapper::new(self.bytes().to_vec()) { - Ok(wrapper) => write!(f, "message/rfc822: {} - {} - {}", wrapper.date(), wrapper.from_to_string(), wrapper.subject()), - Err(e) => write!(f, "{}", e), - } + ContentType::MessageRfc822 => match EnvelopeWrapper::new(self.bytes().to_vec()) { + Ok(wrapper) => write!( + f, + "message/rfc822: {} - {} - {}", + wrapper.date(), + wrapper.field_from_to_string(), + wrapper.subject() + ), + Err(e) => write!(f, "{}", e), }, ContentType::Unsupported { .. } => { write!(f, "Data attachment of type {}", self.mime_type()) } - ContentType::Text { .. } => { - write!(f, "Text attachment of type {}", self.mime_type()) - } + ContentType::Text { .. } => write!(f, "Text attachment of type {}", self.mime_type()), ContentType::Multipart { - kind: ref multipart_type, subattachments: ref sub_att_vec, .. - } => if *multipart_type == MultipartType::Alternative { - write!( - f, - "{} attachment with {} subs", - self.mime_type(), - sub_att_vec.len() - ) - } else { - write!( - f, - "{} attachment with {} subs", - self.mime_type(), - sub_att_vec.len() - ) - }, + } => write!( + f, + "{} attachment with {} subs", + self.mime_type(), + sub_att_vec.len() + ), } } } @@ -297,20 +286,23 @@ impl Attachment { } => match *multipart_type { MultipartType::Alternative => { for a in sub_att_vec { - if let ContentType::Text { kind: Text::Plain, .. } = a.content_type { + if let ContentType::Text { + kind: Text::Plain, .. + } = a.content_type + { a.get_text_recursive(text); break; } } - }, + } MultipartType::Mixed | MultipartType::Digest => { for a in sub_att_vec { a.get_text_recursive(text); text.extend_from_slice(b"\n\n"); } - }, - } - _ => {}, + } + }, + _ => {} } } pub fn text(&self) -> String { @@ -356,7 +348,9 @@ impl Attachment { } pub fn is_html(&self) -> bool { match self.content_type { - ContentType::Text { kind: Text::Html, .. } => true, + ContentType::Text { + kind: Text::Html, .. + } => true, _ => false, } } @@ -369,13 +363,13 @@ pub fn interpret_format_flowed(_t: &str) -> String { fn decode_rfc822(_raw: &[u8]) -> Attachment { let builder = AttachmentBuilder::new(b""); - return builder.build(); + builder.build() /* - eprintln!("raw is\n{:?}", str::from_utf8(raw).unwrap()); + eprintln!("raw is\n{:?}", str::from_utf8(raw).unwrap()); let e = match Envelope::from_bytes(raw) { Some(e) => e, - None => { + None => { eprintln!("error in parsing mail"); let error_msg = b"Mail cannot be shown because of errors."; let mut builder = AttachmentBuilder::new(error_msg); @@ -384,10 +378,11 @@ fn decode_rfc822(_raw: &[u8]) -> Attachment { }; e.body(None) */ - } -fn decode_rec_helper(a: &Attachment, filter: &Option<Box<Fn(&Attachment, &mut Vec<u8>) -> ()>>) -> Vec<u8> { +type Filter = Box<Fn(&Attachment, &mut Vec<u8>) -> ()>; + +fn decode_rec_helper(a: &Attachment, filter: &Option<Filter>) -> Vec<u8> { let mut ret = match a.content_type { ContentType::Unsupported { .. } => Vec::new(), ContentType::Text { .. } => decode_helper(a, filter), @@ -398,7 +393,10 @@ fn decode_rec_helper(a: &Attachment, filter: &Option<Box<Fn(&Attachment, &mut Ve .. } => if *multipart_type == MultipartType::Alternative { for a in sub_att_vec { - if let ContentType::Text { kind: Text::Plain, .. } = a.content_type { + if let ContentType::Text { + kind: Text::Plain, .. + } = a.content_type + { return decode_helper(a, filter); } } @@ -417,10 +415,10 @@ fn decode_rec_helper(a: &Attachment, filter: &Option<Box<Fn(&Attachment, &mut Ve } ret } -pub fn decode_rec(a: &Attachment, filter: Option<Box<Fn(&Attachment, &mut Vec<u8>) -> ()>>) -> Vec<u8> { +pub fn decode_rec(a: &Attachment, filter: Option<Filter>) -> Vec<u8> { decode_rec_helper(a, &filter) } -fn decode_helper(a: &Attachment, filter: &Option<Box<Fn(&Attachment, &mut Vec<u8>) -> ()>>) -> Vec<u8> { +fn decode_helper(a: &Attachment, filter: &Option<Filter>) -> Vec<u8> { let charset = match a.content_type { ContentType::Text { charset: c, .. } => c, _ => Default::default(), @@ -449,12 +447,11 @@ fn decode_helper(a: &Attachment, filter: &Option<Box<Fn(&Attachment, &mut Vec<u8 bytes.to_vec() }; if let Some(filter) = filter { - filter(a, &mut ret); + filter(a, &mut ret); } ret - } -pub fn decode(a: &Attachment, filter: Option<Box<Fn(&Attachment, &mut Vec<u8>) -> ()>>) -> Vec<u8> { +pub fn decode(a: &Attachment, filter: Option<Filter>) -> Vec<u8> { decode_helper(a, &filter) } diff --git a/melib/src/mailbox/email/mod.rs b/melib/src/mailbox/email/mod.rs index 481c8f88..37a5c937 100644 --- a/melib/src/mailbox/email/mod.rs +++ b/ |