From b214c3c1dabdf2f016bd5e60c065ba1edd48c349 Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 13:56:39 +0100 Subject: [PATCH 1/9] Add rustfmt.toml. --- rustfmt.toml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000000..e2c132c09dd --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,7 @@ +ideal_width = 80 +match_block_trailing_comma = true +max_width = 120 +newline_style = "Unix" +normalize_comments = false +struct_lit_multiline_style = "ForceMulti" +where_trailing_comma = true From ef13f01b8ef029a0d15019c7a81549c7ae393f85 Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 13:58:18 +0100 Subject: [PATCH 2/9] Simplify ConstellationControlMsg's Debug implementation. --- components/script_traits/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index 56d4406f1ce..4cf005c93f2 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -258,7 +258,7 @@ pub enum ConstellationControlMsg { impl fmt::Debug for ConstellationControlMsg { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { use self::ConstellationControlMsg::*; - write!(formatter, "ConstellationMsg::{}", match *self { + let variant = match *self { AttachLayout(..) => "AttachLayout", Resize(..) => "Resize", ResizeInactive(..) => "ResizeInactive", @@ -285,7 +285,8 @@ impl fmt::Debug for ConstellationControlMsg { FramedContentChanged(..) => "FramedContentChanged", ReportCSSError(..) => "ReportCSSError", Reload(..) => "Reload" - }) + }; + write!(formatter, "ConstellationMsg::{}", variant) } } From bf643f535602935dbee768f3296357f194570e4c Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 14:07:06 +0100 Subject: [PATCH 3/9] Reformat WebDriverScriptCommand::AddCookie. --- components/script_traits/webdriver_msg.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/components/script_traits/webdriver_msg.rs b/components/script_traits/webdriver_msg.rs index b8c102ee4a2..c197b0dfc18 100644 --- a/components/script_traits/webdriver_msg.rs +++ b/components/script_traits/webdriver_msg.rs @@ -14,12 +14,10 @@ use servo_url::ServoUrl; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { - AddCookie( - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] - Cookie, - IpcSender> - ), + AddCookie(#[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] + Cookie, + IpcSender>), ExecuteScript(String, IpcSender), ExecuteAsyncScript(String, IpcSender), FindElementCSS(String, IpcSender, ()>>), From 2dde348b126796e0811870b23d8b81caefbe3c08 Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 14:07:14 +0100 Subject: [PATCH 4/9] Rustfmt script_traits. --- components/script_traits/lib.rs | 20 ++++++++------------ components/script_traits/script_msg.rs | 9 ++++----- components/script_traits/webdriver_msg.rs | 17 ++++++++--------- 3 files changed, 20 insertions(+), 26 deletions(-) diff --git a/components/script_traits/lib.rs b/components/script_traits/lib.rs index 4cf005c93f2..d87fdbad5d3 100644 --- a/components/script_traits/lib.rs +++ b/components/script_traits/lib.rs @@ -18,7 +18,8 @@ extern crate devtools_traits; extern crate euclid; extern crate gfx_traits; extern crate heapsize; -#[macro_use] extern crate heapsize_derive; +#[macro_use] +extern crate heapsize_derive; extern crate hyper; extern crate hyper_serde; extern crate ipc_channel; @@ -252,7 +253,7 @@ pub enum ConstellationControlMsg { /// Report an error from a CSS parser for the given pipeline ReportCSSError(PipelineId, String, usize, usize, String), /// Reload the given page. - Reload(PipelineId) + Reload(PipelineId), } impl fmt::Debug for ConstellationControlMsg { @@ -284,7 +285,7 @@ impl fmt::Debug for ConstellationControlMsg { DispatchStorageEvent(..) => "DispatchStorageEvent", FramedContentChanged(..) => "FramedContentChanged", ReportCSSError(..) => "ReportCSSError", - Reload(..) => "Reload" + Reload(..) => "Reload", }; write!(formatter, "ConstellationMsg::{}", variant) } @@ -384,10 +385,7 @@ pub enum TouchpadPressurePhase { /// Requests a TimerEvent-Message be sent after the given duration. #[derive(Deserialize, Serialize)] -pub struct TimerEventRequest(pub IpcSender, - pub TimerSource, - pub TimerEventId, - pub MsDuration); +pub struct TimerEventRequest(pub IpcSender, pub TimerSource, pub TimerEventId, pub MsDuration); /// Notifies the script thread to fire due timers. /// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and @@ -479,9 +477,7 @@ pub trait ScriptThreadFactory { /// Type of message sent from script to layout. type Message; /// Create a `ScriptThread`. - fn create(state: InitialScriptState, - load_data: LoadData) - -> (Sender, Receiver); + fn create(state: InitialScriptState, load_data: LoadData) -> (Sender, Receiver); } /// Whether the sandbox attribute is present for an iframe element @@ -490,7 +486,7 @@ pub enum IFrameSandboxState { /// Sandbox attribute is present IFrameSandboxed, /// Sandbox attribute is not present - IFrameUnsandboxed + IFrameUnsandboxed, } /// Specifies the information required to load an iframe. @@ -744,5 +740,5 @@ pub struct WorkerScriptLoadOrigin { /// the referrer policy which is used pub referrer_policy: Option, /// the pipeline id of the entity requesting the load - pub pipeline_id: Option + pub pipeline_id: Option, } diff --git a/components/script_traits/script_msg.rs b/components/script_traits/script_msg.rs index 80dbc3f4165..e268d67bc1d 100644 --- a/components/script_traits/script_msg.rs +++ b/components/script_traits/script_msg.rs @@ -57,7 +57,7 @@ pub enum LogEntry { /// Error, with a reason Error(String), /// warning, with a reason - Warn(String) + Warn(String), } /// Messages from the script to the constellation. @@ -148,7 +148,7 @@ pub enum ScriptMsg { /// Enter or exit fullscreen SetFullscreenState(bool), /// Requests that the compositor shut down. - Exit + Exit, } /// Entities required to spawn service workers @@ -175,7 +175,7 @@ pub struct SWManagerSenders { /// sender for communicating with constellation pub swmanager_sender: IpcSender, /// sender for communicating with resource thread - pub resource_sender: IpcSender + pub resource_sender: IpcSender, } /// Messages sent to Service Worker Manager thread @@ -195,6 +195,5 @@ pub enum ServiceWorkerMsg { #[derive(Deserialize, Serialize)] pub enum SWManagerMsg { /// Provide the constellation with a means of communicating with the Service Worker Manager - OwnSender(IpcSender) - + OwnSender(IpcSender), } diff --git a/components/script_traits/webdriver_msg.rs b/components/script_traits/webdriver_msg.rs index c197b0dfc18..9fe9e9b80f5 100644 --- a/components/script_traits/webdriver_msg.rs +++ b/components/script_traits/webdriver_msg.rs @@ -15,7 +15,7 @@ use servo_url::ServoUrl; #[derive(Deserialize, Serialize)] pub enum WebDriverScriptCommand { AddCookie(#[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] + serialize_with = "::hyper_serde::serialize")] Cookie, IpcSender>), ExecuteScript(String, IpcSender), @@ -35,13 +35,13 @@ pub enum WebDriverScriptCommand { GetUrl(IpcSender), IsEnabled(String, IpcSender>), IsSelected(String, IpcSender>), - GetTitle(IpcSender) + GetTitle(IpcSender), } #[derive(Deserialize, Serialize)] pub enum WebDriverCookieError { InvalidDomain, - UnableToSetCookie + UnableToSetCookie, } #[derive(Deserialize, Serialize)] @@ -50,8 +50,7 @@ pub enum WebDriverJSValue { Null, Boolean(bool), Number(f64), - String(String), - // TODO: Object and WebElement + String(String), // TODO: Object and WebElement } #[derive(Deserialize, Serialize)] @@ -60,7 +59,7 @@ pub enum WebDriverJSError { UnknownType, /// Occurs when handler received an event message for a layout channel that is not /// associated with the current script thread - BrowsingContextNotFound + BrowsingContextNotFound, } pub type WebDriverJSResult = Result; @@ -69,7 +68,7 @@ pub type WebDriverJSResult = Result; pub enum WebDriverFrameId { Short(u16), Element(String), - Parent + Parent, } impl ToJson for WebDriverJSValue { @@ -79,7 +78,7 @@ impl ToJson for WebDriverJSValue { WebDriverJSValue::Null => Json::Null, WebDriverJSValue::Boolean(ref x) => x.to_json(), WebDriverJSValue::Number(ref x) => x.to_json(), - WebDriverJSValue::String(ref x) => x.to_json() + WebDriverJSValue::String(ref x) => x.to_json(), } } } @@ -87,5 +86,5 @@ impl ToJson for WebDriverJSValue { #[derive(Deserialize, Serialize)] pub enum LoadStatus { LoadComplete, - LoadTimeout + LoadTimeout, } From 410e5c6d6f02aa240bf78a5f1ee399092cd5550c Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 14:35:51 +0100 Subject: [PATCH 5/9] Use documentation comments for PixelFormat. --- components/net_traits/image/base.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/components/net_traits/image/base.rs b/components/net_traits/image/base.rs index 78e89697714..fdcab3b2314 100644 --- a/components/net_traits/image/base.rs +++ b/components/net_traits/image/base.rs @@ -8,10 +8,14 @@ use webrender_traits; #[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)] pub enum PixelFormat { - K8, // Luminance channel only - KA8, // Luminance + alpha - RGB8, // RGB, 8 bits per channel - RGBA8, // RGB + alpha, 8 bits per channel + /// Luminance channel only + K8, + /// Luminance + alpha + KA8, + /// RGB, 8 bits per channel + RGB8, + /// RGB + alpha, 8 bits per channel + RGBA8, } #[derive(Clone, Deserialize, Serialize, HeapSizeOf)] From 22f85bfed6cb935ef0015870b60687be3d2ab8c5 Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 14:55:31 +0100 Subject: [PATCH 6/9] Reformat fetch_async(). --- components/net_traits/lib.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index eb8983f9d10..3cad32435b0 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -379,9 +379,8 @@ pub fn fetch_async(request: RequestInit, where F: Fn(FetchResponseMsg) + Send + 'static { let (action_sender, action_receiver) = ipc::channel().unwrap(); - ROUTER.add_route(action_receiver.to_opaque(), box move |message| { - f(message.to().unwrap()); - }); + ROUTER.add_route(action_receiver.to_opaque(), + box move |message| f(message.to().unwrap())); core_resource_thread.send(CoreResourceMsg::Fetch(request, action_sender)).unwrap(); } From 01114ebcf82624b2ee32a77b4b799c2c067c6da1 Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 15:05:07 +0100 Subject: [PATCH 7/9] Reformat WebSocketNetworkEvent::ConnectionEstablished and CoreResourceMsg::SetCookieForUrl. --- components/net_traits/lib.rs | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index 3cad32435b0..39b467dc49e 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -316,12 +316,10 @@ pub enum WebSocketDomAction { #[derive(Deserialize, Serialize)] pub enum WebSocketNetworkEvent { - ConnectionEstablished( - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] - header::Headers, - Vec - ), + ConnectionEstablished(#[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] + header::Headers, + Vec), MessageReceived(MessageData), Close(Option, String), Fail, @@ -346,13 +344,11 @@ pub enum CoreResourceMsg { /// Try to make a websocket connection to a URL. WebsocketConnect(WebSocketCommunicate, WebSocketConnectData), /// Store a cookie for a given originating URL - SetCookieForUrl( - ServoUrl, - #[serde(deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize")] - Cookie, - CookieSource - ), + SetCookieForUrl(ServoUrl, + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] + Cookie, + CookieSource), /// Store cookies for a given originating URL SetCookiesForUrl(ServoUrl, Vec>, CookieSource), /// Retrieve the stored cookies for a given URL From b76613a3891e6edccf32ceefa922f6c745f6ee8a Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 15:05:34 +0100 Subject: [PATCH 8/9] Skip rustfmt on to_filtered. https://github.com/rust-lang-nursery/rustfmt/issues/1262 --- components/net_traits/response.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index d93798be973..694922cec52 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -172,6 +172,7 @@ impl Response { /// Convert to a filtered response, of type `filter_type`. /// Do not use with type Error or Default + #[cfg_attr(rustfmt, rustfmt_skip)] pub fn to_filtered(self, filter_type: ResponseType) -> Response { match filter_type { ResponseType::Default | ResponseType::Error(..) => panic!(), From b46846e2a01ad38e7c8c4cf0099dfd94d74faa6d Mon Sep 17 00:00:00 2001 From: Ms2ger Date: Tue, 3 Jan 2017 14:31:48 +0100 Subject: [PATCH 9/9] Rustfmt net_traits. --- components/net_traits/filemanager_thread.rs | 6 +- components/net_traits/hosts.rs | 24 ++++---- components/net_traits/image/base.rs | 33 ++++++---- components/net_traits/image_cache_thread.rs | 18 +++--- components/net_traits/lib.rs | 56 +++++++++-------- components/net_traits/pub_domains.rs | 26 ++++---- components/net_traits/request.rs | 67 +++++++++++++-------- components/net_traits/response.rs | 37 ++++++------ components/net_traits/storage_thread.rs | 4 +- 9 files changed, 151 insertions(+), 120 deletions(-) diff --git a/components/net_traits/filemanager_thread.rs b/components/net_traits/filemanager_thread.rs index c572c8c4926..4fecf7d10b0 100644 --- a/components/net_traits/filemanager_thread.rs +++ b/components/net_traits/filemanager_thread.rs @@ -54,7 +54,7 @@ impl RelativePos { (Some(old_end), Some(rel_end)) => Some(old_end + rel_end), (old, None) => old, (None, rel) => rel, - } + }, } } @@ -78,7 +78,7 @@ impl RelativePos { } else { min(rel_end, size) } - } + }, None => size, }; @@ -148,7 +148,7 @@ pub enum FileManagerThreadMsg { pub enum ReadFileProgress { Meta(BlobBuf), Partial(Vec), - EOF + EOF, } pub type FileManagerResult = Result; diff --git a/components/net_traits/hosts.rs b/components/net_traits/hosts.rs index c3c48ce9938..9d4acedb83e 100644 --- a/components/net_traits/hosts.rs +++ b/components/net_traits/hosts.rs @@ -15,7 +15,7 @@ lazy_static! { } fn create_host_table() -> Option> { - //TODO: handle bad file path + // TODO: handle bad file path let path = match env::var("HOST_FILE") { Ok(host_file_path) => host_file_path, Err(_) => return None, @@ -58,16 +58,18 @@ pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap { } pub fn replace_hosts(url: &ServoUrl) -> ServoUrl { - HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), |host_table| { - host_replacement(host_table, url) - }) + HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), + |host_table| host_replacement(host_table, url)) } -pub fn host_replacement(host_table: &HashMap, - url: &ServoUrl) -> ServoUrl { - url.domain().and_then(|domain| host_table.get(domain).map(|ip| { - let mut new_url = url.clone(); - new_url.set_ip_host(*ip).unwrap(); - new_url - })).unwrap_or_else(|| url.clone()) +pub fn host_replacement(host_table: &HashMap, url: &ServoUrl) -> ServoUrl { + url.domain() + .and_then(|domain| { + host_table.get(domain).map(|ip| { + let mut new_url = url.clone(); + new_url.set_ip_host(*ip).unwrap(); + new_url + }) + }) + .unwrap_or_else(|| url.clone()) } diff --git a/components/net_traits/image/base.rs b/components/net_traits/image/base.rs index fdcab3b2314..a6bc08ce22f 100644 --- a/components/net_traits/image/base.rs +++ b/components/net_traits/image/base.rs @@ -63,13 +63,13 @@ pub fn load_from_memory(buffer: &[u8]) -> Option { Err(msg) => { debug!("{}", msg); None - } + }, Ok(_) => { match piston_image::load_from_memory(buffer) { Ok(image) => { let mut rgba = match image { DynamicImage::ImageRgba8(rgba) => rgba, - image => image.to_rgba() + image => image.to_rgba(), }; byte_swap_and_premultiply(&mut *rgba); Some(Image { @@ -79,31 +79,38 @@ pub fn load_from_memory(buffer: &[u8]) -> Option { bytes: IpcSharedMemory::from_bytes(&*rgba), id: None, }) - } + }, Err(e) => { debug!("Image decoding error: {:?}", e); None - } + }, } - } + }, } } // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img pub fn detect_image_format(buffer: &[u8]) -> Result { - if is_gif(buffer) { Ok(ImageFormat::GIF) - } else if is_jpeg(buffer) { Ok(ImageFormat::JPEG) - } else if is_png(buffer) { Ok(ImageFormat::PNG) - } else if is_bmp(buffer) { Ok(ImageFormat::BMP) - } else if is_ico(buffer) { Ok(ImageFormat::ICO) - } else { Err("Image Format Not Supported") } + if is_gif(buffer) { + Ok(ImageFormat::GIF) + } else if is_jpeg(buffer) { + Ok(ImageFormat::JPEG) + } else if is_png(buffer) { + Ok(ImageFormat::PNG) + } else if is_bmp(buffer) { + Ok(ImageFormat::BMP) + } else if is_ico(buffer) { + Ok(ImageFormat::ICO) + } else { + Err("Image Format Not Supported") + } } fn is_gif(buffer: &[u8]) -> bool { match buffer { - &[b'G', b'I', b'F', b'8', n, b'a', ..] if n == b'7' || n == b'9' => true, - _ => false + &[b'G', b'I', b'F', b'8', n, b'a', _..] if n == b'7' || n == b'9' => true, + _ => false, } } diff --git a/components/net_traits/image_cache_thread.rs b/components/net_traits/image_cache_thread.rs index d816fd628c7..4fb7aedee04 100644 --- a/components/net_traits/image_cache_thread.rs +++ b/components/net_traits/image_cache_thread.rs @@ -46,7 +46,7 @@ pub enum ImageResponse { /// The requested image failed to load, so a placeholder was loaded instead. PlaceholderLoaded(Arc), /// Neither the requested image nor the placeholder could be loaded. - None + None, } /// Indicating either entire image or just metadata availability @@ -123,10 +123,7 @@ impl ImageCacheThread { } /// Asynchronously request an image. See ImageCacheCommand::RequestImage. - pub fn request_image(&self, - url: ServoUrl, - result_chan: ImageCacheChan, - responder: Option) { + pub fn request_image(&self, url: ServoUrl, result_chan: ImageCacheChan, responder: Option) { let msg = ImageCacheCommand::RequestImage(url, result_chan, responder); let _ = self.chan.send(msg); } @@ -142,8 +139,7 @@ impl ImageCacheThread { } /// Get the current state of an image. See ImageCacheCommand::GetImageIfAvailable. - pub fn find_image(&self, url: ServoUrl, use_placeholder: UsePlaceholder) - -> Result, ImageState> { + pub fn find_image(&self, url: ServoUrl, use_placeholder: UsePlaceholder) -> Result, ImageState> { let (sender, receiver) = ipc::channel().unwrap(); let msg = ImageCacheCommand::GetImageIfAvailable(url, use_placeholder, sender); let _ = self.chan.send(msg); @@ -154,7 +150,9 @@ impl ImageCacheThread { /// See ImageCacheCommand::GetImageOrMetadataIfAvailable. /// /// FIXME: We shouldn't do IPC for data uris! - pub fn find_image_or_metadata(&self, url: ServoUrl, use_placeholder: UsePlaceholder) + pub fn find_image_or_metadata(&self, + url: ServoUrl, + use_placeholder: UsePlaceholder) -> Result { let (sender, receiver) = ipc::channel().unwrap(); let msg = ImageCacheCommand::GetImageOrMetadataIfAvailable(url, use_placeholder, sender); @@ -163,9 +161,7 @@ impl ImageCacheThread { } /// Decode the given image bytes and cache the result for the given URL. - pub fn store_complete_image_bytes(&self, - url: ServoUrl, - image_data: Vec) { + pub fn store_complete_image_bytes(&self, url: ServoUrl, image_data: Vec) { let msg = ImageCacheCommand::StoreDecodeImage(url, image_data); let _ = self.chan.send(msg); } diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index 39b467dc49e..8289e360e32 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -11,7 +11,8 @@ extern crate cookie as cookie_rs; extern crate heapsize; -#[macro_use] extern crate heapsize_derive; +#[macro_use] +extern crate heapsize_derive; extern crate hyper; extern crate hyper_serde; extern crate image as piston_image; @@ -93,12 +94,16 @@ pub struct CustomResponse { #[serde(deserialize_with = "::hyper_serde::deserialize", serialize_with = "::hyper_serde::serialize")] pub raw_status: RawStatus, - pub body: Vec + pub body: Vec, } impl CustomResponse { pub fn new(headers: Headers, raw_status: RawStatus, body: Vec) -> CustomResponse { - CustomResponse { headers: headers, raw_status: raw_status, body: body } + CustomResponse { + headers: headers, + raw_status: raw_status, + body: body, + } } } @@ -169,7 +174,7 @@ pub trait FetchTaskTarget { #[derive(Serialize, Deserialize)] pub enum FilteredMetadata { Opaque, - Transparent(Metadata) + Transparent(Metadata), } #[derive(Serialize, Deserialize)] @@ -177,8 +182,8 @@ pub enum FetchMetadata { Unfiltered(Metadata), Filtered { filtered: FilteredMetadata, - unsafe_: Metadata - } + unsafe_: Metadata, + }, } pub trait FetchResponseListener { @@ -209,8 +214,8 @@ impl FetchTaskTarget for IpcSender { fn process_response_eof(&mut self, response: &Response) { if response.is_network_error() { // todo: finer grained errors - let _ = self.send(FetchResponseMsg::ProcessResponseEOF( - Err(NetworkError::Internal("Network error".into())))); + let _ = + self.send(FetchResponseMsg::ProcessResponseEOF(Err(NetworkError::Internal("Network error".into())))); } else { let _ = self.send(FetchResponseMsg::ProcessResponseEOF(Ok(()))); } @@ -243,7 +248,9 @@ pub type IpcSendResult = Result<(), IOError>; /// Abstraction of the ability to send a particular type of message, /// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields /// XXX: If this trait will be used more in future, some auto derive might be appealing -pub trait IpcSend where T: serde::Serialize + serde::Deserialize { +pub trait IpcSend + where T: serde::Serialize + serde::Deserialize, +{ /// send message T fn send(&self, T) -> IpcSendResult; /// get underlying sender @@ -262,8 +269,7 @@ pub struct ResourceThreads { } impl ResourceThreads { - pub fn new(c: CoreResourceThread, - s: IpcSender) -> ResourceThreads { + pub fn new(c: CoreResourceThread, s: IpcSender) -> ResourceThreads { ResourceThreads { core_thread: c, storage_thread: s, @@ -293,13 +299,15 @@ impl IpcSend for ResourceThreads { // Ignore the sub-fields impl HeapSizeOf for ResourceThreads { - fn heap_size_of_children(&self) -> usize { 0 } + fn heap_size_of_children(&self) -> usize { + 0 + } } #[derive(PartialEq, Copy, Clone, Deserialize, Serialize)] pub enum IncludeSubdomains { Included, - NotIncluded + NotIncluded, } #[derive(HeapSizeOf, Deserialize, Serialize)] @@ -369,10 +377,8 @@ pub enum CoreResourceMsg { } /// Instruct the resource thread to make a new request. -pub fn fetch_async(request: RequestInit, - core_resource_thread: &CoreResourceThread, - f: F) - where F: Fn(FetchResponseMsg) + Send + 'static +pub fn fetch_async(request: RequestInit, core_resource_thread: &CoreResourceThread, f: F) + where F: Fn(FetchResponseMsg) + Send + 'static, { let (action_sender, action_receiver) = ipc::channel().unwrap(); ROUTER.add_route(action_receiver.to_opaque(), @@ -419,9 +425,9 @@ impl Metadata { /// Metadata with defaults for everything optional. pub fn default(url: ServoUrl) -> Self { Metadata { - final_url: url, + final_url: url, content_type: None, - charset: None, + charset: None, headers: None, // https://fetch.spec.whatwg.org/#concept-response-status-message status: Some((200, b"OK".to_vec())), @@ -465,7 +471,7 @@ pub fn load_whole_resource(request: RequestInit, let (action_sender, action_receiver) = ipc::channel().unwrap(); core_resource_thread.send(CoreResourceMsg::Fetch(request, action_sender)).unwrap(); - let mut buf = vec!(); + let mut buf = vec![]; let mut metadata = None; loop { match action_receiver.recv().unwrap() { @@ -474,13 +480,13 @@ pub fn load_whole_resource(request: RequestInit, FetchResponseMsg::ProcessResponse(Ok(m)) => { metadata = Some(match m { FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_ + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, }) }, FetchResponseMsg::ProcessResponseChunk(data) => buf.extend_from_slice(&data), FetchResponseMsg::ProcessResponseEOF(Ok(())) => return Ok((metadata.unwrap(), buf)), FetchResponseMsg::ProcessResponse(Err(e)) | - FetchResponseMsg::ProcessResponseEOF(Err(e)) => return Err(e) + FetchResponseMsg::ProcessResponseEOF(Err(e)) => return Err(e), } } } @@ -511,16 +517,14 @@ pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] { loop { match slice.split_first() { - Some((first, remainder)) if HTTP_WS_BYTES.contains(first) => - slice = remainder, + Some((first, remainder)) if HTTP_WS_BYTES.contains(first) => slice = remainder, _ => break, } } loop { match slice.split_last() { - Some((last, remainder)) if HTTP_WS_BYTES.contains(last) => - slice = remainder, + Some((last, remainder)) if HTTP_WS_BYTES.contains(last) => slice = remainder, _ => break, } } diff --git a/components/net_traits/pub_domains.rs b/components/net_traits/pub_domains.rs index 664c39fb09b..47ebe6f9775 100644 --- a/components/net_traits/pub_domains.rs +++ b/components/net_traits/pub_domains.rs @@ -32,7 +32,9 @@ lazy_static! { } impl<'a> FromIterator<&'a str> for PubDomainRules { - fn from_iter(iter: T) -> Self where T: IntoIterator { + fn from_iter(iter: T) -> Self + where T: IntoIterator, + { let mut result = PubDomainRules::new(); for item in iter { if item.starts_with("!") { @@ -96,9 +98,10 @@ impl PubDomainRules { let domain = domain.trim_left_matches("."); match domain.find(".") { None => !domain.is_empty(), - Some(index) => !self.exceptions.contains(domain) && - self.wildcards.contains(&domain[index + 1..]) || - self.rules.contains(domain), + Some(index) => { + !self.exceptions.contains(domain) && self.wildcards.contains(&domain[index + 1..]) || + self.rules.contains(domain) + }, } } pub fn is_registrable_suffix(&self, domain: &str) -> bool { @@ -108,19 +111,18 @@ impl PubDomainRules { let domain = domain.trim_left_matches("."); match domain.find(".") { None => false, - Some(index) => self.exceptions.contains(domain) || - !self.wildcards.contains(&domain[index + 1..]) && - !self.rules.contains(domain) && - self.is_public_suffix(&domain[index + 1..]), + Some(index) => { + self.exceptions.contains(domain) || + !self.wildcards.contains(&domain[index + 1..]) && !self.rules.contains(domain) && + self.is_public_suffix(&domain[index + 1..]) + }, } } } fn load_pub_domains() -> PubDomainRules { - let content = read_resource_file("public_domains.txt") - .expect("Could not find public suffix list file"); - let content = from_utf8(&content) - .expect("Could not read public suffix list file"); + let content = read_resource_file("public_domains.txt").expect("Could not find public suffix list file"); + let content = from_utf8(&content).expect("Could not read public suffix list file"); PubDomainRules::parse(content) } diff --git a/components/net_traits/request.rs b/components/net_traits/request.rs index 05f802ea183..d082f20b422 100644 --- a/components/net_traits/request.rs +++ b/components/net_traits/request.rs @@ -9,7 +9,7 @@ use msg::constellation_msg::PipelineId; use servo_url::ServoUrl; use std::cell::{Cell, RefCell}; use std::default::Default; -use url::{Origin as UrlOrigin}; +use url::Origin as UrlOrigin; /// An [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator) #[derive(Copy, Clone, PartialEq, HeapSizeOf)] @@ -18,29 +18,47 @@ pub enum Initiator { Download, ImageSet, Manifest, - XSLT + XSLT, } /// A request [type](https://fetch.spec.whatwg.org/#concept-request-type) #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)] pub enum Type { - None, Audio, Font, Image, - Script, Style, Track, Video + None, + Audio, + Font, + Image, + Script, + Style, + Track, + Video, } /// A request [destination](https://fetch.spec.whatwg.org/#concept-request-destination) #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, HeapSizeOf)] pub enum Destination { - None, Document, Embed, Font, Image, Manifest, - Media, Object, Report, Script, ServiceWorker, - SharedWorker, Style, Worker, XSLT + None, + Document, + Embed, + Font, + Image, + Manifest, + Media, + Object, + Report, + Script, + ServiceWorker, + SharedWorker, + Style, + Worker, + XSLT, } /// A request [origin](https://fetch.spec.whatwg.org/#concept-request-origin) #[derive(Clone, PartialEq, Debug, HeapSizeOf)] pub enum Origin { Client, - Origin(UrlOrigin) + Origin(UrlOrigin), } /// A [referer](https://fetch.spec.whatwg.org/#concept-request-referrer) @@ -49,7 +67,7 @@ pub enum Referrer { NoReferrer, /// Default referrer if nothing is specified Client, - ReferrerUrl(ServoUrl) + ReferrerUrl(ServoUrl), } /// A [request mode](https://fetch.spec.whatwg.org/#concept-request-mode) @@ -58,7 +76,7 @@ pub enum RequestMode { Navigate, SameOrigin, NoCors, - CorsMode + CorsMode, } /// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode) @@ -66,7 +84,7 @@ pub enum RequestMode { pub enum CredentialsMode { Omit, CredentialsSameOrigin, - Include + Include, } /// [Cache mode](https://fetch.spec.whatwg.org/#concept-request-cache-mode) @@ -77,7 +95,7 @@ pub enum CacheMode { Reload, NoCache, ForceCache, - OnlyIfCached + OnlyIfCached, } /// [Redirect mode](https://fetch.spec.whatwg.org/#concept-request-redirect-mode) @@ -85,7 +103,7 @@ pub enum CacheMode { pub enum RedirectMode { Follow, Error, - Manual + Manual, } /// [Response tainting](https://fetch.spec.whatwg.org/#concept-request-response-tainting) @@ -93,22 +111,21 @@ pub enum RedirectMode { pub enum ResponseTainting { Basic, CorsTainting, - Opaque + Opaque, } /// [Window](https://fetch.spec.whatwg.org/#concept-request-window) #[derive(Copy, Clone, PartialEq, HeapSizeOf)] pub enum Window { NoWindow, - Client, - // TODO: Environmental settings object + Client, // TODO: Environmental settings object } /// [CORS settings attribute](https://html.spec.whatwg.org/multipage/#attr-crossorigin-anonymous) #[derive(Copy, Clone, PartialEq, Serialize, Deserialize)] pub enum CorsSettings { Anonymous, - UseCredentials + UseCredentials, } #[derive(Serialize, Deserialize, Clone, HeapSizeOf)] @@ -214,7 +231,8 @@ impl Request { pub fn new(url: ServoUrl, origin: Option, is_service_worker_global_scope: bool, - pipeline_id: Option) -> Request { + pipeline_id: Option) + -> Request { Request { method: RefCell::new(Method::Get), local_urls_only: false, @@ -251,7 +269,8 @@ impl Request { pub fn from_init(init: RequestInit) -> Request { let mut req = Request::new(init.url, Some(Origin::Origin(init.origin.origin())), - false, init.pipeline_id); + false, + init.pipeline_id); *req.method.borrow_mut() = init.method; *req.headers.borrow_mut() = init.headers; req.unsafe_request = init.unsafe_request; @@ -289,11 +308,9 @@ impl Request { pub fn is_subresource_request(&self) -> bool { match self.destination { - Destination::Font | Destination::Image | Destination::Manifest - | Destination::Media | Destination::Script - | Destination::Style | Destination::XSLT - | Destination::None => true, - _ => false + Destination::Font | Destination::Image | Destination::Manifest | Destination::Media | + Destination::Script | Destination::Style | Destination::XSLT | Destination::None => true, + _ => false, } } } @@ -302,7 +319,7 @@ impl Referrer { pub fn to_url(&self) -> Option<&ServoUrl> { match *self { Referrer::NoReferrer | Referrer::Client => None, - Referrer::ReferrerUrl(ref url) => Some(url) + Referrer::ReferrerUrl(ref url) => Some(url), } } } diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index 694922cec52..1eff533680a 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -21,7 +21,7 @@ pub enum ResponseType { Default, Error(NetworkError), Opaque, - OpaqueRedirect + OpaqueRedirect, } /// [Response termination reason](https://fetch.spec.whatwg.org/#concept-response-termination-reason) @@ -29,7 +29,7 @@ pub enum ResponseType { pub enum TerminationReason { EndUserAbort, Fatal, - Timeout + Timeout, } /// The response body can still be pushed to after fetch @@ -45,7 +45,8 @@ impl ResponseBody { pub fn is_done(&self) -> bool { match *self { ResponseBody::Done(..) => true, - ResponseBody::Empty | ResponseBody::Receiving(..) => false + ResponseBody::Empty | + ResponseBody::Receiving(..) => false, } } } @@ -57,7 +58,7 @@ pub enum CacheState { None, Local, Validated, - Partial + Partial, } /// [Https state](https://fetch.spec.whatwg.org/#concept-response-https-state) @@ -65,13 +66,13 @@ pub enum CacheState { pub enum HttpsState { None, Deprecated, - Modern + Modern, } pub enum ResponseMsg { Chunk(Vec), Finished, - Errored + Errored, } /// A [Response](https://fetch.spec.whatwg.org/#concept-response) as defined by the Fetch spec @@ -114,7 +115,7 @@ impl Response { https_state: HttpsState::None, referrer: None, internal_response: None, - return_internal: Cell::new(true) + return_internal: Cell::new(true), } } @@ -132,7 +133,7 @@ impl Response { https_state: HttpsState::None, referrer: None, internal_response: None, - return_internal: Cell::new(true) + return_internal: Cell::new(true), } } @@ -143,7 +144,7 @@ impl Response { pub fn is_network_error(&self) -> bool { match self.response_type { ResponseType::Error(..) => true, - _ => false + _ => false, } } @@ -175,7 +176,8 @@ impl Response { #[cfg_attr(rustfmt, rustfmt_skip)] pub fn to_filtered(self, filter_type: ResponseType) -> Response { match filter_type { - ResponseType::Default | ResponseType::Error(..) => panic!(), + ResponseType::Default | + ResponseType::Error(..) => panic!(), _ => (), } @@ -191,7 +193,8 @@ impl Response { response.response_type = filter_type; match response.response_type { - ResponseType::Default | ResponseType::Error(..) => unreachable!(), + ResponseType::Default | + ResponseType::Error(..) => unreachable!(), ResponseType::Basic => { let headers = old_headers.iter().filter(|header| { @@ -236,7 +239,7 @@ impl Response { response.status = None; response.body = Arc::new(Mutex::new(ResponseBody::Empty)); response.cache_state = CacheState::None; - } + }, } response @@ -247,7 +250,7 @@ impl Response { let mut metadata = Metadata::default(url.clone()); metadata.set_content_type(match response.headers.get() { Some(&ContentType(ref mime)) => Some(mime), - None => None + None => None, }); metadata.headers = Some(Serde(response.headers.clone())); metadata.status = response.raw_status.clone(); @@ -270,12 +273,12 @@ impl Response { Ok(FetchMetadata::Filtered { filtered: match metadata { Some(m) => FilteredMetadata::Transparent(m), - None => FilteredMetadata::Opaque + None => FilteredMetadata::Opaque, }, - unsafe_: unsafe_metadata + unsafe_: unsafe_metadata, }) - } - None => Err(NetworkError::Internal("No url found in unsafe response".to_owned())) + }, + None => Err(NetworkError::Internal("No url found in unsafe response".to_owned())), } } else { Ok(FetchMetadata::Unfiltered(metadata.unwrap())) diff --git a/components/net_traits/storage_thread.rs b/components/net_traits/storage_thread.rs index e4fec8729f1..b56ed2e3181 100644 --- a/components/net_traits/storage_thread.rs +++ b/components/net_traits/storage_thread.rs @@ -8,7 +8,7 @@ use servo_url::ServoUrl; #[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)] pub enum StorageType { Session, - Local + Local, } /// Request operations on the storage data associated with a particular url @@ -36,5 +36,5 @@ pub enum StorageThreadMsg { Clear(IpcSender, ServoUrl, StorageType), /// send a reply when done cleaning up thread resources and then shut it down - Exit(IpcSender<()>) + Exit(IpcSender<()>), }