diff options
Diffstat (limited to 'core')
-rw-r--r-- | core/examples/readme.rs | 18 | ||||
-rw-r--r-- | core/src/compose.rs | 118 | ||||
-rw-r--r-- | core/src/context.rs | 207 | ||||
-rw-r--r-- | core/src/default_impl/cpupool.rs | 27 | ||||
-rw-r--r-- | core/src/default_impl/fs.rs | 153 | ||||
-rw-r--r-- | core/src/default_impl/message_id_gen.rs | 46 | ||||
-rw-r--r-- | core/src/default_impl/mod.rs | 17 | ||||
-rw-r--r-- | core/src/default_impl/simple_context.rs | 30 | ||||
-rw-r--r-- | core/src/encode.rs | 128 | ||||
-rw-r--r-- | core/src/error.rs | 37 | ||||
-rw-r--r-- | core/src/iri.rs | 75 | ||||
-rw-r--r-- | core/src/lib.rs | 45 | ||||
-rw-r--r-- | core/src/macros.rs | 37 | ||||
-rw-r--r-- | core/src/mail.rs | 300 | ||||
-rw-r--r-- | core/src/mime.rs | 34 | ||||
-rw-r--r-- | core/src/resource/data.rs | 122 | ||||
-rw-r--r-- | core/src/resource/loading.rs | 68 | ||||
-rw-r--r-- | core/src/resource/mod.rs | 22 | ||||
-rw-r--r-- | core/src/resource/source.rs | 25 | ||||
-rw-r--r-- | core/src/test_utils.rs | 10 | ||||
-rw-r--r-- | core/src/utils.rs | 14 | ||||
-rw-r--r-- | core/tests/mail.rs | 2 | ||||
-rw-r--r-- | core/tests/resource/load_file.rs | 40 | ||||
-rw-r--r-- | core/tests/resource/mod.rs | 1 |
24 files changed, 695 insertions, 881 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<Resource> - + pub attachments: Vec<Resource>, } /// Parts which can be used to compose a multipart mail. @@ -116,17 +106,14 @@ pub struct MailParts { pub inline_embeddings: Vec<Resource>, /// A number of embeddings which should be treated as attachments - pub attachments: Vec<Resource> + pub attachments: Vec<Resource>, } //-------------------------------------------------------\\ // 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::<Vec<_>>(); - let mut alternatives = alternative_bodies.into_iter() + let mut alternatives = alternative_bodies + .into_iter() .map(|body| body.create_mail(&mut attachments)) .collect::<Vec<_>>(); //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::<Vec<_>>(); - 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::<Vec<_>>(); + 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>, - ) -> Mail { + pub fn create_mail(self, attachments_out: &mut Vec<Mail>) -> 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::<Vec<_>>(); 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>) - -> Mail - { + pub fn wrap_with_mixed(self, other_bodies: Vec<Mail>) -> 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>) - -> Mail - { + pub fn wrap_with_alternatives(self, alternates: Vec<Mail>) -> 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>) - -> Mail - { + pub fn wrap_with_related(self, related: Vec<Mail>) -> Mail { let mut bodies = related; bodies.insert(0, self); new_multipart(&RELATED, bodies) } - } /// Creates a `multipart/<sub_type>` 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>) - -> Mail -{ - let content_type = MediaType::new(MULTIPART, sub_type) - .unwrap(); +fn new_multipart(sub_type: &'static str, bodies: Vec<Mail>) -> 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<Item=EncData,Error=ResourceLoadingError> - { + pub fn encode( + self, + ctx: &impl Context, + ) -> impl Future<Item = EncData, Error = ResourceLoadingError> { 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<InnerSomeCtx> }`. 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<MaybeEncData, ResourceLoadingError>; + fn load_resource(&self, source: &Source) -> SendBoxFuture<MaybeEncData, ResourceLoadingError>; /// 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<EncData, ResourceLoadingError> - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ) -> SendBoxFuture<EncData, ResourceLoadingError> { 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<F>(&self, fut: F) -> SendBoxFuture<F::Item, F::Error> - 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<FN, I>(&self, func: FN ) -> SendBoxFuture<I::Item, I::Error> - where FN: FnOnce() -> I + Send + 'static, - I: IntoFuture + 'static, - I::Future: Send + 'static, - I::Item: Send + 'static, - I::Error: Send + 'static + fn offload_fn<FN, I>(&self, func: FN) -> SendBoxFuture<I::Item, I::Error> + 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<EncData, ResourceLoadingError> -{ +pub fn default_impl_for_load_transfer_encoded_resource( + ctx: &impl Context, + resource: &Resource, +) -> SendBoxFuture<EncData, ResourceLoadingError> { 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<MaybeEncData, ResourceLoadingError>; + fn load_resource( + &self, + source: &Source, + ctx: &impl Context, + ) -> SendBoxFuture<MaybeEncData, ResourceLoadingError>; /// 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<EncData, ResourceLoadingError> - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ctx: &impl Context, + ) -> SendBoxFuture<EncData, ResourceLoadingError> { 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<F>(&self, fut: F) -> SendBoxFuture<F::Item, F::Error> - 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<R, O, M> Clone for CompositeContext<R, O, M> - where R: ResourceLoaderComponent, - O: OffloaderComponent, - M: MailIdGenComponent +where + R: ResourceLoaderComponent, + O: OffloaderComponent, + M: MailIdGenComponent, { fn clone(&self) -> Self { CompositeContext { @@ -301,9 +302,10 @@ impl<R, O, M> Clone for CompositeContext<R, O, M> } impl<R, O, M> CompositeContext<R, O, M> - 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<R, O, M> CompositeContext<R, O, M> } impl<R, O, M> Context for CompositeContext<R, O, M> - where R: ResourceLoaderComponent, - O: OffloaderComponent, - M: MailIdGenComponent +where + R: ResourceLoaderComponent, + O: OffloaderComponent, + M: MailIdGenComponent, { - - fn load_resource(&self, source: &Source) - -> SendBoxFuture<MaybeEncData, ResourceLoadingError> - { + fn load_resource(&self, source: &Source) -> SendBoxFuture<MaybeEncData, ResourceLoadingError> { self.resource_loader().load_resource(source, self) } - fn load_transfer_encoded_resource(&self, resource: &Resource) - -> SendBoxFuture<EncData, ResourceLoadingError> - { - self.resource_loader().load_transfer_encoded_resource(resource, self) + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + ) -> SendBoxFuture<EncData, ResourceLoadingError> { + self.resource_loader() + .load_transfer_encoded_resource(resource, self) } fn offload<F>(&self, fut: F) -> SendBoxFuture<F::Item, F::Error> - 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<R, O, M> Context for CompositeContext<R, O, M> fn generate_message_id(&self) -> MessageId { self.id_gen().generate_message_id() } - } /// Allows using a part of an context as an component. impl<C> MailIdGenComponent for C - where C: Context +where + C: Context, { fn generate_message_id(&self) -> MessageId { <Self as Context>::generate_message_id(self) @@ -379,12 +382,14 @@ impl<C> MailIdGenComponent for C /// Allows using a part of an context as an component. impl<C> OffloaderComponent for C - where C: Context +where + C: Context, { fn offload<F>(&self, fut: F) -> SendBoxFuture<F::Item, F::Error> - 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 as Context>::offload(self, fut) } @@ -392,18 +397,22 @@ impl<C> OffloaderComponent for C /// Allows using a part of an context as an component. impl<C> ResourceLoaderComponent for C - where C: Context +where + C: Context, { - - fn load_resource(&self, source: &Source, _: &impl Context) - -> SendBoxFuture<MaybeEncData, ResourceLoadingError> - { + fn load_resource( + &self, + source: &Source, + _: &impl Context, + ) -> SendBoxFuture<MaybeEncData, ResourceLoadingError> { <Self as Context>::load_resource(self, source) } - fn load_transfer_encoded_resource(&self, resource: &Resource, _: &impl Context) - -> SendBoxFuture<EncData, ResourceLoadingError> - { + fn load_transfer_encoded_resource( + &self, + resource: &Resource, + _: &impl Context, + ) -> SendBoxFuture<EncData, ResourceLoadingError> { <Self as Context>::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<F>(&self, fut: F) -> SendBoxFuture<F::Item, F::Error> - 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: OffloaderComponent>(r: R) { - let res = r.offload(future::lazy(||-> Result<u32, ()> { Ok(33u32) } )).wait(); - let val = assert_ok!( res ); - assert_eq!( 33u32, val ); + let res = r + .offload(future::lazy(|| -> Result<u32, ()> { 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<SchemeValidation: ConstSwitch = Enabled> { root: PathBuf, scheme: &'static str, - _marker: PhantomData<SchemeValidation> + _marker: PhantomData<SchemeValidation>, } impl<SVSw> FsResourceLoader<SVSw> - 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<P: Into<PathBuf>>( root: P ) -> Self { + pub fn new<P: Into<PathBuf>>(root: P) -> Self { Self::new_with_scheme(root.into(), Self::DEFAULT_SCHEME) } - pub fn new_with_scheme<P: Into<PathBuf>>( root: P, scheme: &'static str ) -> Self { - FsResourceLoader { root: root.into(), scheme, _marker: PhantomData} + pub fn new_with_scheme<P: Into<PathBuf>>(root: P, scheme: &'static str) -> Self { + FsResourceLoader { + root: root.into(), + scheme, + _marker: PhantomData, + } } pub fn with_cwd_root() -> Result<Self, io::Error> { @@ -94,17 +78,17 @@ impl<SVSw> FsResourceLoader<SVSw> } } - impl<ValidateScheme> ResourceLoaderComponent for FsResourceLoader<ValidateScheme> - where ValidateScheme: ConstSwitch +where + ValidateScheme: ConstSwitch, { - - fn load_resource(&self, source: &Source, ctx: &impl Context) - -> SendBoxFuture<MaybeEncData, ResourceLoadingError> - { + fn load_resource( + &self, + source: &Source, + ctx: &impl Context, + ) -> SendBoxFuture<MaybeEncData, ResourceLoadingError> { 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<ValidateScheme> ResourceLoaderComponent for FsResourceLoader<ValidateScheme let use_media_type = source.use_media_type.clone(); let use_file_name = source.use_file_name.clone(); - load_data( - path, - use_media_type, - use_file_name, - ctx, - |data| Ok(MaybeEncData::EncData(data.transfer_encode(Default::default()))) - ) + load_data(path, use_media_type, use_file_name, ctx, |data| { + Ok(MaybeEncData::EncData( + data.transfer_encode(Default::default()), + )) + }) } } - //TODO add a PostProcess hook which can be any combination of // FixNewline, SniffMediaType and custom postprocessing // now this has new responsibilities @@ -137,68 +118,63 @@ pub fn load_data<R, F>( ctx: &impl Context, post_process: F, ) -> SendBoxFuture<R, ResourceLoadingError> - where R: Send + 'static, - F: FnOnce(Data) -> Result<R, ResourceLoadingError> + Send + 'static +where + R: Send + 'static, + F: FnOnce(Data) -> Result<R, ResourceLoadingError> + Send + 'static, { let content_id = ctx.generate_content_id(); ctx.offload_fn(move || { - let mut fd = File::open(& |