From 31193c2bef934d26265673c91cbea0b64a53cd15 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Mon, 23 Dec 2019 12:51:54 +0100 Subject: Run cargo-fmt on codebase Signed-off-by: Matthias Beyer --- core/examples/readme.rs | 18 +- core/src/compose.rs | 118 ++-- core/src/context.rs | 207 +++--- core/src/default_impl/cpupool.rs | 27 +- core/src/default_impl/fs.rs | 153 ++--- core/src/default_impl/message_id_gen.rs | 46 +- core/src/default_impl/mod.rs | 17 +- core/src/default_impl/simple_context.rs | 30 +- core/src/encode.rs | 128 ++-- core/src/error.rs | 37 +- core/src/iri.rs | 75 +- core/src/lib.rs | 45 +- core/src/macros.rs | 37 +- core/src/mail.rs | 300 ++++---- core/src/mime.rs | 34 +- core/src/resource/data.rs | 122 ++-- core/src/resource/loading.rs | 68 +- core/src/resource/mod.rs | 22 +- core/src/resource/source.rs | 25 +- core/src/test_utils.rs | 10 +- core/src/utils.rs | 14 +- core/tests/mail.rs | 2 +- core/tests/resource/load_file.rs | 40 +- core/tests/resource/mod.rs | 1 - headers/src/convert.rs | 10 +- headers/src/data/inner_item.rs | 130 ++-- headers/src/data/input.rs | 93 ++- headers/src/data/mod.rs | 2 +- headers/src/data/simple_item.rs | 74 +- headers/src/error.rs | 61 +- headers/src/header.rs | 65 +- headers/src/header_components/cfws.rs | 14 +- headers/src/header_components/date_time.rs | 52 +- headers/src/header_components/disposition.rs | 131 ++-- headers/src/header_components/email.rs | 210 +++--- headers/src/header_components/file_meta.rs | 26 +- headers/src/header_components/mailbox.rs | 136 ++-- headers/src/header_components/mailbox_list.rs | 70 +- headers/src/header_components/media_type.rs | 152 ++--- headers/src/header_components/message_id.rs | 243 ++++--- headers/src/header_components/mod.rs | 8 +- headers/src/header_components/path.rs | 31 +- headers/src/header_components/phrase.rs | 79 +-- headers/src/header_components/phrase_list.rs | 60 +- headers/src/header_components/raw_unstructured.rs | 29 +- headers/src/header_components/received_token.rs | 61 +- headers/src/header_components/transfer_encoding.rs | 49 +- headers/src/header_components/unstructured.rs | 79 +-- headers/src/header_components/utils/mod.rs | 55 +- .../src/header_components/utils/text_partition.rs | 27 +- headers/src/header_components/word.rs | 204 +++--- headers/src/header_macro.rs | 3 +- headers/src/headers.rs | 39 +- headers/src/lib.rs | 21 +- headers/src/macros.rs | 54 +- headers/src/map/into_iter.rs | 7 +- headers/src/map/mod.rs | 283 ++++---- headers/src/name.rs | 76 ++- internals/src/bind/base64.rs | 112 ++- internals/src/bind/encoded_word/impls.rs | 77 ++- internals/src/bind/encoded_word/mod.rs | 47 +- internals/src/bind/idna.rs | 44 +- internals/src/bind/mime.rs | 27 +- internals/src/bind/mod.rs | 6 +- internals/src/bind/quoted_printable.rs | 143 ++-- internals/src/bind/quoted_string.rs | 23 +- internals/src/encoder/encodable.rs | 59 +- internals/src/encoder/mod.rs | 751 +++++++++++---------- internals/src/encoder/trace.rs | 30 +- internals/src/error.rs | 58 +- internals/src/grammar.rs | 128 ++-- internals/src/lib.rs | 18 +- internals/src/macros.rs | 38 +- internals/src/mail_type.rs | 7 +- internals/src/utils/mod.rs | 38 +- mail/examples/mail_by_hand.rs | 17 +- mail/examples/mail_from_template/main.rs | 29 +- mail/examples/send_mail/cli.rs | 48 +- mail/examples/send_mail/main.rs | 50 +- mail/src/lib.rs | 48 +- smtp/src/error.rs | 21 +- smtp/src/lib.rs | 25 +- smtp/src/request.rs | 176 ++--- smtp/src/resolve_all.rs | 40 +- smtp/src/send_mail.rs | 100 +-- template/src/additional_cid.rs | 37 +- template/src/base_dir.rs | 46 +- template/src/error.rs | 2 +- template/src/handlebars.rs | 70 +- template/src/lib.rs | 202 +++--- template/src/path_rebase.rs | 81 ++- template/src/serde_impl.rs | 197 +++--- 92 files changed, 3304 insertions(+), 3701 deletions(-) diff --git a/core/examples/readme.rs b/core/examples/readme.rs index 5e0cd42..7f2c0ed 100644 --- a/core/examples/readme.rs +++ b/core/examples/readme.rs @@ -6,24 +6,17 @@ extern crate mail_internals; #[macro_use] extern crate mail_headers; -use std::str; use futures::Future; +use std::str; use mail_internals::MailType; // In the facade this is the `headers` module. -use mail_headers::{ - headers::*, - header_components::Domain -}; +use mail_headers::{header_components::Domain, headers::*}; // In the facade this types (and the default_impl module) // are also exposed at top level -use mail_core::{ - Mail, - default_impl::simple_context, - error::MailError -}; +use mail_core::{default_impl::simple_context, error::MailError, Mail}; fn print_some_mail() -> Result<(), MailError> { // Domain will implement `from_str` in the future, @@ -43,7 +36,8 @@ fn print_some_mail() -> Result<(), MailError> { // We don't added any think which needs loading but we could have // and all of it would have been loaded concurrent and async. - let encoded = mail.into_encodable_mail(ctx.clone()) + let encoded = mail + .into_encodable_mail(ctx.clone()) .wait()? .encode_into_bytes(MailType::Ascii)?; @@ -54,4 +48,4 @@ fn print_some_mail() -> Result<(), MailError> { fn main() { print_some_mail().unwrap() -} \ No newline at end of file +} diff --git a/core/src/compose.rs b/core/src/compose.rs index 1334a22..e69317b 100644 --- a/core/src/compose.rs +++ b/core/src/compose.rs @@ -17,23 +17,15 @@ // in the later part of the file for better readability. || //-------------------------------------------------------------// -use media_type::{MULTIPART, ALTERNATIVE, RELATED, MIXED}; +use media_type::{ALTERNATIVE, MIXED, MULTIPART, RELATED}; use vec1::Vec1; use headers::{ - HeaderKind, - headers, - header_components::{ - Disposition, - DispositionKind, - MediaType - } + header_components::{Disposition, DispositionKind, MediaType}, + headers, HeaderKind, }; -use crate::{ - mail::Mail, - resource::Resource -}; +use crate::{mail::Mail, resource::Resource}; /// Parts used to create a mail body (in a multipart mail). /// @@ -45,7 +37,6 @@ use crate::{ /// by it's content id. #[derive(Debug)] pub struct BodyPart { - /// A body created by a template. pub resource: Resource, @@ -68,8 +59,7 @@ pub struct BodyPart { /// Attachments of a `BodyPart` instance will be combined with /// the attachments of other instances and the ones in the /// `MailParts` instance. - pub attachments: Vec - + pub attachments: Vec, } /// Parts which can be used to compose a multipart mail. @@ -116,17 +106,14 @@ pub struct MailParts { pub inline_embeddings: Vec, /// A number of embeddings which should be treated as attachments - pub attachments: Vec + pub attachments: Vec, } //-------------------------------------------------------\\ // implementations for creating mails are from here on || //-------------------------------------------------------// - impl MailParts { - - /// Create a `Mail` instance based on this `MailParts` instance. /// /// @@ -151,57 +138,52 @@ impl MailParts { /// Each sub-body created for a `BodyPart` will be wrapped /// inside a `multipart/related` if it has body specific /// embeddings (with content disposition inline). - pub fn compose(self) - -> Mail - { + pub fn compose(self) -> Mail { let MailParts { alternative_bodies, inline_embeddings, - attachments + attachments, } = self; - let mut attachments = attachments.into_iter() + let mut attachments = attachments + .into_iter() .map(|atta| atta.create_mail_with_disposition(DispositionKind::Attachment)) .collect::>(); - let mut alternatives = alternative_bodies.into_iter() + let mut alternatives = alternative_bodies + .into_iter() .map(|body| body.create_mail(&mut attachments)) .collect::>(); //UNWRAP_SAFE: bodies is Vec1, i.e. we have at last one let mail = alternatives.pop().unwrap(); - let mail = - if alternatives.is_empty() { - mail - } else { - mail.wrap_with_alternatives(alternatives) - }; + let mail = if alternatives.is_empty() { + mail + } else { + mail.wrap_with_alternatives(alternatives) + }; - let mail = - if inline_embeddings.is_empty() { - mail - } else { - let related = inline_embeddings.into_iter() - .map(|embedding| { - embedding.create_mail_with_disposition(DispositionKind::Inline) - }) - .collect::>(); - mail.wrap_with_related(related) - }; + let mail = if inline_embeddings.is_empty() { + mail + } else { + let related = inline_embeddings + .into_iter() + .map(|embedding| embedding.create_mail_with_disposition(DispositionKind::Inline)) + .collect::>(); + mail.wrap_with_related(related) + }; - let mail = - if attachments.is_empty() { - mail - } else { - mail.wrap_with_mixed(attachments) - }; + let mail = if attachments.is_empty() { + mail + } else { + mail.wrap_with_mixed(attachments) + }; mail } } impl BodyPart { - /// Creates a `Mail` instance from this `BodyPart` instance. /// /// All embeddings in `BodyPart.embeddings` which have a @@ -215,14 +197,11 @@ impl BodyPart { /// have a `Inline` disposition that body will be /// wrapped into a `multipart/related` body containing /// them. - pub fn create_mail( - self, - attachments_out: &mut Vec, - ) -> Mail { + pub fn create_mail(self, attachments_out: &mut Vec) -> Mail { let BodyPart { resource, inline_embeddings, - attachments + attachments, } = self; let body = resource.create_mail(); @@ -235,10 +214,9 @@ impl BodyPart { if inline_embeddings.is_empty() { body } else { - let related = inline_embeddings.into_iter() - .map(|embedding| { - embedding.create_mail_with_disposition(DispositionKind::Inline) - }) + let related = inline_embeddings + .into_iter() + .map(|embedding| embedding.create_mail_with_disposition(DispositionKind::Inline)) .collect::>(); body.wrap_with_related(related) } @@ -246,7 +224,6 @@ impl BodyPart { } impl Resource { - /// Create a `Mail` instance representing this `Resource`. /// /// This is not a complete mail, i.e. it will not contain @@ -268,15 +245,12 @@ impl Resource { } impl Mail { - /// Create a `multipart/mixed` `Mail` instance containing this mail as /// first body and one additional body for each attachment. /// /// Normally this is used with embeddings having a attachment /// disposition creating a mail with attachments. - pub fn wrap_with_mixed(self, other_bodies: Vec) - -> Mail - { + pub fn wrap_with_mixed(self, other_bodies: Vec) -> Mail { let mut bodies = other_bodies; bodies.push(self); new_multipart(&MIXED, bodies) @@ -291,9 +265,7 @@ impl Mail { /// specified by `multipart/alternative`. /// This also means that _this_ body will be the last body as it is /// meant to be the _main_ body. - pub fn wrap_with_alternatives(self, alternates: Vec) - -> Mail - { + pub fn wrap_with_alternatives(self, alternates: Vec) -> Mail { let mut bodies = alternates; //TODO[opt] accept iter and prepend instead of insert in vec bodies.insert(0, self); @@ -302,14 +274,11 @@ impl Mail { /// Creates a `multipart/related` `Mail` instance containing this /// mail first and then all related bodies. - pub fn wrap_with_related(self, related: Vec) - -> Mail - { + pub fn wrap_with_related(self, related: Vec) -> Mail { let mut bodies = related; bodies.insert(0, self); new_multipart(&RELATED, bodies) } - } /// Creates a `multipart/` mail with given bodies. @@ -318,10 +287,7 @@ impl Mail { /// /// If `sub_type` can not be used to create a multipart content /// type this will panic. -fn new_multipart(sub_type: &'static str, bodies: Vec) - -> Mail -{ - let content_type = MediaType::new(MULTIPART, sub_type) - .unwrap(); +fn new_multipart(sub_type: &'static str, bodies: Vec) -> Mail { + let content_type = MediaType::new(MULTIPART, sub_type).unwrap(); Mail::new_multipart_mail(content_type, bodies) -} \ No newline at end of file +} diff --git a/core/src/context.rs b/core/src/context.rs index 88f1045..d776da5 100644 --- a/core/src/context.rs +++ b/core/src/context.rs @@ -1,44 +1,46 @@ //! Provides the context needed for building/encoding mails. -use std::sync::Arc; use std::fmt::Debug; +use std::sync::Arc; -use futures::{ future::{self, Either}, Future, IntoFuture }; +use futures::{ + future::{self, Either}, + Future, IntoFuture, +}; use utils::SendBoxFuture; -use headers::header_components::{ - MessageId, ContentId -}; +use headers::header_components::{ContentId, MessageId}; use crate::{ - resource::{Source, Data, EncData, Resource}, - error::ResourceLoadingError + error::ResourceLoadingError, + resource::{Data, EncData, Resource, Source}, }; - /// Represents Data which might already have been transfer encoded. pub enum MaybeEncData { /// The data is returned normally. Data(Data), /// The data is returned in a already transfer encoded variant. - EncData(EncData) + EncData(EncData), } impl MaybeEncData { - pub fn to_resource(self) -> Resource { match self { MaybeEncData::Data(data) => Resource::Data(data), - MaybeEncData::EncData(enc_data) => Resource::EncData(enc_data) + MaybeEncData::EncData(enc_data) => Resource::EncData(enc_data), } } - pub fn encode(self, ctx: &impl Context) - -> impl Future - { + pub fn encode( + self, + ctx: &impl Context, + ) -> impl Future { match self { - MaybeEncData::Data(data) => Either::A(ctx.load_transfer_encoded_resource(&Resource::Data(data))), - MaybeEncData::EncData(enc) => Either::B(future::ok(enc)) + MaybeEncData::Data(data) => { + Either::A(ctx.load_transfer_encoded_resource(&Resource::Data(data))) + } + MaybeEncData::EncData(enc) => Either::B(future::ok(enc)), } } } @@ -76,8 +78,6 @@ impl MaybeEncData { /// implementor to have a outer+inner type where the inner type is wrapped /// into a `Arc` e.g. `struct SomeCtx { inner: Arc }`. pub trait Context: Debug + Clone + Send + Sync + 'static { - - /// Loads and transfer encodes a `Data` instance. /// /// This is called when a `Mail` instance is converted into @@ -98,8 +98,7 @@ pub trait Context: Debug + Clone + Send + Sync + 'static { /// This function should not block and schedule the encoding /// in some other place e.g. by using the contexts offload /// functionality. - fn load_resource(&self, source: &Source) - -> SendBoxFuture; + fn load_resource(&self, source: &Source) -> SendBoxFuture; /// Loads and Transfer encodes a `Resource` instance. /// @@ -124,9 +123,10 @@ pub trait Context: Debug + Clone + Send + Sync + 'static { /// This function should not block and schedule the encoding /// in some other place e.g. by using the contexts offload /// functionality. - fn load_transfer_encoded_resource(&self, resource: &Resource) - -> SendBoxFuture - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ) -> SendBoxFuture { default_impl_for_load_transfer_encoded_resource(self, resource) } @@ -161,60 +161,56 @@ pub trait Context: Debug + Clone + Send + Sync + 'static { //TODO[futures/v>=0.2]: integrate this with Context /// offloads the execution of the future `fut` to somewhere else e.g. a cpu pool fn offload(&self, fut: F) -> SendBoxFuture - where F: Future + Send + 'static, - F::Item: Send + 'static, - F::Error: Send + 'static; + where + F: Future + Send + 'static, + F::Item: Send + 'static, + F::Error: Send + 'static; //TODO[futures/v>=0.2]: integrate this with Context /// offloads the execution of the function `func` to somewhere else e.g. a cpu pool - fn offload_fn(&self, func: FN ) -> SendBoxFuture - where FN: FnOnce() -> I + Send + 'static, - I: IntoFuture + 'static, - I::Future: Send + 'static, - I::Item: Send + 'static, - I::Error: Send + 'static + fn offload_fn(&self, func: FN) -> SendBoxFuture + where + FN: FnOnce() -> I + Send + 'static, + I: IntoFuture + 'static, + I::Future: Send + 'static, + I::Item: Send + 'static, + I::Error: Send + 'static, { - self.offload( future::lazy( func ) ) + self.offload(future::lazy(func)) } } - /// Provides the default impl for the `load_transfer_encoded_resource` method of `Context`. /// /// This function guarantees to only call `load_resource` and `offload`/`offload_fn` on the /// passed in context, to prevent infinite recursion. -pub fn default_impl_for_load_transfer_encoded_resource(ctx: &impl Context, resource: &Resource) - -> SendBoxFuture -{ +pub fn default_impl_for_load_transfer_encoded_resource( + ctx: &impl Context, + resource: &Resource, +) -> SendBoxFuture { match resource { Resource::Source(source) => { let ctx2 = ctx.clone(); - let fut = ctx.load_resource(&source) - .and_then(move |me_data| { - match me_data { - MaybeEncData::Data(data) => { - Either::A(ctx2.offload_fn(move || Ok(data.transfer_encode(Default::default())))) - }, - MaybeEncData::EncData(enc_data) => { - Either::B(future::ok(enc_data)) - } - } + let fut = ctx + .load_resource(&source) + .and_then(move |me_data| match me_data { + MaybeEncData::Data(data) => Either::A( + ctx2.offload_fn(move || Ok(data.transfer_encode(Default::default()))), + ), + MaybeEncData::EncData(enc_data) => Either::B(future::ok(enc_data)), }); Box::new(fut) - }, + } Resource::Data(data) => { let data = data.clone(); ctx.offload_fn(move || Ok(data.transfer_encode(Default::default()))) - }, - Resource::EncData(enc_data) => { - Box::new(future::ok(enc_data.clone())) } + Resource::EncData(enc_data) => Box::new(future::ok(enc_data.clone())), } } /// Trait needed to be implemented for providing the resource loading parts to a`CompositeContext`. pub trait ResourceLoaderComponent: Debug + Send + Sync + 'static { - /// Calls to `Context::load_resource` will be forwarded to this method. /// /// It is the same as `Context::load_resource` except that a reference @@ -222,8 +218,11 @@ pub trait ResourceLoaderComponent: Debug + Send + Sync + 'static { /// infinite recursion the `Context.load_resource` method _must not_ /// be called. Additionally the `Context.load_transfer_encoded_resource` _must not_ /// be called if it uses `Context.load_resource`. - fn load_resource(&self, source: &Source, ctx: &impl Context) - -> SendBoxFuture; + fn load_resource( + &self, + source: &Source, + ctx: &impl Context, + ) -> SendBoxFuture; /// Calls to `Context::transfer_encode_resource` will be forwarded to this method. /// @@ -233,21 +232,23 @@ pub trait ResourceLoaderComponent: Debug + Send + Sync + 'static { /// /// To prevent infinite recursion the `load_transfer_encoded_resource` method /// of the context _must not_ be called. - fn load_transfer_encoded_resource(&self, resource: &Resource, ctx: &impl Context) - -> SendBoxFuture - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ctx: &impl Context, + ) -> SendBoxFuture { default_impl_for_load_transfer_encoded_resource(ctx, resource) } } /// Trait needed to be implemented for providing the offloading parts to a `CompositeContext`. pub trait OffloaderComponent: Debug + Send + Sync + 'static { - /// Calls to `Context::offload` and `Context::offload_fn` will be forwarded to this method. fn offload(&self, fut: F) -> SendBoxFuture - where F: Future + Send + 'static, - F::Item: Send+'static, - F::Error: Send+'static; + where + F: Future + Send + 'static, + F::Item: Send + 'static, + F::Error: Send + 'static; } /// Trait needed to be implemented for providing the id generation parts to a `CompositeContext`. @@ -258,7 +259,6 @@ pub trait OffloaderComponent: Debug + Send + Sync + 'static { /// more important for an message id to be "world unique" then for an content id, /// expect in some cases where external bodies are used). pub trait MailIdGenComponent: Debug + Send + Sync + 'static { - /// Calls to `Context::generate_message_id` will be forwarded to this method. fn generate_message_id(&self) -> MessageId; @@ -283,15 +283,16 @@ pub trait MailIdGenComponent: Debug + Send + Sync + 'static { pub struct CompositeContext< R: ResourceLoaderComponent, O: OffloaderComponent, - M: MailIdGenComponent ->{ + M: MailIdGenComponent, +> { inner: Arc<(R, O, M)>, } impl Clone for CompositeContext - where R: ResourceLoaderComponent, - O: OffloaderComponent, - M: MailIdGenComponent +where + R: ResourceLoaderComponent, + O: OffloaderComponent, + M: MailIdGenComponent, { fn clone(&self) -> Self { CompositeContext { @@ -301,9 +302,10 @@ impl Clone for CompositeContext } impl CompositeContext - where R: ResourceLoaderComponent, - O: OffloaderComponent, - M: MailIdGenComponent +where + R: ResourceLoaderComponent, + O: OffloaderComponent, + M: MailIdGenComponent, { /// Create a new context from the given components. pub fn new(resource_loader: R, offloader: O, message_id_gen: M) -> Self { @@ -329,27 +331,28 @@ impl CompositeContext } impl Context for CompositeContext - where R: ResourceLoaderComponent, - O: OffloaderComponent, - M: MailIdGenComponent +where + R: ResourceLoaderComponent, + O: OffloaderComponent, + M: MailIdGenComponent, { - - fn load_resource(&self, source: &Source) - -> SendBoxFuture - { + fn load_resource(&self, source: &Source) -> SendBoxFuture { self.resource_loader().load_resource(source, self) } - fn load_transfer_encoded_resource(&self, resource: &Resource) - -> SendBoxFuture - { - self.resource_loader().load_transfer_encoded_resource(resource, self) + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ) -> SendBoxFuture { + self.resource_loader() + .load_transfer_encoded_resource(resource, self) } fn offload(&self, fut: F) -> SendBoxFuture - where F: Future + Send + 'static, - F::Item: Send+'static, - F::Error: Send+'static + where + F: Future + Send + 'static, + F::Item: Send + 'static, + F::Error: Send + 'static, { self.offloader().offload(fut) } @@ -361,12 +364,12 @@ impl Context for CompositeContext fn generate_message_id(&self) -> MessageId { self.id_gen().generate_message_id() } - } /// Allows using a part of an context as an component. impl MailIdGenComponent for C - where C: Context +where + C: Context, { fn generate_message_id(&self) -> MessageId { ::generate_message_id(self) @@ -379,12 +382,14 @@ impl MailIdGenComponent for C /// Allows using a part of an context as an component. impl OffloaderComponent for C - where C: Context +where + C: Context, { fn offload(&self, fut: F) -> SendBoxFuture - where F: Future + Send + 'static, - F::Item: Send+'static, - F::Error: Send+'static + where + F: Future + Send + 'static, + F::Item: Send + 'static, + F::Error: Send + 'static, { ::offload(self, fut) } @@ -392,18 +397,22 @@ impl OffloaderComponent for C /// Allows using a part of an context as an component. impl ResourceLoaderComponent for C - where C: Context +where + C: Context, { - - fn load_resource(&self, source: &Source, _: &impl Context) - -> SendBoxFuture - { + fn load_resource( + &self, + source: &Source, + _: &impl Context, + ) -> SendBoxFuture { ::load_resource(self, source) } - fn load_transfer_encoded_resource(&self, resource: &Resource, _: &impl Context) - -> SendBoxFuture - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + _: &impl Context, + ) -> SendBoxFuture { ::load_transfer_encoded_resource(self, resource) } -} \ No newline at end of file +} diff --git a/core/src/default_impl/cpupool.rs b/core/src/default_impl/cpupool.rs index de02deb..87cb5e5 100644 --- a/core/src/default_impl/cpupool.rs +++ b/core/src/default_impl/cpupool.rs @@ -1,8 +1,7 @@ - use futures::Future; use utils::SendBoxFuture; -use futures_cpupool::{ CpuPool, Builder}; +use futures_cpupool::{Builder, CpuPool}; use context::OffloaderComponent; @@ -18,30 +17,32 @@ pub fn simple_cpu_pool() -> CpuPool { impl OffloaderComponent for CpuPool { /// executes the futures `fut` "elswhere" e.g. in a cpu pool fn offload(&self, fut: F) -> SendBoxFuture - where F: Future + Send + 'static, - F::Item: Send+'static, - F::Error: Send+'static + where + F: Future + Send + 'static, + F::Item: Send + 'static, + F::Error: Send + 'static, { - Box::new( self.spawn( fut ) ) + Box::new(self.spawn(fut)) } } - #[cfg(test)] mod test { + use super::*; use futures::future; use futures_cpupool::Builder; - use super::*; #[test] fn check_if_it_works() { let pool = Builder::new().create(); - _check_if_it_works( pool ) + _check_if_it_works(pool) } fn _check_if_it_works(r: R) { - let res = r.offload(future::lazy(||-> Result { Ok(33u32) } )).wait(); - let val = assert_ok!( res ); - assert_eq!( 33u32, val ); + let res = r + .offload(future::lazy(|| -> Result { Ok(33u32) })) + .wait(); + let val = assert_ok!(res); + assert_eq!(33u32, val); } -} \ No newline at end of file +} diff --git a/core/src/default_impl/fs.rs b/core/src/default_impl/fs.rs index bab8af7..44e5c47 100644 --- a/core/src/default_impl/fs.rs +++ b/core/src/default_impl/fs.rs @@ -1,41 +1,23 @@ use std::{ - path::{Path, PathBuf}, + env, fs::{self, File}, io::{self, Read}, - env, marker::PhantomData, + path::{Path, PathBuf}, }; use checked_command::CheckedCommand; use failure::Fail; use futures::IntoFuture; -use headers::header_components::{ - MediaType, - FileMeta -}; +use headers::header_components::{FileMeta, MediaType}; use crate::{ + context::{Context, MaybeEncData, ResourceLoaderComponent}, + error::{ResourceLoadingError, ResourceLoadingErrorKind}, iri::IRI, - utils::{ - SendBoxFuture, - ConstSwitch, Enabled - }, - error::{ - ResourceLoadingError, - ResourceLoadingErrorKind - }, - resource:: { - Data, - Source, - UseMediaType, - Metadata - }, - context::{ - Context, - ResourceLoaderComponent, - MaybeEncData - } + resource::{Data, Metadata, Source, UseMediaType}, + utils::{ConstSwitch, Enabled, SendBoxFuture}, }; // have a scheme ignoring variant for Mux as the scheme is preset @@ -47,29 +29,31 @@ use crate::{ /// load a resource from a file based on a scheme tail as path independent of the rest, /// so e.g. it it is used in a `Mux` which selects a `ResourceLoader` impl based on a scheme /// the scheme would not be double validated. -#[derive( Debug, Clone, PartialEq, Default )] -pub struct FsResourceLoader< - SchemeValidation: ConstSwitch = Enabled, -> { +#[derive(Debug, Clone, PartialEq, Default)] +pub struct FsResourceLoader { root: PathBuf, scheme: &'static str, - _marker: PhantomData + _marker: PhantomData, } impl FsResourceLoader - where SVSw: ConstSwitch +where + SVSw: ConstSwitch, { - const DEFAULT_SCHEME: &'static str = "path"; /// create a new file system based FileLoader, which will "just" standard _blocking_ IO /// to read a file from the file system into a buffer - pub fn new>( root: P ) -> Self { + pub fn new>(root: P) -> Self { Self::new_with_scheme(root.into(), Self::DEFAULT_SCHEME) } - pub fn new_with_scheme>( root: P, scheme: &'static str ) -> Self { - FsResourceLoader { root: root.into(), scheme, _marker: PhantomData} + pub fn new_with_scheme>(root: P, scheme: &'static str) -> Self { + FsResourceLoader { + root: root.into(), + scheme, + _marker: PhantomData, + } } pub fn with_cwd_root() -> Result { @@ -94,17 +78,17 @@ impl FsResourceLoader } } - impl ResourceLoaderComponent for FsResourceLoader - where ValidateScheme: ConstSwitch +where + ValidateScheme: ConstSwitch, { - - fn load_resource(&self, source: &Source, ctx: &impl Context) - -> SendBoxFuture - { + fn load_resource( + &self, + source: &Source, + ctx: &impl Context, + ) -> SendBoxFuture { if ValidateScheme::ENABLED && !self.iri_has_compatible_scheme(&source.iri) { - let err = ResourceLoadingError - ::from(ResourceLoadingErrorKind::NotFound) + let err = ResourceLoadingError::from(ResourceLoadingErrorKind::NotFound) .with_source_iri_or_else(|| Some(source.iri.clone())); return Box::new(Err(err).into_future()); @@ -114,17 +98,14 @@ impl ResourceLoaderComponent for FsResourceLoader( ctx: &impl Context, post_process: F, ) -> SendBoxFuture - where R: Send + 'static, - F: FnOnce(Data) -> Result + Send + 'static +where + R: Send + 'static, + F: FnOnce(Data) -> Result + Send + 'static, { let content_id = ctx.generate_content_id(); ctx.offload_fn(move || { - let mut fd = File::open(&path) - .map_err(|err| { - if err.kind() == io::ErrorKind::NotFound { - err.context(ResourceLoadingErrorKind::NotFound) - } else { - err.context(ResourceLoadingErrorKind::LoadingFailed) - } - })?; + let mut fd = File::open(&path).map_err(|err| { + if err.kind() == io::ErrorKind::NotFound { + err.context(ResourceLoadingErrorKind::NotFound) + } else { + err.context(ResourceLoadingErrorKind::LoadingFailed) + } + })?; let mut file_meta = file_meta_from_metadata(fd.metadata()?); if let Some(name) = use_file_name { file_meta.file_name = Some(name) } else { - file_meta.file_name = path.file_name() + file_meta.file_name = path + .file_name() .map(|name| name.to_string_lossy().into_owned()) } let mut buffer = Vec::new(); fd.read_to_end(&mut buffer)?; - let media_type = - match use_media_type { - UseMediaType::Auto => { - sniff_media_type(&path)? - }, - UseMediaType::Default(media_type) => { - media_type - } - }; - - let data = Data::new(buffer, Metadata { - file_meta, - content_id, - media_type, - }); + let media_type = match use_media_type { + UseMediaType::Auto => sniff_media_type(&path)?, + UseMediaType::Default(media_type) => media_type, + }; + + let data = Data::new( + buffer, + Metadata { + file_meta, + content_id, + media_type, + }, + ); post_process(data) }) - } fn sniff_media_type(path: impl AsRef) -> Result { //TODO replace current impl with conservative sniffing - let output = CheckedCommand - ::new("file") + let output = CheckedCommand::new("file") .args(&["--brief", "--mime"]) .arg(path.as_ref()) .output() .map_err(|err| err.context(ResourceLoadingErrorKind::MediaTypeDetectionFailed))?; - let raw_media_type = String - ::from_utf8(output.stdout) + let raw_media_type = String::from_utf8(output.stdout) .map_err(|err| err.context(ResourceLoadingErrorKind::MediaTypeDetectionFailed))?; - let media_type = MediaType - ::parse(raw_media_type.trim()) + let media_type = MediaType::parse(raw_media_type.trim()) .map_err(|err| err.context(ResourceLoadingErrorKind::MediaTypeDetectionFailed))?; Ok(media_type) @@ -212,7 +188,7 @@ fn file_meta_from_metadata(meta: fs::Metadata) -> FileMeta { modification_date: meta.modified().ok().map(From::from), read_date: meta.accessed().ok().map(From::from), //TODO make FileMeta.size a u64 - size: get_file_size(&meta).map(|x|x as usize), + size: get_file_size(&meta).map(|x| x as usize), } } @@ -241,22 +217,19 @@ fn path_from_tail(path_iri: &IRI) -> &Path { Path::new(path) } - #[cfg(test)] mod tests { - mod sniff_media_type { use super::super::*; #[test] fn works_reasonable_for_cargo_files() { - let res = sniff_media_type("./Cargo.toml") - .unwrap(); + let res = sniff_media_type("./Cargo.toml").unwrap(); // it currently doesn't take advantage of file endings so // all pure "text" will be text/plain assert_eq!(res.as_str_repr(), "text/plain; charset=us-ascii"); } } -} \ No newline at end of file +} diff --git a/core/src/default_impl/message_id_gen.rs b/core/src/default_impl/message_id_gen.rs index ca46b2b..671b2b3 100644 --- a/core/src/default_impl/message_id_gen.rs +++ b/core/src/default_impl/message_id_gen.rs @@ -1,14 +1,13 @@ -use std::sync::atomic::{AtomicUsize, Ordering}; use std::collections::hash_map::DefaultHasher; use std::hash::Hasher; +use std::sync::atomic::{AtomicUsize, Ordering}; use rand; use soft_ascii_string::SoftAsciiString; +use context::MailIdGenComponent; +use headers::header_components::{ContentId, Domain, MessageId}; use internals::error::EncodingError; -use headers::header_components::{MessageId, ContentId, Domain}; -use ::context::MailIdGenComponent; - static MAIL_COUNTER: AtomicUsize = AtomicUsize::new(0); @@ -32,12 +31,10 @@ fn gen_next_program_unique_number() -> u64 { #[derive(Debug, Clone)] pub struct HashedIdGen { domain: SoftAsciiString, - part_unique_in_domain: SoftAsciiString + part_unique_in_domain: SoftAsciiString, } impl HashedIdGen { - - /// create a new id gen from a `Domain` and a unique part. /// /// The domain is used as the right hand side of the message @@ -75,31 +72,32 @@ impl HashedIdGen { /// /// The other problem is solved by hashing the counter with /// a random part. - pub fn new(domain: Domain, part_unique_in_domain: SoftAsciiString) - -> Result - { + pub fn new( + domain: Domain, + part_unique_in_domain: SoftAsciiString, + ) -> Result { let domain = domain.into_ascii_string()?; Ok(HashedIdGen { domain, - part_unique_in_domain + part_unique_in_domain, }) } } impl MailIdGenComponent for HashedIdGen { - fn generate_message_id(&self) -> MessageId { - let msg_id = format!("{unique}.{hash:x}@{domain}", - unique=self.part_unique_in_domain, - hash=gen_next_program_unique_number(), - domain=self.domain); + let msg_id = format!( + "{unique}.{hash:x}@{domain}", + unique = self.part_unique_in_domain, + hash = gen_next_program_unique_number(), + domain = self.domain + ); MessageId::from_unchecked(msg_id) } fn generate_content_id(&self) -> ContentId { - self.generate_message_id().into() + self.generate_message_id().into() } - } #[cfg(test)] @@ -108,16 +106,16 @@ mod test { mod HashedIdGen { #![allow(non_snake_case)] - use std::sync::Arc; - use std::collections::HashSet; - use soft_ascii_string::SoftAsciiString; use headers::header_components::Domain; use headers::HeaderTryFrom; + use soft_ascii_string::SoftAsciiString; + use std::collections::HashSet; + use std::sync::Arc; //NOTE: this is a rust bug, the import is not unused - #[allow(unused_imports)] - use ::context::MailIdGenComponent; use super::super::HashedIdGen; + #[allow(unused_imports)] + use context::MailIdGenComponent; fn setup() -> Arc { let unique_part = SoftAsciiString::from_unchecked("bfr7tz4"); @@ -151,4 +149,4 @@ mod test { } } } -} \ No newline at end of file +} diff --git a/core/src/default_impl/mod.rs b/core/src/default_impl/mod.rs index 6e5398b..06fdb3a 100644 --- a/core/src/default_impl/mod.rs +++ b/core/src/default_impl/mod.rs @@ -2,9 +2,9 @@ //! //! For example it provides a default implementation for the context needed //! to build/encode a mail. -#[cfg(feature="default_impl_cpupool")] +#[cfg(feature = "default_impl_cpupool")] mod cpupool; -#[cfg(feature="default_impl_cpupool")] +#[cfg(feature = "default_impl_cpupool")] pub use self::cpupool::*; mod fs; @@ -13,17 +13,16 @@ pub use self::fs::*; mod message_id_gen; pub use self::message_id_gen::*; - -#[cfg(all(feature="default_impl_cpupool"))] +#[cfg(all(feature = "default_impl_cpupool"))] pub mod simple_context; -#[cfg(all(test, not(feature="default_impl_cpupool")))] +#[cfg(all(test, not(feature = "default_impl_cpupool")))] compile_error!("test need following (default) features: default_impl_cpupool, default_impl_fs, default_impl_message_id_gen"); -#[cfg(test)] -use soft_ascii_string::SoftAsciiString; #[cfg(test)] use headers::header_components::Domain; +#[cfg(test)] +use soft_ascii_string::SoftAsciiString; #[cfg(test)] pub type TestContext = simple_context::Context; @@ -36,7 +35,3 @@ pub fn test_context() -> TestContext { let unique_part = SoftAsciiString::from_unchecked("CM0U3c412"); simple_context::new(domain, unique_part).unwrap() } - - - - diff --git a/core/src/default_impl/simple_context.rs b/core/src/default_impl/simple_context.rs index 53d941d..47337a7 100644 --- a/core/src/default_impl/simple_context.rs +++ b/core/src/default_impl/simple_context.rs @@ -28,14 +28,14 @@ //! use std::io; -use soft_ascii_string::SoftAsciiString; use futures_cpupool::{Builder, CpuPool}; +use soft_ascii_string::SoftAsciiString; -use internals::error::EncodingError; use headers::header_components::Domain; +use internals::error::EncodingError; -use ::context::CompositeContext; -use ::default_impl::{FsResourceLoader, HashedIdGen}; +use context::CompositeContext; +use default_impl::{FsResourceLoader, HashedIdGen}; /// Error returned when creating a "simple_context" fails. #[derive(Debug, Fail)] @@ -43,12 +43,12 @@ pub enum ContextSetupError { /// Reading the env variables failed. /// /// (Mainly getting the current working dir failed). - #[fail(display="{}", _0)] + #[fail(display = "{}", _0)] ReadingEnv(io::Error), /// Punny encoding a non us-ascii domain failed. - #[fail(display="{}", _0)] - PunyCodingDomain(EncodingError) + #[fail(display = "{}", _0)] + PunyCodingDomain(EncodingError), } /// Type Alias for a the type returned by `simple_context::new`. @@ -67,19 +67,13 @@ pub type Context = CompositeContext; /// under any circumstances (expect if they use different domains, but then you /// also should only use domain you actually own). pub fn new(domain: Domain, unique_part: SoftAsciiString) -> Result { - let resource_loader = FsResourceLoader - ::with_cwd_root() - .map_err(|err| ContextSetupError::ReadingEnv(err))?; + let resource_loader = + FsResourceLoader::with_cwd_root().map_err(|err| ContextSetupError::ReadingEnv(err))?; let cpu_pool = Builder::new().create(); - let id_gen = HashedIdGen - ::new(domain, unique_part) + let id_gen = HashedIdGen::new(domain, unique_part) .map_err(|err| ContextSetupError::PunyCodingDomain(err))?; - Ok(CompositeContext::new( - resource_loader, - cpu_pool, - id_gen, - )) -} \ No newline at end of file + Ok(CompositeContext::new(resource_loader, cpu_pool, id_gen)) +} diff --git a/core/src/encode.rs b/core/src/encode.rs index 1ea34c0..1a1c5c5 100644 --- a/core/src/encode.rs +++ b/core/src/encode.rs @@ -1,33 +1,20 @@ -use soft_ascii_string::{ - SoftAsciiStr, - SoftAsciiChar, - SoftAsciiString -}; use media_type::BOUNDARY; +use soft_ascii_string::{SoftAsciiChar, SoftAsciiStr, SoftAsciiString}; -use internals::{ - encoder::{ - EncodingBuffer, EncodingWriter, - }, - error::{EncodingError, EncodingErrorKind, Place, UTF_8, US_ASCII} -}; use headers::{ - HeaderName, - HeaderObj, HeaderObjTrait, - HeaderKind, - headers::{ContentTransferEncoding, ContentType} + headers::{ContentTransferEncoding, ContentType}, + HeaderKind, HeaderName, HeaderObj, HeaderObjTrait, +}; +use internals::{ + encoder::{EncodingBuffer, EncodingWriter}, + error::{EncodingError, EncodingErrorKind, Place, US_ASCII, UTF_8}, }; -use ::{ +use { error::MailError, - mail::{ - Mail, - EncodableMail, - assume_encoded - } + mail::{assume_encoded, EncodableMail, Mail}, }; - /// /// # Panics /// if the body is not yet resolved use `Body::poll_body` or `IntoFuture` @@ -37,25 +24,20 @@ use ::{ pub(crate) fn encode_mail( mail: &EncodableMail, top: bool, - encoder: &mut EncodingBuffer + encoder: &mut EncodingBuffer, ) -> Result<(), MailError> { - _encode_mail(&*mail, top, encoder) - .map_err(|err| { - let mail_type = encoder.mail_type(); - use self::MailError::*; - - match err { - Encoding(enc_err) => Encoding(enc_err.with_mail_type_or_else(||Some(mail_type))), - other => other - } - }) + _encode_mail(&*mail, top, encoder).map_err(|err| { + let mail_type = encoder.mail_type(); + use self::MailError::*; + + match err { + Encoding(enc_err) => Encoding(enc_err.with_mail_type_or_else(|| Some(mail_type))), + other => other, + } + }) } -fn _encode_mail( - mail: &Mail, - top: bool, - encoder: &mut EncodingBuffer -) -> Result<(), MailError> { +fn _encode_mail(mail: &Mail, top: bool, encoder: &mut EncodingBuffer) -> Result<(), MailError> { encode_headers(&mail, top, encoder)?; //the empty line between the headers and the body @@ -71,35 +53,30 @@ fn _encode_mail( /// if the body is not yet resolved use `Body::poll_body` or `IntoFuture` /// on `Mail` to prevent this from happening /// -fn encode_headers( - mail: &Mail, - top: bool, - encoder: &mut EncodingBuffer -) -> Result<(), MailError> { +fn encode_headers(mail: &Mail, top: bool, encoder: &mut EncodingBuffer) -> Result<(), MailError> { use super::MailBody::*; let mut handle = encoder.writer(); if top { - handle.write_str(SoftAsciiStr::from_unchecked( - "MIME-Version: 1.0" - ))?; + handle.write_str(SoftAsciiStr::from_unchecked("MIME-Version: 1.0"))?; handle.finish_header(); } for (name, hbody) in mail.headers().iter() { let name_as_str = name.as_str(); - let ignored_header = !top && - !(name_as_str.starts_with("Content-") - || name_as_str.starts_with("X-") ); + let ignored_header = + !top && !(name_as_str.starts_with("Content-") || name_as_str.starts_with("X-")); if ignored_header { - warn!("non `Content-` header in MIME body: {:?}: {:?}", name, hbody); + warn!( + "non `Content-` header in MIME body: {:?}: {:?}", + name, hbody + ); } encode_header(&mut handle, name, hbody)?; } - match mail.body() { SingleBody { ref body } => { let data = assume_encoded(body); @@ -107,8 +84,11 @@ fn encode_headers( encode_header(&mut handle, header.name(), &header)?; let header = ContentType::body(data.media_type().clone()); encode_header(&mut handle, header.name(), &header)?; - }, - MultipleBodies { hidden_text:_, bodies:_ } => {} + } + MultipleBodies { + hidden_text: _, + bodies: _, + } => {} } Ok(()) } @@ -116,7 +96,7 @@ fn encode_headers( fn encode_header( handle: &mut EncodingWriter, name: HeaderName, - header: &HeaderObj + header: &HeaderObj, ) -> Result<(), EncodingError> { //FIXME[rust/catch] use catch block let res = (|| -> Result<(), EncodingError> { @@ -129,7 +109,11 @@ fn encode_header( })(); res.map_err(|err| { - err.with_place_or_else(|| Some(Place::Header { name: name.as_str() })) + err.with_place_or_else(|| { + Some(Place::Header { + name: name.as_str(), + }) + }) }) } @@ -138,9 +122,7 @@ fn encode_header( /// if the body is not yet resolved use `Body::poll_body` or `IntoFuture` /// on `Mail` to prevent this from happening /// -fn encode_mail_part(mail: &Mail, encoder: &mut EncodingBuffer ) - -> Result<(), MailError> -{ +fn encode_mail_part(mail: &Mail, encoder: &mut EncodingBuffer) -> Result<(), MailError> { use super::MailBody::*; let minus = SoftAsciiChar::from_unchecked('-'); @@ -150,8 +132,11 @@ fn encode_mail_part(mail: &Mail, encoder: &mut EncodingBuffer ) let data = assume_encoded(body); let buffer = data.transfer_encoded_buffer(); encoder.write_body_unchecked(buffer); - }, - MultipleBodies { ref hidden_text, ref bodies } => { + } + MultipleBodies { + ref hidden_text, + ref bodies, + } => { if hidden_text.len() > 0 { //TODO find out if there is any source using the hidden text // (e.g. for some form of validation, prove of senders validity etc.) @@ -160,7 +145,8 @@ fn encode_mail_part(mail: &Mail, encoder: &mut EncodingBuffer ) } let mail_was_validated_err_msg = "[BUG] mail was already validated"; - let boundary = mail.headers() + let boundary = mail + .headers() .get_single(ContentType) .expect(mail_was_validated_err_msg) .expect(mail_was_validated_err_msg) @@ -168,16 +154,18 @@ fn encode_mail_part(mail: &Mail, encoder: &mut EncodingBuffer ) .expect(mail_was_validated_err_msg) .to_content(); - let boundary = SoftAsciiString - ::from_string(boundary) - .map_err(|orig_string| EncodingError - ::from(EncodingErrorKind::InvalidTextEncoding { - got_encoding: UTF_8, - expected_encoding: US_ASCII + let boundary = SoftAsciiString::from_string(boundary).map_err(|orig_string| { + EncodingError::from(EncodingErrorKind::InvalidTextEncoding { + got_encoding: UTF_8, + expected_encoding: US_ASCII, + }) + .with_place_or_else(|| { + Some(Place::Header { + name: "Content-Type", }) - .with_place_or_else(|| Some(Place::Header { name: "Content-Type" })) - .with_str_context(orig_string.into_source()) - )?; + }) + .with_str_context(orig_string.into_source()) + })?; for mail in bodies.iter() { encoder.write_header_line(|handle| { diff --git a/core/src/error.rs b/core/src/error.rs index 9f787c4..44f0225 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -2,15 +2,13 @@ use std::fmt::{self, Display}; use std::io; -use failure::{Fail, Context, Backtrace}; +use failure::{Backtrace, Context, Fail}; -use internals::error::EncodingError; use headers::error::{ - BuildInValidationError, - HeaderTypeError, ComponentCreationError, - HeaderValidationError + BuildInValidationError, ComponentCreationError, HeaderTypeError, HeaderValidationError, }; -use ::IRI; +use internals::error::EncodingError; +use IRI; // errors from loading a Resource (which includes encoding it's body) // / NotFound | IRI (no Backtrace neede) \ MailError::ResourceLoading // ResourceError < LoadingFailed | chain Error / @@ -31,7 +29,7 @@ pub enum ResourceError { /// resources to not be re-encoded every time they are /// used. #[fail(display = "{}", _0)] - Encoding(EncodingError) + Encoding(EncodingError), } impl From for ResourceError { @@ -58,14 +56,14 @@ pub enum ResourceLoadingErrorKind { LoadingFailed, #[fail(display = "automatically detecting the media type failed")] - MediaTypeDetectionFailed + MediaTypeDetectionFailed, } /// The loading of an Resource failed. #[derive(Debug)] pub struct ResourceLoadingError { inner: Context, - iri: Option + iri: Option, } impl Display for ResourceLoadingError { @@ -85,7 +83,6 @@ impl Fail for ResourceLoadingError { } impl ResourceLoadingError { - /// The kind of error which caused the loading to fail. pub fn kind(&self) -> ResourceLoadingErrorKind { *self.inner.get_context() @@ -98,7 +95,8 @@ impl ResourceLoadingError { /// Sets the source IRI if not already set and returns self. pub fn with_source_iri_or_else(mut self, func: F) -> Self - where F: FnOnce() -> Option + where + F: FnOnce() -> Option, { if self.iri.is_none() { self.iri = func(); @@ -139,9 +137,7 @@ impl From<(Option, ResourceLoadingErrorKind)> for ResourceLoadingError { impl From<(Option, Context)> for ResourceLoadingError { fn from((iri, inner): (Option, Context)) -> Self { - ResourceLoadingError { - inner, iri - } + ResourceLoadingError { inner, iri } } } @@ -151,7 +147,6 @@ impl From for ResourceLoadingError { } } - #[derive(Debug, Fail)] pub enum OtherValidationError { /// Non-multipart mail headers derive the Content-Type header from it's body `Resource`. @@ -182,7 +177,7 @@ pub enum OtherValidationError { /// A mail (top level, not in multipart) requires a `From` header to be given. #[fail(display = "mail did not contain a From header")] - NoFrom + NoFrom, } impl From for HeaderValidationError { @@ -227,7 +222,7 @@ pub enum MailError { /// E.g. the file to attach or the image to embedded could not /// be found. #[fail(display = "{}", _0)] - ResourceLoading(ResourceLoadingError) + ResourceLoading(ResourceLoadingError), } impl From for MailError { @@ -248,7 +243,6 @@ impl From for MailError { } } - impl From for MailError { fn from(err: HeaderValidationError) -> Self { MailError::Validation(err) @@ -265,7 +259,7 @@ impl From for MailError { fn from(err: ResourceError) -> Self { match err { ResourceError::Loading(err) => MailError::ResourceLoading(err), - ResourceError::Encoding(err) => MailError::Encoding(err) + ResourceError::Encoding(err) => MailError::Encoding(err), } } } @@ -276,7 +270,6 @@ impl From for MailError { } } - /// Error returned when trying to _unload_ and `Resource` and it fails. #[derive(Copy, Clone, Debug, Fail)] pub enum ResourceNotUnloadableError { @@ -289,5 +282,5 @@ pub enum ResourceNotUnloadableError { /// that unloading is just for thinks like caching, it doesn't affect /// the deletion/dropping of `Resource` instances. #[fail(display = "resource has no source, can't unload it")] - NoSource -} \ No newline at end of file + NoSource, +} diff --git a/core/src/iri.rs b/core/src/iri.rs index 33ba4a0..b225fcf 100644 --- a/core/src/iri.rs +++ b/core/src/iri.rs @@ -1,14 +1,12 @@ -use std::{ - str::FromStr -}; +use std::str::FromStr; -#[cfg(feature="serde")] -use std::fmt; -#[cfg(feature="serde")] +#[cfg(feature = "serde")] use serde::{ + de::{self, Deserialize, Deserializer, Visitor}, ser::{Serialize, Serializer}, - de::{self, Deserialize, Deserializer, Visitor} }; +#[cfg(feature = "serde")] +use std::fmt; //TODO consider adding a str_context #[derive(Copy, Clone, Debug, Fail)] @@ -35,11 +33,10 @@ pub struct InvalidIRIScheme; #[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] pub struct IRI { iri: String, - scheme_end_idx: usize + scheme_end_idx: usize, } impl IRI { - /// Create a new IRI from a scheme part and a tail part. /// /// This will convert the scheme part into lower case before @@ -56,7 +53,7 @@ impl IRI { buffer.push_str(tail); Ok(IRI { iri: buffer, - scheme_end_idx: scheme_len + scheme_end_idx: scheme_len, }) } @@ -68,10 +65,13 @@ impl IRI { /// (or `"+"`,`"-"`,`"."`). /// 3. converts the scheme part to lower case pub fn new(iri: I) -> Result - where I: Into + where + I: Into, { let mut buffer = iri.into(); - let split_pos = buffer.bytes().position(|b| b == b':') + let split_pos = buffer + .bytes() + .position(|b| b == b':') //TODO error type .ok_or_else(|| InvalidIRIScheme)?; { @@ -85,16 +85,19 @@ impl IRI { Ok(IRI { iri: buffer, - scheme_end_idx: split_pos + scheme_end_idx: split_pos, }) } fn validate_scheme(scheme: &str) -> Result<(), InvalidIRIScheme> { let mut iter = scheme.bytes(); - let valid = iter.next() - .map(|bch| bch.is_ascii_alphabetic()).unwrap_or(false) - && iter.all(|bch| - bch.is_ascii_alphanumeric() || bch == b'+' || bch == b'-' || bch == b'.'); + let valid = iter + .next() + .map(|bch| bch.is_ascii_alphabetic()) + .unwrap_or(false) + && iter.all(|bch| { + bch.is_ascii_alphanumeric() || bch == b'+' || bch == b'-' || bch == b'.' + }); if !valid { return Err(InvalidIRIScheme); @@ -104,8 +107,7 @@ impl IRI { /// Creates a new IRI with the same schema but a different tail. pub fn with_tail(&self, new_tail: &str) -> Self { - IRI::from_parts(self.scheme(), new_tail) - .unwrap() + IRI::from_parts(self.scheme(), new_tail).unwrap() } /// The scheme part of the uri excluding the `:` seperator. @@ -133,7 +135,7 @@ impl IRI { /// assert_eq!(uri.scheme(), "file"); /// ``` pub fn tail(&self) -> &str { - &self.iri[self.scheme_end_idx+1..] + &self.iri[self.scheme_end_idx + 1..] } /// returns the underlying string representation @@ -161,20 +163,21 @@ impl Into for IRI { } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] impl Serialize for IRI { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { serializer.serialize_str(self.as_str()) } } -#[cfg(feature="serde")] +#[cfg(feature = "serde")] impl<'de> Deserialize<'de> for IRI { - fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> + where + D: Deserializer<'de>, { struct IRIVisitor; impl<'de> Visitor<'de> for IRIVisitor { @@ -188,8 +191,7 @@ impl<'de> Deserialize<'de> for IRI { where E: de::Error, { - let iri = s.parse() - .map_err(|err| E::custom(err))?; + let iri = s.parse().map_err(|err| E::custom(err))?; Ok(iri) } @@ -233,7 +235,6 @@ mod test { assert!(IRI::new("c1+-.:is valid").is_ok()); } - #[test] fn scheme_is_always_lower_case() { let iri = IRI::new("FoO:bAr").unwrap(); @@ -254,23 +255,17 @@ mod test { assert_eq!(iri.as_str(), "foo:bar/bazz"); } - #[cfg(feature="serde")] + #[cfg(feature = "serde")] #[test] fn serde_works_for_str_iri() { - use serde_test::{Token, assert_tokens, assert_de_tokens}; + use serde_test::{assert_de_tokens, assert_tokens, Token}; let iri: IRI = "path:./my/joke.txt".parse().unwrap(); - assert_tokens(&iri, &[ - Token::Str("path:./my/joke.txt") - ]); + assert_tokens(&iri, &[Token::Str("path:./my/joke.txt")]); - assert_de_tokens(&iri, &[ - Token::String("path:./my/joke.txt"), - ]); + assert_de_tokens(&iri, &[Token::String("path:./my/joke.txt")]); - assert_de_tokens(&iri, &[ - Token::BorrowedStr("path:./my/joke.txt"), - ]); + assert_de_tokens(&iri, &[Token::BorrowedStr("path:./my/joke.txt")]); } -} \ No newline at end of file +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 1378a45..b1b5d8b 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -4,61 +4,56 @@ //! and the `Resource` type, which is used to represent mail bodies. //! Especially such which are attachments or embedded images. //! -#![recursion_limit="128"] +#![recursion_limit = "128"] #[macro_use] extern crate log; #[macro_use] extern crate failure; -extern crate media_type; +extern crate checked_command; extern crate chrono; extern crate futures; -extern crate rand; -extern crate vec1; -extern crate soft_ascii_string; -extern crate checked_command; #[cfg_attr(test, macro_use)] extern crate mail_headers as headers; extern