Use try syntax for Option where appropriate

This commit is contained in:
Matt Brubeck 2017-10-20 08:25:35 -07:00
parent fe16c1d5c3
commit 2d45e9d2da
19 changed files with 65 additions and 180 deletions

View file

@ -321,10 +321,7 @@ impl BluetoothManager {
self.adapter = BluetoothAdapter::init().ok(); self.adapter = BluetoothAdapter::init().ok();
} }
let adapter = match self.adapter.as_ref() { let adapter = self.adapter.as_ref()?;
Some(adapter) => adapter,
None => return None,
};
if is_mock_adapter(adapter) && !adapter.is_present().unwrap_or(false) { if is_mock_adapter(adapter) && !adapter.is_present().unwrap_or(false) {
return None; return None;
@ -422,14 +419,8 @@ impl BluetoothManager {
} }
fn device_from_service_id(&self, service_id: &str) -> Option<BluetoothDevice> { fn device_from_service_id(&self, service_id: &str) -> Option<BluetoothDevice> {
let device_id = match self.service_to_device.get(service_id) { let device_id = self.service_to_device.get(service_id)?;
Some(id) => id, self.cached_devices.get(device_id).cloned()
None => return None,
};
match self.cached_devices.get(device_id) {
Some(d) => Some(d.clone()),
None => None,
}
} }
fn device_is_cached(&self, device_id: &str) -> bool { fn device_is_cached(&self, device_id: &str) -> bool {
@ -471,10 +462,7 @@ impl BluetoothManager {
fn get_gatt_service(&mut self, adapter: &mut BluetoothAdapter, service_id: &str) -> Option<&BluetoothGATTService> { fn get_gatt_service(&mut self, adapter: &mut BluetoothAdapter, service_id: &str) -> Option<&BluetoothGATTService> {
return_if_cached!(self.cached_services, service_id); return_if_cached!(self.cached_services, service_id);
let device_id = match self.service_to_device.get(service_id) { let device_id = self.service_to_device.get(service_id)?.clone();
Some(d) => d.clone(),
None => return None,
};
self.get_and_cache_gatt_services(adapter, &device_id); self.get_and_cache_gatt_services(adapter, &device_id);
return_if_cached!(self.cached_services, service_id); return_if_cached!(self.cached_services, service_id);
None None
@ -508,10 +496,7 @@ impl BluetoothManager {
characteristic_id: &str) characteristic_id: &str)
-> Option<&BluetoothGATTCharacteristic> { -> Option<&BluetoothGATTCharacteristic> {
return_if_cached!(self.cached_characteristics, characteristic_id); return_if_cached!(self.cached_characteristics, characteristic_id);
let service_id = match self.characteristic_to_service.get(characteristic_id) { let service_id = self.characteristic_to_service.get(characteristic_id)?.clone();
Some(s) => s.clone(),
None => return None,
};
self.get_and_cache_gatt_characteristics(adapter, &service_id); self.get_and_cache_gatt_characteristics(adapter, &service_id);
return_if_cached!(self.cached_characteristics, characteristic_id); return_if_cached!(self.cached_characteristics, characteristic_id);
None None
@ -566,10 +551,7 @@ impl BluetoothManager {
descriptor_id: &str) descriptor_id: &str)
-> Option<&BluetoothGATTDescriptor> { -> Option<&BluetoothGATTDescriptor> {
return_if_cached!(self.cached_descriptors, descriptor_id); return_if_cached!(self.cached_descriptors, descriptor_id);
let characteristic_id = match self.descriptor_to_characteristic.get(descriptor_id) { let characteristic_id = self.descriptor_to_characteristic.get(descriptor_id)?.clone();
Some(c) => c.clone(),
None => return None,
};
self.get_and_cache_gatt_descriptors(adapter, &characteristic_id); self.get_and_cache_gatt_descriptors(adapter, &characteristic_id);
return_if_cached!(self.cached_descriptors, descriptor_id); return_if_cached!(self.cached_descriptors, descriptor_id);
None None

View file

@ -317,16 +317,10 @@ fn run_server(sender: Sender<DevtoolsControlMsg>,
actor_pipelines: &HashMap<PipelineId, String>) -> Option<String> { actor_pipelines: &HashMap<PipelineId, String>) -> Option<String> {
let actors = actors.lock().unwrap(); let actors = actors.lock().unwrap();
if let Some(worker_id) = worker_id { if let Some(worker_id) = worker_id {
let actor_name = match (*actor_workers).get(&(id, worker_id)) { let actor_name = (*actor_workers).get(&(id, worker_id))?;
Some(name) => name,
None => return None,
};
Some(actors.find::<WorkerActor>(actor_name).console.clone()) Some(actors.find::<WorkerActor>(actor_name).console.clone())
} else { } else {
let actor_name = match (*actor_pipelines).get(&id) { let actor_name = (*actor_pipelines).get(&id)?;
Some(name) => name,
None => return None,
};
Some(actors.find::<TabActor>(actor_name).console.clone()) Some(actors.find::<TabActor>(actor_name).console.clone())
} }
} }

View file

@ -2895,10 +2895,7 @@ impl Fragment {
/// Returns the 4D matrix representing this fragment's transform. /// Returns the 4D matrix representing this fragment's transform.
pub fn transform_matrix(&self, stacking_relative_border_box: &Rect<Au>) -> Option<Transform3D<f32>> { pub fn transform_matrix(&self, stacking_relative_border_box: &Rect<Au>) -> Option<Transform3D<f32>> {
let list = &self.style.get_box().transform; let list = &self.style.get_box().transform;
let transform = match list.to_transform_3d_matrix(Some(stacking_relative_border_box)) { let transform = list.to_transform_3d_matrix(Some(stacking_relative_border_box))?;
Some(transform) => transform,
None => return None,
};
let transform_origin = &self.style.get_box().transform_origin; let transform_origin = &self.style.get_box().transform_origin;
let transform_origin_x = let transform_origin_x =
@ -3039,10 +3036,7 @@ impl<'a> Iterator for InlineStyleIterator<'a> {
self.primary_style_yielded = true; self.primary_style_yielded = true;
return Some(&*self.fragment.style) return Some(&*self.fragment.style)
} }
let inline_context = match self.fragment.inline_context { let inline_context = self.fragment.inline_context.as_ref()?;
None => return None,
Some(ref inline_context) => inline_context,
};
let inline_style_index = self.inline_style_index; let inline_style_index = self.inline_style_index;
if inline_style_index == inline_context.nodes.len() { if inline_style_index == inline_context.nodes.len() {
return None return None

View file

@ -384,10 +384,7 @@ impl LineBreaker {
-> Option<Fragment> -> Option<Fragment>
where I: Iterator<Item=Fragment>, where I: Iterator<Item=Fragment>,
{ {
let mut result = match self.next_fragment(old_fragment_iter) { let mut result = self.next_fragment(old_fragment_iter)?;
None => return None,
Some(fragment) => fragment,
};
loop { loop {
let candidate = match self.next_fragment(old_fragment_iter) { let candidate = match self.next_fragment(old_fragment_iter) {

View file

@ -78,10 +78,7 @@ impl<'a, T> Iterator for PersistentListIterator<'a, T> where T: Send + Sync + 's
#[inline] #[inline]
fn next(&mut self) -> Option<&'a T> { fn next(&mut self) -> Option<&'a T> {
let entry = match self.entry { let entry = self.entry?;
None => return None,
Some(entry) => entry,
};
let value = &entry.value; let value = &entry.value;
self.entry = match entry.next { self.entry = match entry.next {
None => None, None => None,

View file

@ -895,11 +895,7 @@ impl LayoutThread {
} }
fn try_get_layout_root<N: LayoutNode>(&self, node: N) -> Option<FlowRef> { fn try_get_layout_root<N: LayoutNode>(&self, node: N) -> Option<FlowRef> {
let mut data = match node.mutate_layout_data() { let result = node.mutate_layout_data()?.flow_construction_result.get();
Some(x) => x,
None => return None,
};
let result = data.flow_construction_result.get();
let mut flow = match result { let mut flow = match result {
ConstructionResult::Flow(mut flow, abs_descendants) => { ConstructionResult::Flow(mut flow, abs_descendants) => {

View file

@ -16,22 +16,13 @@ lazy_static! {
} }
fn create_host_table() -> Option<HashMap<String, IpAddr>> { fn create_host_table() -> Option<HashMap<String, IpAddr>> {
// TODO: handle bad file path let path = env::var_os("HOST_FILE")?;
let path = match env::var("HOST_FILE") {
Ok(host_file_path) => host_file_path,
Err(_) => return None,
};
let mut file = match File::open(&path) { let file = File::open(&path).ok()?;
Ok(f) => BufReader::new(f), let mut reader = BufReader::new(file);
Err(_) => return None,
};
let mut lines = String::new(); let mut lines = String::new();
match file.read_to_string(&mut lines) { reader.read_to_string(&mut lines).ok()?;
Ok(_) => (),
Err(_) => return None,
};
Some(parse_hostsfile(&lines)) Some(parse_hostsfile(&lines))
} }

View file

@ -108,10 +108,7 @@ impl WrappedHttpResponse {
} }
fn content_encoding(&self) -> Option<Encoding> { fn content_encoding(&self) -> Option<Encoding> {
let encodings = match self.headers().get::<ContentEncoding>() { let &ContentEncoding(ref encodings) = self.headers().get()?;
Some(&ContentEncoding(ref encodings)) => encodings,
None => return None,
};
if encodings.contains(&Encoding::Gzip) { if encodings.contains(&Encoding::Gzip) {
Some(Encoding::Gzip) Some(Encoding::Gzip)
} else if encodings.contains(&Encoding::Deflate) { } else if encodings.contains(&Encoding::Deflate) {

View file

@ -515,16 +515,11 @@ mod system_reporter {
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
// Like std::macros::try!, but for Option<>. let mut f = File::open("/proc/self/statm").ok()?;
macro_rules! option_try(
($e:expr) => (match $e { Some(e) => e, None => return None })
);
let mut f = option_try!(File::open("/proc/self/statm").ok());
let mut contents = String::new(); let mut contents = String::new();
option_try!(f.read_to_string(&mut contents).ok()); f.read_to_string(&mut contents).ok()?;
let s = option_try!(contents.split_whitespace().nth(field)); let s = contents.split_whitespace().nth(field)?;
let npages = option_try!(s.parse::<usize>().ok()); let npages = s.parse::<usize>().ok()?;
Some(npages * page_size()) Some(npages * page_size())
} }

View file

@ -2072,10 +2072,9 @@ fn get_registrable_domain_suffix_of_or_is_equal_to(host_suffix_string: &str, ori
}; };
// Step 4.2 // Step 4.2
let (prefix, suffix) = match original_host.len().checked_sub(host.len()) { let index = original_host.len().checked_sub(host.len())?;
Some(index) => original_host.split_at(index), let (prefix, suffix) = original_host.split_at(index);
None => return None,
};
if !prefix.ends_with(".") { if !prefix.ends_with(".") {
return None; return None;
} }
@ -2319,11 +2318,7 @@ impl Document {
/// ///
/// Also, shouldn't return an option, I'm quite sure. /// Also, shouldn't return an option, I'm quite sure.
pub fn device(&self) -> Option<Device> { pub fn device(&self) -> Option<Device> {
let window_size = match self.window().window_size() { let window_size = self.window().window_size()?;
Some(ws) => ws,
None => return None,
};
let viewport_size = window_size.initial_viewport; let viewport_size = window_size.initial_viewport;
let device_pixel_ratio = window_size.device_pixel_ratio; let device_pixel_ratio = window_size.device_pixel_ratio;
Some(Device::new(MediaType::screen(), viewport_size, device_pixel_ratio)) Some(Device::new(MediaType::screen(), viewport_size, device_pixel_ratio))
@ -4017,12 +4012,9 @@ impl PendingInOrderScriptVec {
fn take_next_ready_to_be_executed(&self) -> Option<(DomRoot<HTMLScriptElement>, ScriptResult)> { fn take_next_ready_to_be_executed(&self) -> Option<(DomRoot<HTMLScriptElement>, ScriptResult)> {
let mut scripts = self.scripts.borrow_mut(); let mut scripts = self.scripts.borrow_mut();
let pair = scripts.front_mut().and_then(PendingScript::take_result); let pair = scripts.front_mut()?.take_result()?;
if pair.is_none() {
return None;
}
scripts.pop_front(); scripts.pop_front();
pair Some(pair)
} }
fn clear(&self) { fn clear(&self) {

View file

@ -1039,24 +1039,20 @@ impl Element {
// https://dom.spec.whatwg.org/#locate-a-namespace-prefix // https://dom.spec.whatwg.org/#locate-a-namespace-prefix
pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> { pub fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> {
for node in self.upcast::<Node>().inclusive_ancestors() { for node in self.upcast::<Node>().inclusive_ancestors() {
match node.downcast::<Element>() { let element = node.downcast::<Element>()?;
Some(element) => { // Step 1.
// Step 1. if *element.namespace() == namespace {
if *element.namespace() == namespace { if let Some(prefix) = element.GetPrefix() {
if let Some(prefix) = element.GetPrefix() { return Some(prefix);
return Some(prefix); }
} }
}
// Step 2. // Step 2.
for attr in element.attrs.borrow().iter() { for attr in element.attrs.borrow().iter() {
if attr.prefix() == Some(&namespace_prefix!("xmlns")) && if attr.prefix() == Some(&namespace_prefix!("xmlns")) &&
**attr.value() == *namespace { **attr.value() == *namespace {
return Some(attr.LocalName()); return Some(attr.LocalName());
} }
}
},
None => return None,
} }
} }
None None

View file

@ -219,12 +219,7 @@ impl HTMLCanvasElement {
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender)); let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
context.get_ipc_renderer().send(msg).unwrap(); context.get_ipc_renderer().send(msg).unwrap();
match receiver.recv().unwrap() { receiver.recv().unwrap()?
Some(pixels) => pixels,
None => {
return None;
}
}
}, },
Some(&CanvasContext::WebGL(_)) => { Some(&CanvasContext::WebGL(_)) => {
// TODO: add a method in WebGLRenderingContext to get the pixels. // TODO: add a method in WebGLRenderingContext to get the pixels.

View file

@ -588,17 +588,13 @@ impl HTMLIFrameElementMethods for HTMLIFrameElement {
// https://html.spec.whatwg.org/multipage/#concept-bcc-content-document // https://html.spec.whatwg.org/multipage/#concept-bcc-content-document
fn GetContentDocument(&self) -> Option<DomRoot<Document>> { fn GetContentDocument(&self) -> Option<DomRoot<Document>> {
// Step 1. // Step 1.
let pipeline_id = match self.pipeline_id.get() { let pipeline_id = self.pipeline_id.get()?;
None => return None,
Some(pipeline_id) => pipeline_id,
};
// Step 2-3. // Step 2-3.
// Note that this lookup will fail if the document is dissimilar-origin, // Note that this lookup will fail if the document is dissimilar-origin,
// so we should return None in that case. // so we should return None in that case.
let document = match ScriptThread::find_document(pipeline_id) { let document = ScriptThread::find_document(pipeline_id)?;
None => return None,
Some(document) => document,
};
// Step 4. // Step 4.
let current = GlobalScope::current().expect("No current global object").as_window().Document(); let current = GlobalScope::current().expect("No current global object").as_window().Document();
if !current.origin().same_origin_domain(document.origin()) { if !current.origin().same_origin_domain(document.origin()) {

View file

@ -661,10 +661,7 @@ impl HTMLImageElement {
} }
pub fn areas(&self) -> Option<Vec<DomRoot<HTMLAreaElement>>> { pub fn areas(&self) -> Option<Vec<DomRoot<HTMLAreaElement>>> {
let elem = self.upcast::<Element>(); let elem = self.upcast::<Element>();
let usemap_attr = match elem.get_attribute(&ns!(), &local_name!("usemap")) { let usemap_attr = elem.get_attribute(&ns!(), &local_name!("usemap"))?;
Some(attr) => attr,
None => return None,
};
let value = usemap_attr.value(); let value = usemap_attr.value();

View file

@ -1206,11 +1206,7 @@ pub struct FollowingNodeIterator {
impl FollowingNodeIterator { impl FollowingNodeIterator {
/// Skips iterating the children of the current node /// Skips iterating the children of the current node
pub fn next_skipping_children(&mut self) -> Option<DomRoot<Node>> { pub fn next_skipping_children(&mut self) -> Option<DomRoot<Node>> {
let current = match self.current.take() { let current = self.current.take()?;
None => return None,
Some(current) => current,
};
self.next_skipping_children_impl(current) self.next_skipping_children_impl(current)
} }
@ -1244,10 +1240,7 @@ impl Iterator for FollowingNodeIterator {
// https://dom.spec.whatwg.org/#concept-tree-following // https://dom.spec.whatwg.org/#concept-tree-following
fn next(&mut self) -> Option<DomRoot<Node>> { fn next(&mut self) -> Option<DomRoot<Node>> {
let current = match self.current.take() { let current = self.current.take()?;
None => return None,
Some(current) => current,
};
if let Some(first_child) = current.GetFirstChild() { if let Some(first_child) = current.GetFirstChild() {
self.current = Some(first_child); self.current = Some(first_child);
@ -1268,10 +1261,7 @@ impl Iterator for PrecedingNodeIterator {
// https://dom.spec.whatwg.org/#concept-tree-preceding // https://dom.spec.whatwg.org/#concept-tree-preceding
fn next(&mut self) -> Option<DomRoot<Node>> { fn next(&mut self) -> Option<DomRoot<Node>> {
let current = match self.current.take() { let current = self.current.take()?;
None => return None,
Some(current) => current,
};
self.current = if self.root == current { self.current = if self.root == current {
None None
@ -1323,10 +1313,7 @@ impl TreeIterator {
} }
pub fn next_skipping_children(&mut self) -> Option<DomRoot<Node>> { pub fn next_skipping_children(&mut self) -> Option<DomRoot<Node>> {
let current = match self.current.take() { let current = self.current.take()?;
None => return None,
Some(current) => current,
};
self.next_skipping_children_impl(current) self.next_skipping_children_impl(current)
} }
@ -1353,10 +1340,7 @@ impl Iterator for TreeIterator {
// https://dom.spec.whatwg.org/#concept-tree-order // https://dom.spec.whatwg.org/#concept-tree-order
fn next(&mut self) -> Option<DomRoot<Node>> { fn next(&mut self) -> Option<DomRoot<Node>> {
let current = match self.current.take() { let current = self.current.take()?;
None => return None,
Some(current) => current,
};
if let Some(first_child) = current.GetFirstChild() { if let Some(first_child) = current.GetFirstChild() {
self.current = Some(first_child); self.current = Some(first_child);
self.depth += 1; self.depth += 1;

View file

@ -480,10 +480,7 @@ impl<I> Iterator for FragmentParsingResult<I>
type Item = DomRoot<Node>; type Item = DomRoot<Node>;
fn next(&mut self) -> Option<DomRoot<Node>> { fn next(&mut self) -> Option<DomRoot<Node>> {
let next = match self.inner.next() { let next = self.inner.next()?;
Some(next) => next,
None => return None,
};
next.remove_self(); next.remove_self();
Some(next) Some(next)
} }

View file

@ -395,13 +395,9 @@ impl TreeWalker {
None => { None => {
let mut candidate = DomRoot::from_ref(node); let mut candidate = DomRoot::from_ref(node);
while !self.is_root_node(&candidate) && candidate.GetNextSibling().is_none() { while !self.is_root_node(&candidate) && candidate.GetNextSibling().is_none() {
match candidate.GetParentNode() { // This can return None if the user set the current node to somewhere
None => // outside of the tree rooted at the original root.
// This can happen if the user set the current node to somewhere candidate = candidate.GetParentNode()?;
// outside of the tree rooted at the original root.
return None,
Some(n) => candidate = n
}
} }
if self.is_root_node(&candidate) { if self.is_root_node(&candidate) {
None None

View file

@ -592,15 +592,11 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-frameelement // https://html.spec.whatwg.org/multipage/#dom-frameelement
fn GetFrameElement(&self) -> Option<DomRoot<Element>> { fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
// Steps 1-3. // Steps 1-3.
let window_proxy = match self.window_proxy.get() { let window_proxy = self.window_proxy.get()?;
None => return None,
Some(window_proxy) => window_proxy,
};
// Step 4-5. // Step 4-5.
let container = match window_proxy.frame_element() { let container = window_proxy.frame_element()?;
None => return None,
Some(container) => container,
};
// Step 6. // Step 6.
let container_doc = document_from_node(container); let container_doc = document_from_node(container);
let current_doc = GlobalScope::current().expect("No current global object").as_window().Document(); let current_doc = GlobalScope::current().expect("No current global object").as_window().Document();
@ -688,10 +684,8 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-parent // https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<DomRoot<WindowProxy>> { fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3. // Steps 1-3.
let window_proxy = match self.undiscarded_window_proxy() { let window_proxy = self.undiscarded_window_proxy()?;
Some(window_proxy) => window_proxy,
None => return None,
};
// Step 4. // Step 4.
if let Some(parent) = window_proxy.parent() { if let Some(parent) = window_proxy.parent() {
return Some(DomRoot::from_ref(parent)); return Some(DomRoot::from_ref(parent));
@ -703,10 +697,8 @@ impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-top // https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<DomRoot<WindowProxy>> { fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3. // Steps 1-3.
let window_proxy = match self.undiscarded_window_proxy() { let window_proxy = self.undiscarded_window_proxy()?;
Some(window_proxy) => window_proxy,
None => return None,
};
// Steps 4-5. // Steps 4-5.
Some(DomRoot::from_ref(window_proxy.top())) Some(DomRoot::from_ref(window_proxy.top()))
} }

View file

@ -1946,10 +1946,7 @@ impl ScriptThread {
pipeline_id: PipelineId) pipeline_id: PipelineId)
-> Option<DomRoot<WindowProxy>> -> Option<DomRoot<WindowProxy>>
{ {
let browsing_context_id = match self.ask_constellation_for_browsing_context_id(pipeline_id) { let browsing_context_id = self.ask_constellation_for_browsing_context_id(pipeline_id)?;
Some(browsing_context_id) => browsing_context_id,
None => return None,
};
if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) { if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) {
return Some(DomRoot::from_ref(window_proxy)); return Some(DomRoot::from_ref(window_proxy));
} }