file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
htmllinkelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use document_loader::LoadType; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use encoding::EncodingRef; use encoding::all::UTF_8; use hyper::header::ContentType; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use layout_interface::Msg; use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError}; use network_listener::{NetworkListener, PreInvoke}; use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use std::mem; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::attr::AttrValue; use style::media_queries::{MediaQueryList, parse_media_query_list}; use style::parser::ParserContextExtraData; use style::servo::Stylesheet; use style::stylesheets::Origin; use url::Url; use util::str::HTML_SPACE_CHARACTERS; no_jsmanaged_fields!(Stylesheet); #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, } impl HTMLLinkElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator == ElementCreator::ParserCreated), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> Root<HTMLLinkElement> { let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator); Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap) } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } fn get_attr(element: &Element, local_name: &Atom) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => { let mut found_stylesheet = false; for s in value.split(HTML_SPACE_CHARACTERS).into_iter() { if s.eq_ignore_ascii_case("alternate") { return false; } if s.eq_ignore_ascii_case("stylesheet") { found_stylesheet = true; } } found_stylesheet }, None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// https://html.spec.whatwg.org/multipage/#rel-icon fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => { value.split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")) }, None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed { return; } let rel = get_attr(self.upcast(), &atom!("rel")); match attr.local_name() {
self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &atom!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) { self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string())); } } }, &atom!("media") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } }, _ => {}, } } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &atom!("rel")); let href = get_attr(element, &atom!("href")); let sizes = get_attr(self.upcast(), &atom!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); } Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); } _ => {} } } } } impl HTMLLinkElement { fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let element = self.upcast::<Element>(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); // TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match. let elem = Trusted::new(self); let context = Arc::new(Mutex::new(StylesheetContext { elem: elem, media: Some(media), data: vec!(), metadata: None, url: url.clone(), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, script_chan: document.window().networking_task_source(), }; let response_target = AsyncResponseTarget { sender: action_sender, }; ROUTER.add_route(action_receiver.to_opaque(), box move |message| { listener.notify_action(message.to().unwrap()); }); if self.parser_inserted.get() { document.increment_script_blocking_stylesheet_count(); } document.load_async(LoadType::Stylesheet(url), response_target); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let event = ConstellationMsg::NewFavicon(url.clone()); document.window().constellation_chan().send(event).unwrap(); let mozbrowser_event = match *sizes { Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()), None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned()) }; document.trigger_mozbrowser_event(mozbrowser_event); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } } /// The context required for asynchronously loading an external stylesheet. struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLLinkElement>, media: Option<MediaQueryList>, /// The response body received to date. data: Vec<u8>, /// The response metadata received to date. metadata: Option<Metadata>, /// The initial URL requested. url: Url, } impl PreInvoke for StylesheetContext {} impl AsyncResponseListener for StylesheetContext { fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) { self.metadata = metadata.ok(); if let Some(ref meta) = self.metadata { if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type { } else { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); } } } fn data_available(&mut self, payload: Vec<u8>) { let mut payload = payload; self.data.append(&mut payload); } fn response_complete(&mut self, status: Result<(), NetworkError>) { if status.is_err() { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); return; } let data = mem::replace(&mut self.data, vec!()); let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8 as EncodingRef; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let elem = self.elem.root(); let win = window_from_node(&*elem); let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let media = self.media.take().unwrap(); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); let elem = elem.r(); let document = document_from_node(elem); let document = document.r(); let win = window_from_node(elem); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *elem.stylesheet.borrow_mut() = Some(sheet); document.invalidate_stylesheets(); if elem.parser_inserted.get() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_setter!(SetRel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); }
&atom!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &atom!("sizes"));
random_line_split
htmllinkelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use document_loader::LoadType; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use encoding::EncodingRef; use encoding::all::UTF_8; use hyper::header::ContentType; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use layout_interface::Msg; use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError}; use network_listener::{NetworkListener, PreInvoke}; use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use std::mem; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::attr::AttrValue; use style::media_queries::{MediaQueryList, parse_media_query_list}; use style::parser::ParserContextExtraData; use style::servo::Stylesheet; use style::stylesheets::Origin; use url::Url; use util::str::HTML_SPACE_CHARACTERS; no_jsmanaged_fields!(Stylesheet); #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, } impl HTMLLinkElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator == ElementCreator::ParserCreated), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> Root<HTMLLinkElement> { let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator); Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap) } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } fn get_attr(element: &Element, local_name: &Atom) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => { let mut found_stylesheet = false; for s in value.split(HTML_SPACE_CHARACTERS).into_iter() { if s.eq_ignore_ascii_case("alternate") { return false; } if s.eq_ignore_ascii_case("stylesheet") { found_stylesheet = true; } } found_stylesheet }, None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// https://html.spec.whatwg.org/multipage/#rel-icon fn is_favicon(value: &Option<String>) -> bool
impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed { return; } let rel = get_attr(self.upcast(), &atom!("rel")); match attr.local_name() { &atom!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &atom!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &atom!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) { self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string())); } } }, &atom!("media") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } }, _ => {}, } } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &atom!("rel")); let href = get_attr(element, &atom!("href")); let sizes = get_attr(self.upcast(), &atom!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); } Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); } _ => {} } } } } impl HTMLLinkElement { fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let element = self.upcast::<Element>(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); // TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match. let elem = Trusted::new(self); let context = Arc::new(Mutex::new(StylesheetContext { elem: elem, media: Some(media), data: vec!(), metadata: None, url: url.clone(), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, script_chan: document.window().networking_task_source(), }; let response_target = AsyncResponseTarget { sender: action_sender, }; ROUTER.add_route(action_receiver.to_opaque(), box move |message| { listener.notify_action(message.to().unwrap()); }); if self.parser_inserted.get() { document.increment_script_blocking_stylesheet_count(); } document.load_async(LoadType::Stylesheet(url), response_target); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let event = ConstellationMsg::NewFavicon(url.clone()); document.window().constellation_chan().send(event).unwrap(); let mozbrowser_event = match *sizes { Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()), None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned()) }; document.trigger_mozbrowser_event(mozbrowser_event); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } } /// The context required for asynchronously loading an external stylesheet. struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLLinkElement>, media: Option<MediaQueryList>, /// The response body received to date. data: Vec<u8>, /// The response metadata received to date. metadata: Option<Metadata>, /// The initial URL requested. url: Url, } impl PreInvoke for StylesheetContext {} impl AsyncResponseListener for StylesheetContext { fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) { self.metadata = metadata.ok(); if let Some(ref meta) = self.metadata { if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type { } else { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); } } } fn data_available(&mut self, payload: Vec<u8>) { let mut payload = payload; self.data.append(&mut payload); } fn response_complete(&mut self, status: Result<(), NetworkError>) { if status.is_err() { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); return; } let data = mem::replace(&mut self.data, vec!()); let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8 as EncodingRef; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let elem = self.elem.root(); let win = window_from_node(&*elem); let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let media = self.media.take().unwrap(); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); let elem = elem.r(); let document = document_from_node(elem); let document = document.r(); let win = window_from_node(elem); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *elem.stylesheet.borrow_mut() = Some(sheet); document.invalidate_stylesheets(); if elem.parser_inserted.get() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_setter!(SetRel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); }
{ match *value { Some(ref value) => { value.split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")) }, None => false, } }
identifier_body
htmllinkelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser as CssParser; use document_loader::LoadType; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::bindings::str::DOMString; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use encoding::EncodingRef; use encoding::all::UTF_8; use hyper::header::ContentType; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use layout_interface::Msg; use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError}; use network_listener::{NetworkListener, PreInvoke}; use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use std::mem; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::attr::AttrValue; use style::media_queries::{MediaQueryList, parse_media_query_list}; use style::parser::ParserContextExtraData; use style::servo::Stylesheet; use style::stylesheets::Origin; use url::Url; use util::str::HTML_SPACE_CHARACTERS; no_jsmanaged_fields!(Stylesheet); #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>, /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts parser_inserted: Cell<bool>, } impl HTMLLinkElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator == ElementCreator::ParserCreated), stylesheet: DOMRefCell::new(None), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document, creator: ElementCreator) -> Root<HTMLLinkElement> { let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator); Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap) } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } } fn get_attr(element: &Element, local_name: &Atom) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => { let mut found_stylesheet = false; for s in value.split(HTML_SPACE_CHARACTERS).into_iter() { if s.eq_ignore_ascii_case("alternate") { return false; } if s.eq_ignore_ascii_case("stylesheet") { found_stylesheet = true; } } found_stylesheet }, None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// https://html.spec.whatwg.org/multipage/#rel-icon fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => { value.split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")) }, None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed { return; } let rel = get_attr(self.upcast(), &atom!("rel")); match attr.local_name() { &atom!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &atom!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &atom!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) { self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string())); } } }, &atom!("media") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } }, _ => {}, } } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn
(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &atom!("rel")); let href = get_attr(element, &atom!("href")); let sizes = get_attr(self.upcast(), &atom!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); } Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); } _ => {} } } } } impl HTMLLinkElement { fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let element = self.upcast::<Element>(); let mq_attribute = element.get_attribute(&ns!(), &atom!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut css_parser = CssParser::new(&mq_str); let media = parse_media_query_list(&mut css_parser); // TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match. let elem = Trusted::new(self); let context = Arc::new(Mutex::new(StylesheetContext { elem: elem, media: Some(media), data: vec!(), metadata: None, url: url.clone(), })); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, script_chan: document.window().networking_task_source(), }; let response_target = AsyncResponseTarget { sender: action_sender, }; ROUTER.add_route(action_receiver.to_opaque(), box move |message| { listener.notify_action(message.to().unwrap()); }); if self.parser_inserted.get() { document.increment_script_blocking_stylesheet_count(); } document.load_async(LoadType::Stylesheet(url), response_target); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let event = ConstellationMsg::NewFavicon(url.clone()); document.window().constellation_chan().send(event).unwrap(); let mozbrowser_event = match *sizes { Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()), None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned()) }; document.trigger_mozbrowser_event(mozbrowser_event); } Err(e) => debug!("Parsing url {} failed: {}", href, e) } } } /// The context required for asynchronously loading an external stylesheet. struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLLinkElement>, media: Option<MediaQueryList>, /// The response body received to date. data: Vec<u8>, /// The response metadata received to date. metadata: Option<Metadata>, /// The initial URL requested. url: Url, } impl PreInvoke for StylesheetContext {} impl AsyncResponseListener for StylesheetContext { fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) { self.metadata = metadata.ok(); if let Some(ref meta) = self.metadata { if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type { } else { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); } } } fn data_available(&mut self, payload: Vec<u8>) { let mut payload = payload; self.data.append(&mut payload); } fn response_complete(&mut self, status: Result<(), NetworkError>) { if status.is_err() { self.elem.root().upcast::<EventTarget>().fire_simple_event("error"); return; } let data = mem::replace(&mut self.data, vec!()); let metadata = match self.metadata.take() { Some(meta) => meta, None => return, }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8 as EncodingRef; let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s); let final_url = metadata.final_url; let elem = self.elem.root(); let win = window_from_node(&*elem); let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label, Some(environment_encoding), Origin::Author, win.css_error_reporter(), ParserContextExtraData::default()); let media = self.media.take().unwrap(); sheet.set_media(Some(media)); let sheet = Arc::new(sheet); let elem = elem.r(); let document = document_from_node(elem); let document = document.r(); let win = window_from_node(elem); win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap(); *elem.stylesheet.borrow_mut() = Some(sheet); document.invalidate_stylesheets(); if elem.parser_inserted.get() { document.decrement_script_blocking_stylesheet_count(); } document.finish_load(LoadType::Stylesheet(self.url.clone())); } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_setter!(SetRel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); }
bind_to_tree
identifier_name
timer_scheduler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::{self, IpcSender}; use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg}; use std::cmp::{self, Ord}; use std::collections::BinaryHeap; use std::sync::mpsc; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::thread; use std::time::{Duration, Instant}; pub struct TimerScheduler; struct ScheduledEvent { request: TimerEventRequest, for_time: Instant, } impl Ord for ScheduledEvent { fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering { self.for_time.cmp(&other.for_time).reverse() } } impl PartialOrd for ScheduledEvent { fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering>
} impl Eq for ScheduledEvent {} impl PartialEq for ScheduledEvent { fn eq(&self, other: &ScheduledEvent) -> bool { self as *const ScheduledEvent == other as *const ScheduledEvent } } impl TimerScheduler { pub fn start() -> IpcSender<TimerSchedulerMsg> { let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed."); let (req_sender, req_receiver) = mpsc::sync_channel(1); // We could do this much more directly with recv_timeout // (https://github.com/rust-lang/rfcs/issues/962). // util::thread doesn't give us access to the JoinHandle, which we need for park/unpark, // so we use the builder directly. let timeout_thread = thread::Builder::new() .name(String::from("TimerScheduler")) .spawn(move || { // We maintain a priority queue of future events, sorted by due time. let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new(); loop { let now = Instant::now(); // Dispatch any events whose due time is past loop { match scheduled_events.peek() { // Dispatch the event if its due time is past Some(event) if event.for_time <= now => { let TimerEventRequest(ref sender, source, id, _) = event.request; let _ = sender.send(TimerEvent(source, id)); }, // Otherwise, we're done dispatching events _ => break, } // Remove the event from the priority queue // (Note this only executes when the first event has been dispatched scheduled_events.pop(); } // Look to see if there are any incoming events match req_receiver.try_recv() { // If there is an event, add it to the priority queue Ok(TimerSchedulerMsg::Request(req)) => { let TimerEventRequest(_, _, _, delay) = req; let schedule = Instant::now() + Duration::from_millis(delay.get()); let event = ScheduledEvent { request: req, for_time: schedule }; scheduled_events.push(event); }, // If there is no incoming event, park the thread, // it will either be unparked when a new event arrives, // or by a timeout. Err(Empty) => match scheduled_events.peek() { None => thread::park(), Some(event) => thread::park_timeout(event.for_time - now), }, // If the channel is closed or we are shutting down, we are done. Ok(TimerSchedulerMsg::Exit) | Err(Disconnected) => break, } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerScheduler thread terminated."); }) .expect("Thread creation failed.") .thread() .clone(); // A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread, // and unparks the timeout thread each time. Note that if unpark is called while the timeout // thread isn't parked, this causes the next call to thread::park by the timeout thread // not to block. This means that the timeout thread won't park when there is a request // waiting in the MPSC channel buffer. thread::Builder::new() .name(String::from("TimerProxy")) .spawn(move || { while let Ok(req) = req_ipc_receiver.recv() { let mut shutting_down = false; match req { TimerSchedulerMsg::Exit => shutting_down = true, _ => {} } let _ = req_sender.send(req); timeout_thread.unpark(); if shutting_down { break; } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerProxy thread terminated."); }) .expect("Thread creation failed."); // Return the IPC sender req_ipc_sender } }
{ Some(self.cmp(other)) }
identifier_body
timer_scheduler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::{self, IpcSender}; use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg}; use std::cmp::{self, Ord}; use std::collections::BinaryHeap; use std::sync::mpsc; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::thread; use std::time::{Duration, Instant}; pub struct
; struct ScheduledEvent { request: TimerEventRequest, for_time: Instant, } impl Ord for ScheduledEvent { fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering { self.for_time.cmp(&other.for_time).reverse() } } impl PartialOrd for ScheduledEvent { fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl Eq for ScheduledEvent {} impl PartialEq for ScheduledEvent { fn eq(&self, other: &ScheduledEvent) -> bool { self as *const ScheduledEvent == other as *const ScheduledEvent } } impl TimerScheduler { pub fn start() -> IpcSender<TimerSchedulerMsg> { let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed."); let (req_sender, req_receiver) = mpsc::sync_channel(1); // We could do this much more directly with recv_timeout // (https://github.com/rust-lang/rfcs/issues/962). // util::thread doesn't give us access to the JoinHandle, which we need for park/unpark, // so we use the builder directly. let timeout_thread = thread::Builder::new() .name(String::from("TimerScheduler")) .spawn(move || { // We maintain a priority queue of future events, sorted by due time. let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new(); loop { let now = Instant::now(); // Dispatch any events whose due time is past loop { match scheduled_events.peek() { // Dispatch the event if its due time is past Some(event) if event.for_time <= now => { let TimerEventRequest(ref sender, source, id, _) = event.request; let _ = sender.send(TimerEvent(source, id)); }, // Otherwise, we're done dispatching events _ => break, } // Remove the event from the priority queue // (Note this only executes when the first event has been dispatched scheduled_events.pop(); } // Look to see if there are any incoming events match req_receiver.try_recv() { // If there is an event, add it to the priority queue Ok(TimerSchedulerMsg::Request(req)) => { let TimerEventRequest(_, _, _, delay) = req; let schedule = Instant::now() + Duration::from_millis(delay.get()); let event = ScheduledEvent { request: req, for_time: schedule }; scheduled_events.push(event); }, // If there is no incoming event, park the thread, // it will either be unparked when a new event arrives, // or by a timeout. Err(Empty) => match scheduled_events.peek() { None => thread::park(), Some(event) => thread::park_timeout(event.for_time - now), }, // If the channel is closed or we are shutting down, we are done. Ok(TimerSchedulerMsg::Exit) | Err(Disconnected) => break, } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerScheduler thread terminated."); }) .expect("Thread creation failed.") .thread() .clone(); // A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread, // and unparks the timeout thread each time. Note that if unpark is called while the timeout // thread isn't parked, this causes the next call to thread::park by the timeout thread // not to block. This means that the timeout thread won't park when there is a request // waiting in the MPSC channel buffer. thread::Builder::new() .name(String::from("TimerProxy")) .spawn(move || { while let Ok(req) = req_ipc_receiver.recv() { let mut shutting_down = false; match req { TimerSchedulerMsg::Exit => shutting_down = true, _ => {} } let _ = req_sender.send(req); timeout_thread.unpark(); if shutting_down { break; } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerProxy thread terminated."); }) .expect("Thread creation failed."); // Return the IPC sender req_ipc_sender } }
TimerScheduler
identifier_name
timer_scheduler.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::{self, IpcSender}; use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg}; use std::cmp::{self, Ord}; use std::collections::BinaryHeap; use std::sync::mpsc; use std::sync::mpsc::TryRecvError::{Disconnected, Empty}; use std::thread; use std::time::{Duration, Instant}; pub struct TimerScheduler; struct ScheduledEvent { request: TimerEventRequest, for_time: Instant, } impl Ord for ScheduledEvent { fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering { self.for_time.cmp(&other.for_time).reverse() } } impl PartialOrd for ScheduledEvent { fn partial_cmp(&self, other: &ScheduledEvent) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl Eq for ScheduledEvent {} impl PartialEq for ScheduledEvent { fn eq(&self, other: &ScheduledEvent) -> bool { self as *const ScheduledEvent == other as *const ScheduledEvent } } impl TimerScheduler { pub fn start() -> IpcSender<TimerSchedulerMsg> { let (req_ipc_sender, req_ipc_receiver) = ipc::channel().expect("Channel creation failed."); let (req_sender, req_receiver) = mpsc::sync_channel(1); // We could do this much more directly with recv_timeout // (https://github.com/rust-lang/rfcs/issues/962). // util::thread doesn't give us access to the JoinHandle, which we need for park/unpark, // so we use the builder directly. let timeout_thread = thread::Builder::new() .name(String::from("TimerScheduler")) .spawn(move || {
// We maintain a priority queue of future events, sorted by due time. let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new(); loop { let now = Instant::now(); // Dispatch any events whose due time is past loop { match scheduled_events.peek() { // Dispatch the event if its due time is past Some(event) if event.for_time <= now => { let TimerEventRequest(ref sender, source, id, _) = event.request; let _ = sender.send(TimerEvent(source, id)); }, // Otherwise, we're done dispatching events _ => break, } // Remove the event from the priority queue // (Note this only executes when the first event has been dispatched scheduled_events.pop(); } // Look to see if there are any incoming events match req_receiver.try_recv() { // If there is an event, add it to the priority queue Ok(TimerSchedulerMsg::Request(req)) => { let TimerEventRequest(_, _, _, delay) = req; let schedule = Instant::now() + Duration::from_millis(delay.get()); let event = ScheduledEvent { request: req, for_time: schedule }; scheduled_events.push(event); }, // If there is no incoming event, park the thread, // it will either be unparked when a new event arrives, // or by a timeout. Err(Empty) => match scheduled_events.peek() { None => thread::park(), Some(event) => thread::park_timeout(event.for_time - now), }, // If the channel is closed or we are shutting down, we are done. Ok(TimerSchedulerMsg::Exit) | Err(Disconnected) => break, } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerScheduler thread terminated."); }) .expect("Thread creation failed.") .thread() .clone(); // A proxy that just routes incoming IPC requests over the MPSC channel to the timeout thread, // and unparks the timeout thread each time. Note that if unpark is called while the timeout // thread isn't parked, this causes the next call to thread::park by the timeout thread // not to block. This means that the timeout thread won't park when there is a request // waiting in the MPSC channel buffer. thread::Builder::new() .name(String::from("TimerProxy")) .spawn(move || { while let Ok(req) = req_ipc_receiver.recv() { let mut shutting_down = false; match req { TimerSchedulerMsg::Exit => shutting_down = true, _ => {} } let _ = req_sender.send(req); timeout_thread.unpark(); if shutting_down { break; } } // This thread can terminate if the req_ipc_sender is dropped. warn!("TimerProxy thread terminated."); }) .expect("Thread creation failed."); // Return the IPC sender req_ipc_sender } }
random_line_split
d3d11on12.rs
// Copyright © 2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! Mappings for the content of d3d11on12.h use ctypes::c_void; use shared::guiddef::IID; use shared::minwindef::UINT; use um::d3d11::{ID3D11Device, ID3D11DeviceContext, ID3D11Resource}; use um::d3d12::D3D12_RESOURCE_STATES; use um::d3dcommon::D3D_FEATURE_LEVEL; use um::unknwnbase::{IUnknown, IUnknownVtbl}; use um::winnt::HRESULT; FN!{stdcall PFN_D3D11ON12_CREATE_DEVICE( *mut IUnknown, UINT, *const D3D_FEATURE_LEVEL, UINT, *mut *mut IUnknown, UINT, UINT, *mut *mut ID3D11Device, *mut *mut ID3D11DeviceContext, *mut D3D_FEATURE_LEVEL, ) -> HRESULT} extern "system"{ pub fn D3D11On12CreateDevice( pDevice: *mut IUnknown, Flags: UINT, pFeatureLevels: *const D3D_FEATURE_LEVEL, FeatureLevels: UINT, ppCommandQueues: *mut *mut IUnknown, NumQueues: UINT, NodeMask: UINT, ppDevice: *mut *mut ID3D11Device, ppImmediateContext: *mut *mut ID3D11DeviceContext, pChosenFeatureLevel: *mut D3D_FEATURE_LEVEL ) -> HRESULT; } STRUCT!{struct D3D11_RESOURCE_FLAGS { BindFlags: UINT, MiscFlags: UINT, CPUAccessFlags: UINT, StructureByteStride: UINT, }} RIDL!{#[uuid(0x85611e73, 0x70a9, 0x490e, 0x96, 0x14, 0xa9, 0xe3, 0x02, 0x77, 0x79, 0x04)] interface ID3D11On12Device(ID3D11On12DeviceVtbl): IUnknown(IUnknownVtbl) { fn CreateWrappedResource( pResource12: *mut IUnknown, pFlags11: *const D3D11_RESOURCE_FLAGS, InState: D3D12_RESOURCE_STATES, OutState: D3D12_RESOURCE_STATES, riid: *const IID, ppResource11: *mut *mut c_void, ) -> HRESULT, fn ReleaseWrappedResources( ppResources: *mut *mut ID3D11Resource, NumResources: UINT, ) -> (),
ppResources: *mut *mut ID3D11Resource, NumResources: UINT, ) -> (), }} DEFINE_GUID!{IID_ID3D11On12Device, 0x85611e73, 0x70a9, 0x490e, 0x96, 0x14, 0xa9, 0xe3, 0x02, 0x77, 0x79, 0x04}
fn AcquireWrappedResources(
random_line_split
tree.rs
use ai; use ai::value; use ai::StatelessAI; use game; use game::Position2; pub fn recursive_judgement( state: &game::State, my_color: game::Color, depth: u8, value_function: value::Simple, ) -> i32 { if depth == 0 ||!state.victory_state.active() { value_function.value_of(state, my_color) } else { let values = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement(&new_state, my_color, depth - 1, value_function); value }); if state.current_color == my_color
else { values.min() }.unwrap() } } pub struct TreeJudgementAI { search_depth: u8, value_function: value::Simple, } impl TreeJudgementAI { pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI { TreeJudgementAI { search_depth: depth, value_function, } } } impl StatelessAI for TreeJudgementAI { fn action(&self, state: &game::State) -> Position2 { let my_color = state.current_color; let graded_actions = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement( &new_state, my_color, self.search_depth - 1, self.value_function, ); (action, value) }); ai::random_best_move(graded_actions) } }
{ values.max() }
conditional_block
tree.rs
use ai; use ai::value; use ai::StatelessAI; use game; use game::Position2; pub fn recursive_judgement( state: &game::State, my_color: game::Color, depth: u8, value_function: value::Simple, ) -> i32 { if depth == 0 ||!state.victory_state.active() { value_function.value_of(state, my_color) } else { let values = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement(&new_state, my_color, depth - 1, value_function); value }); if state.current_color == my_color { values.max() } else { values.min() }.unwrap() } } pub struct TreeJudgementAI { search_depth: u8, value_function: value::Simple, } impl TreeJudgementAI { pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI
} impl StatelessAI for TreeJudgementAI { fn action(&self, state: &game::State) -> Position2 { let my_color = state.current_color; let graded_actions = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement( &new_state, my_color, self.search_depth - 1, self.value_function, ); (action, value) }); ai::random_best_move(graded_actions) } }
{ TreeJudgementAI { search_depth: depth, value_function, } }
identifier_body
tree.rs
use ai; use ai::value; use ai::StatelessAI; use game; use game::Position2; pub fn recursive_judgement( state: &game::State, my_color: game::Color, depth: u8, value_function: value::Simple, ) -> i32 { if depth == 0 ||!state.victory_state.active() { value_function.value_of(state, my_color) } else { let values = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action);
let value = recursive_judgement(&new_state, my_color, depth - 1, value_function); value }); if state.current_color == my_color { values.max() } else { values.min() }.unwrap() } } pub struct TreeJudgementAI { search_depth: u8, value_function: value::Simple, } impl TreeJudgementAI { pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI { TreeJudgementAI { search_depth: depth, value_function, } } } impl StatelessAI for TreeJudgementAI { fn action(&self, state: &game::State) -> Position2 { let my_color = state.current_color; let graded_actions = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement( &new_state, my_color, self.search_depth - 1, self.value_function, ); (action, value) }); ai::random_best_move(graded_actions) } }
random_line_split
tree.rs
use ai; use ai::value; use ai::StatelessAI; use game; use game::Position2; pub fn
( state: &game::State, my_color: game::Color, depth: u8, value_function: value::Simple, ) -> i32 { if depth == 0 ||!state.victory_state.active() { value_function.value_of(state, my_color) } else { let values = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement(&new_state, my_color, depth - 1, value_function); value }); if state.current_color == my_color { values.max() } else { values.min() }.unwrap() } } pub struct TreeJudgementAI { search_depth: u8, value_function: value::Simple, } impl TreeJudgementAI { pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI { TreeJudgementAI { search_depth: depth, value_function, } } } impl StatelessAI for TreeJudgementAI { fn action(&self, state: &game::State) -> Position2 { let my_color = state.current_color; let graded_actions = state.legal_actions().map(|action| { let mut new_state = state.clone(); new_state.execute(action); let value = recursive_judgement( &new_state, my_color, self.search_depth - 1, self.value_function, ); (action, value) }); ai::random_best_move(graded_actions) } }
recursive_judgement
identifier_name
postoffice.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use std::collections::BTreeSet; use std::iter::FromIterator; use tokio::{fs, io::AsyncWriteExt}; async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); let mut file = fs::File::create(conf_file).await?; let rt: Vec<String> = Vec::from_iter(routes); file.write_all(rt.join("\n").as_bytes()).await?; file.write(b"\n").await?; Ok(()) } async fn
() -> Result<BTreeSet<String>, ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); Ok(fs::read_to_string(conf_file) .await? .lines() .map(|s| s.to_string()) .collect()) } pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.insert(mailbox) { write_config(conf).await } else { Ok(()) } } pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.remove(&mailbox) { write_config(conf).await } else { Ok(()) } }
read_config
identifier_name
postoffice.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use std::collections::BTreeSet; use std::iter::FromIterator; use tokio::{fs, io::AsyncWriteExt}; async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); let mut file = fs::File::create(conf_file).await?; let rt: Vec<String> = Vec::from_iter(routes); file.write_all(rt.join("\n").as_bytes()).await?; file.write(b"\n").await?; Ok(()) } async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); Ok(fs::read_to_string(conf_file) .await? .lines() .map(|s| s.to_string()) .collect()) } pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.insert(mailbox) { write_config(conf).await } else { Ok(()) } } pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError>
{ let mut conf = read_config().await?; if conf.remove(&mailbox) { write_config(conf).await } else { Ok(()) } }
identifier_body
postoffice.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use std::collections::BTreeSet; use std::iter::FromIterator; use tokio::{fs, io::AsyncWriteExt}; async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); let mut file = fs::File::create(conf_file).await?;
Ok(()) } async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); Ok(fs::read_to_string(conf_file) .await? .lines() .map(|s| s.to_string()) .collect()) } pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.insert(mailbox) { write_config(conf).await } else { Ok(()) } } pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.remove(&mailbox) { write_config(conf).await } else { Ok(()) } }
let rt: Vec<String> = Vec::from_iter(routes); file.write_all(rt.join("\n").as_bytes()).await?; file.write(b"\n").await?;
random_line_split
postoffice.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{agent_error::ImlAgentError, env}; use std::collections::BTreeSet; use std::iter::FromIterator; use tokio::{fs, io::AsyncWriteExt}; async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); let mut file = fs::File::create(conf_file).await?; let rt: Vec<String> = Vec::from_iter(routes); file.write_all(rt.join("\n").as_bytes()).await?; file.write(b"\n").await?; Ok(()) } async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> { let conf_file = env::get_var("POSTMAN_CONF_PATH"); Ok(fs::read_to_string(conf_file) .await? .lines() .map(|s| s.to_string()) .collect()) } pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.insert(mailbox) { write_config(conf).await } else { Ok(()) } } pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> { let mut conf = read_config().await?; if conf.remove(&mailbox)
else { Ok(()) } }
{ write_config(conf).await }
conditional_block
3_16_exercise_springs.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 3-16: Exercise Springs use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } // Spring Type describes an anchor point that can connect to "Bob" objects via a spring // Thank you: http://www.myphysicslab.com/spring2d.html struct Spring { // Rest length and spring constant len: f32, k: f32, } impl Spring { fn new(l: f32) -> Self { Spring { len: l, k: 0.2 } } // Calculate spring force fn update(&self, a: &mut Bob, b: &mut Bob) { // Vector pointing from anchor to bob position let mut force = a.position - b.position; // What is the distance let d = force.magnitude(); // Stretch is difference between current distance and rest length let stretch = d - self.len; // Calculate force according to Hooke's Law // F = k * stretch force = force.normalize(); force *= -1.0 * self.k * stretch; a.apply_force(force); force *= -1.0; b.apply_force(force); } fn display(&self, draw: &Draw, a: &Bob, b: &Bob) { draw.line() .start(a.position) .end(b.position) .color(BLACK) .stroke_weight(2.0); } } struct Bob { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, damping: f32, drag_offset: Vector2, dragging: bool, } impl Bob { fn new(x: f32, y: f32) -> Self { Bob { position: pt2(x, y), velocity: vec2(0.0, 0.0), acceleration: vec2(0.0, 0.0), mass: 12.0, damping: 0.95, // Arbitrary damping to simulate friction / drag drag_offset: vec2(0.0, 0.0), dragging: false, } } // Standard Euler integration fn update(&mut self) { self.velocity += self.acceleration; self.velocity *= self.damping; self.position += self.velocity; self.acceleration *= 0.0; } // Newton's law: F = M * A fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn display(&self, draw: &Draw) { let c = if self.dragging { GREY } else { DARKGREY }; draw.ellipse() .xy(self.position) .w_h(self.mass * 2.0, self.mass * 2.0) .color(c) .stroke(BLACK) .stroke_weight(2.0); } // The methods below are for mouse interaction // This checks to see if we clicked on the mover fn clicked(&mut self, mx: f32, my: f32) { let d = pt2(mx, my).distance(self.position); if d < self.mass { self.dragging = true; self.drag_offset.x = self.position.x - mx; self.drag_offset.y = self.position.y - my; } } fn stop_dragging(&mut self)
fn drag(&mut self, mx: f32, my: f32) { if self.dragging { self.position.x = mx + self.drag_offset.x; self.position.y = my - self.drag_offset.y; } } } struct Model { b1: Bob, b2: Bob, b3: Bob, s1: Spring, s2: Spring, s3: Spring, } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .view(view) .mouse_pressed(mouse_pressed) .mouse_released(mouse_released) .build() .unwrap(); // Create objects at starting position // Note third argument in Spring constructor is "rest length" let win = app.window_rect(); Model { b1: Bob::new(0.0, win.top() - 100.0), b2: Bob::new(0.0, win.top() - 200.0), b3: Bob::new(0.0, win.top() - 300.0), s1: Spring::new(100.0), s2: Spring::new(100.0), s3: Spring::new(100.0), } } fn update(app: &App, m: &mut Model, _update: Update) { m.s1.update(&mut m.b1, &mut m.b2); m.s2.update(&mut m.b2, &mut m.b3); m.s3.update(&mut m.b1, &mut m.b3); m.b1.update(); m.b2.update(); m.b3.update(); m.b1.drag(app.mouse.x, app.mouse.y); } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); m.s1.display(&draw, &m.b1, &m.b2); m.s2.display(&draw, &m.b2, &m.b3); m.s3.display(&draw, &m.b1, &m.b3); m.b1.display(&draw); m.b2.display(&draw); m.b3.display(&draw); // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.b1.clicked(app.mouse.x, app.mouse.y); } fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) { m.b1.stop_dragging(); }
{ self.dragging = false; }
identifier_body
3_16_exercise_springs.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 3-16: Exercise Springs use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } // Spring Type describes an anchor point that can connect to "Bob" objects via a spring // Thank you: http://www.myphysicslab.com/spring2d.html struct Spring { // Rest length and spring constant len: f32, k: f32, } impl Spring { fn new(l: f32) -> Self { Spring { len: l, k: 0.2 } } // Calculate spring force fn update(&self, a: &mut Bob, b: &mut Bob) { // Vector pointing from anchor to bob position let mut force = a.position - b.position; // What is the distance let d = force.magnitude(); // Stretch is difference between current distance and rest length let stretch = d - self.len; // Calculate force according to Hooke's Law // F = k * stretch force = force.normalize(); force *= -1.0 * self.k * stretch; a.apply_force(force); force *= -1.0; b.apply_force(force); } fn
(&self, draw: &Draw, a: &Bob, b: &Bob) { draw.line() .start(a.position) .end(b.position) .color(BLACK) .stroke_weight(2.0); } } struct Bob { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, damping: f32, drag_offset: Vector2, dragging: bool, } impl Bob { fn new(x: f32, y: f32) -> Self { Bob { position: pt2(x, y), velocity: vec2(0.0, 0.0), acceleration: vec2(0.0, 0.0), mass: 12.0, damping: 0.95, // Arbitrary damping to simulate friction / drag drag_offset: vec2(0.0, 0.0), dragging: false, } } // Standard Euler integration fn update(&mut self) { self.velocity += self.acceleration; self.velocity *= self.damping; self.position += self.velocity; self.acceleration *= 0.0; } // Newton's law: F = M * A fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn display(&self, draw: &Draw) { let c = if self.dragging { GREY } else { DARKGREY }; draw.ellipse() .xy(self.position) .w_h(self.mass * 2.0, self.mass * 2.0) .color(c) .stroke(BLACK) .stroke_weight(2.0); } // The methods below are for mouse interaction // This checks to see if we clicked on the mover fn clicked(&mut self, mx: f32, my: f32) { let d = pt2(mx, my).distance(self.position); if d < self.mass { self.dragging = true; self.drag_offset.x = self.position.x - mx; self.drag_offset.y = self.position.y - my; } } fn stop_dragging(&mut self) { self.dragging = false; } fn drag(&mut self, mx: f32, my: f32) { if self.dragging { self.position.x = mx + self.drag_offset.x; self.position.y = my - self.drag_offset.y; } } } struct Model { b1: Bob, b2: Bob, b3: Bob, s1: Spring, s2: Spring, s3: Spring, } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .view(view) .mouse_pressed(mouse_pressed) .mouse_released(mouse_released) .build() .unwrap(); // Create objects at starting position // Note third argument in Spring constructor is "rest length" let win = app.window_rect(); Model { b1: Bob::new(0.0, win.top() - 100.0), b2: Bob::new(0.0, win.top() - 200.0), b3: Bob::new(0.0, win.top() - 300.0), s1: Spring::new(100.0), s2: Spring::new(100.0), s3: Spring::new(100.0), } } fn update(app: &App, m: &mut Model, _update: Update) { m.s1.update(&mut m.b1, &mut m.b2); m.s2.update(&mut m.b2, &mut m.b3); m.s3.update(&mut m.b1, &mut m.b3); m.b1.update(); m.b2.update(); m.b3.update(); m.b1.drag(app.mouse.x, app.mouse.y); } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); m.s1.display(&draw, &m.b1, &m.b2); m.s2.display(&draw, &m.b2, &m.b3); m.s3.display(&draw, &m.b1, &m.b3); m.b1.display(&draw); m.b2.display(&draw); m.b3.display(&draw); // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.b1.clicked(app.mouse.x, app.mouse.y); } fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) { m.b1.stop_dragging(); }
display
identifier_name
3_16_exercise_springs.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com
// Example 3-16: Exercise Springs use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } // Spring Type describes an anchor point that can connect to "Bob" objects via a spring // Thank you: http://www.myphysicslab.com/spring2d.html struct Spring { // Rest length and spring constant len: f32, k: f32, } impl Spring { fn new(l: f32) -> Self { Spring { len: l, k: 0.2 } } // Calculate spring force fn update(&self, a: &mut Bob, b: &mut Bob) { // Vector pointing from anchor to bob position let mut force = a.position - b.position; // What is the distance let d = force.magnitude(); // Stretch is difference between current distance and rest length let stretch = d - self.len; // Calculate force according to Hooke's Law // F = k * stretch force = force.normalize(); force *= -1.0 * self.k * stretch; a.apply_force(force); force *= -1.0; b.apply_force(force); } fn display(&self, draw: &Draw, a: &Bob, b: &Bob) { draw.line() .start(a.position) .end(b.position) .color(BLACK) .stroke_weight(2.0); } } struct Bob { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, damping: f32, drag_offset: Vector2, dragging: bool, } impl Bob { fn new(x: f32, y: f32) -> Self { Bob { position: pt2(x, y), velocity: vec2(0.0, 0.0), acceleration: vec2(0.0, 0.0), mass: 12.0, damping: 0.95, // Arbitrary damping to simulate friction / drag drag_offset: vec2(0.0, 0.0), dragging: false, } } // Standard Euler integration fn update(&mut self) { self.velocity += self.acceleration; self.velocity *= self.damping; self.position += self.velocity; self.acceleration *= 0.0; } // Newton's law: F = M * A fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn display(&self, draw: &Draw) { let c = if self.dragging { GREY } else { DARKGREY }; draw.ellipse() .xy(self.position) .w_h(self.mass * 2.0, self.mass * 2.0) .color(c) .stroke(BLACK) .stroke_weight(2.0); } // The methods below are for mouse interaction // This checks to see if we clicked on the mover fn clicked(&mut self, mx: f32, my: f32) { let d = pt2(mx, my).distance(self.position); if d < self.mass { self.dragging = true; self.drag_offset.x = self.position.x - mx; self.drag_offset.y = self.position.y - my; } } fn stop_dragging(&mut self) { self.dragging = false; } fn drag(&mut self, mx: f32, my: f32) { if self.dragging { self.position.x = mx + self.drag_offset.x; self.position.y = my - self.drag_offset.y; } } } struct Model { b1: Bob, b2: Bob, b3: Bob, s1: Spring, s2: Spring, s3: Spring, } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .view(view) .mouse_pressed(mouse_pressed) .mouse_released(mouse_released) .build() .unwrap(); // Create objects at starting position // Note third argument in Spring constructor is "rest length" let win = app.window_rect(); Model { b1: Bob::new(0.0, win.top() - 100.0), b2: Bob::new(0.0, win.top() - 200.0), b3: Bob::new(0.0, win.top() - 300.0), s1: Spring::new(100.0), s2: Spring::new(100.0), s3: Spring::new(100.0), } } fn update(app: &App, m: &mut Model, _update: Update) { m.s1.update(&mut m.b1, &mut m.b2); m.s2.update(&mut m.b2, &mut m.b3); m.s3.update(&mut m.b1, &mut m.b3); m.b1.update(); m.b2.update(); m.b3.update(); m.b1.drag(app.mouse.x, app.mouse.y); } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); m.s1.display(&draw, &m.b1, &m.b2); m.s2.display(&draw, &m.b2, &m.b3); m.s3.display(&draw, &m.b1, &m.b3); m.b1.display(&draw); m.b2.display(&draw); m.b3.display(&draw); // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.b1.clicked(app.mouse.x, app.mouse.y); } fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) { m.b1.stop_dragging(); }
//
random_line_split
3_16_exercise_springs.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 3-16: Exercise Springs use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } // Spring Type describes an anchor point that can connect to "Bob" objects via a spring // Thank you: http://www.myphysicslab.com/spring2d.html struct Spring { // Rest length and spring constant len: f32, k: f32, } impl Spring { fn new(l: f32) -> Self { Spring { len: l, k: 0.2 } } // Calculate spring force fn update(&self, a: &mut Bob, b: &mut Bob) { // Vector pointing from anchor to bob position let mut force = a.position - b.position; // What is the distance let d = force.magnitude(); // Stretch is difference between current distance and rest length let stretch = d - self.len; // Calculate force according to Hooke's Law // F = k * stretch force = force.normalize(); force *= -1.0 * self.k * stretch; a.apply_force(force); force *= -1.0; b.apply_force(force); } fn display(&self, draw: &Draw, a: &Bob, b: &Bob) { draw.line() .start(a.position) .end(b.position) .color(BLACK) .stroke_weight(2.0); } } struct Bob { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, damping: f32, drag_offset: Vector2, dragging: bool, } impl Bob { fn new(x: f32, y: f32) -> Self { Bob { position: pt2(x, y), velocity: vec2(0.0, 0.0), acceleration: vec2(0.0, 0.0), mass: 12.0, damping: 0.95, // Arbitrary damping to simulate friction / drag drag_offset: vec2(0.0, 0.0), dragging: false, } } // Standard Euler integration fn update(&mut self) { self.velocity += self.acceleration; self.velocity *= self.damping; self.position += self.velocity; self.acceleration *= 0.0; } // Newton's law: F = M * A fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn display(&self, draw: &Draw) { let c = if self.dragging { GREY } else { DARKGREY }; draw.ellipse() .xy(self.position) .w_h(self.mass * 2.0, self.mass * 2.0) .color(c) .stroke(BLACK) .stroke_weight(2.0); } // The methods below are for mouse interaction // This checks to see if we clicked on the mover fn clicked(&mut self, mx: f32, my: f32) { let d = pt2(mx, my).distance(self.position); if d < self.mass
} fn stop_dragging(&mut self) { self.dragging = false; } fn drag(&mut self, mx: f32, my: f32) { if self.dragging { self.position.x = mx + self.drag_offset.x; self.position.y = my - self.drag_offset.y; } } } struct Model { b1: Bob, b2: Bob, b3: Bob, s1: Spring, s2: Spring, s3: Spring, } fn model(app: &App) -> Model { app.new_window() .size(640, 360) .view(view) .mouse_pressed(mouse_pressed) .mouse_released(mouse_released) .build() .unwrap(); // Create objects at starting position // Note third argument in Spring constructor is "rest length" let win = app.window_rect(); Model { b1: Bob::new(0.0, win.top() - 100.0), b2: Bob::new(0.0, win.top() - 200.0), b3: Bob::new(0.0, win.top() - 300.0), s1: Spring::new(100.0), s2: Spring::new(100.0), s3: Spring::new(100.0), } } fn update(app: &App, m: &mut Model, _update: Update) { m.s1.update(&mut m.b1, &mut m.b2); m.s2.update(&mut m.b2, &mut m.b3); m.s3.update(&mut m.b1, &mut m.b3); m.b1.update(); m.b2.update(); m.b3.update(); m.b1.drag(app.mouse.x, app.mouse.y); } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); m.s1.display(&draw, &m.b1, &m.b2); m.s2.display(&draw, &m.b2, &m.b3); m.s3.display(&draw, &m.b1, &m.b3); m.b1.display(&draw); m.b2.display(&draw); m.b3.display(&draw); // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) { m.b1.clicked(app.mouse.x, app.mouse.y); } fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) { m.b1.stop_dragging(); }
{ self.dragging = true; self.drag_offset.x = self.position.x - mx; self.drag_offset.y = self.position.y - my; }
conditional_block
auth.rs
use std::os; pub enum Credentials { BasicCredentials(String, String) } impl<'r> Credentials { pub fn aws_access_key_id(&'r self) -> &'r str { match *self { BasicCredentials(ref key, _) => key.as_slice() } } pub fn aws_secret_access_key(&'r self) -> &'r str { match *self { BasicCredentials(_, ref secret) => secret.as_slice() } } } pub trait CredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String>; } pub struct DefaultCredentialsProvider; impl CredentialsProvider for DefaultCredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String>
}
{ match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) { (Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)), _ => Err("Could not find AWS credentials".to_string()) } }
identifier_body
auth.rs
use std::os;
impl<'r> Credentials { pub fn aws_access_key_id(&'r self) -> &'r str { match *self { BasicCredentials(ref key, _) => key.as_slice() } } pub fn aws_secret_access_key(&'r self) -> &'r str { match *self { BasicCredentials(_, ref secret) => secret.as_slice() } } } pub trait CredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String>; } pub struct DefaultCredentialsProvider; impl CredentialsProvider for DefaultCredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String> { match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) { (Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)), _ => Err("Could not find AWS credentials".to_string()) } } }
pub enum Credentials { BasicCredentials(String, String) }
random_line_split
auth.rs
use std::os; pub enum Credentials { BasicCredentials(String, String) } impl<'r> Credentials { pub fn aws_access_key_id(&'r self) -> &'r str { match *self { BasicCredentials(ref key, _) => key.as_slice() } } pub fn
(&'r self) -> &'r str { match *self { BasicCredentials(_, ref secret) => secret.as_slice() } } } pub trait CredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String>; } pub struct DefaultCredentialsProvider; impl CredentialsProvider for DefaultCredentialsProvider { fn get_credentials(&mut self) -> Result<Credentials,String> { match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) { (Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)), _ => Err("Could not find AWS credentials".to_string()) } } }
aws_secret_access_key
identifier_name
checkerboard.rs
use crate::noise_fns::NoiseFn; /// Noise function that outputs a checkerboard pattern. /// /// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized /// blocks of alternating values. The values of these blocks alternate between /// -1.0 and 1.0. /// /// This noise function is not very useful by itself, but it can be used for /// debugging purposes. #[derive(Clone, Copy, Debug)] pub struct Checkerboard { /// Controls the size of the block in 2^(size). size: usize, } impl Checkerboard { const DEFAULT_SIZE: usize = 0; pub fn new(size: usize) -> Self { Self { size: 1 << size } } pub fn set_size(self, size: usize) -> Self { Self { size: 1 << size } } pub fn size(self) -> usize { self.size } } impl Default for Checkerboard { fn
() -> Self { Self { size: 1 << Checkerboard::DEFAULT_SIZE, } } } // These impl's should be made generic over Point, but there is no higher Point // type. Keep the code the same anyway. impl NoiseFn<[f64; 2]> for Checkerboard { fn get(&self, point: [f64; 2]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 3]> for Checkerboard { fn get(&self, point: [f64; 3]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 4]> for Checkerboard { fn get(&self, point: [f64; 4]) -> f64 { calculate_checkerboard(&point, self.size) } } fn calculate_checkerboard(point: &[f64], size: usize) -> f64 { let result = point .iter() .map(|&a| a.floor() as usize) .fold(0, |a, b| (a & size) ^ (b & size)); if result > 0 { -1.0 } else { 1.0 } }
default
identifier_name
checkerboard.rs
use crate::noise_fns::NoiseFn; /// Noise function that outputs a checkerboard pattern. /// /// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized /// blocks of alternating values. The values of these blocks alternate between /// -1.0 and 1.0. /// /// This noise function is not very useful by itself, but it can be used for /// debugging purposes. #[derive(Clone, Copy, Debug)] pub struct Checkerboard { /// Controls the size of the block in 2^(size). size: usize, } impl Checkerboard { const DEFAULT_SIZE: usize = 0; pub fn new(size: usize) -> Self { Self { size: 1 << size } } pub fn set_size(self, size: usize) -> Self { Self { size: 1 << size } } pub fn size(self) -> usize { self.size } } impl Default for Checkerboard { fn default() -> Self { Self { size: 1 << Checkerboard::DEFAULT_SIZE, } } } // These impl's should be made generic over Point, but there is no higher Point // type. Keep the code the same anyway. impl NoiseFn<[f64; 2]> for Checkerboard { fn get(&self, point: [f64; 2]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 3]> for Checkerboard { fn get(&self, point: [f64; 3]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 4]> for Checkerboard { fn get(&self, point: [f64; 4]) -> f64 { calculate_checkerboard(&point, self.size) } } fn calculate_checkerboard(point: &[f64], size: usize) -> f64 { let result = point .iter() .map(|&a| a.floor() as usize) .fold(0, |a, b| (a & size) ^ (b & size)); if result > 0 { -1.0 } else
}
{ 1.0 }
conditional_block
checkerboard.rs
use crate::noise_fns::NoiseFn; /// Noise function that outputs a checkerboard pattern. /// /// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized /// blocks of alternating values. The values of these blocks alternate between /// -1.0 and 1.0. /// /// This noise function is not very useful by itself, but it can be used for /// debugging purposes. #[derive(Clone, Copy, Debug)] pub struct Checkerboard { /// Controls the size of the block in 2^(size). size: usize, } impl Checkerboard { const DEFAULT_SIZE: usize = 0; pub fn new(size: usize) -> Self { Self { size: 1 << size } } pub fn set_size(self, size: usize) -> Self { Self { size: 1 << size } } pub fn size(self) -> usize { self.size } } impl Default for Checkerboard {
} } } // These impl's should be made generic over Point, but there is no higher Point // type. Keep the code the same anyway. impl NoiseFn<[f64; 2]> for Checkerboard { fn get(&self, point: [f64; 2]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 3]> for Checkerboard { fn get(&self, point: [f64; 3]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 4]> for Checkerboard { fn get(&self, point: [f64; 4]) -> f64 { calculate_checkerboard(&point, self.size) } } fn calculate_checkerboard(point: &[f64], size: usize) -> f64 { let result = point .iter() .map(|&a| a.floor() as usize) .fold(0, |a, b| (a & size) ^ (b & size)); if result > 0 { -1.0 } else { 1.0 } }
fn default() -> Self { Self { size: 1 << Checkerboard::DEFAULT_SIZE,
random_line_split
checkerboard.rs
use crate::noise_fns::NoiseFn; /// Noise function that outputs a checkerboard pattern. /// /// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized /// blocks of alternating values. The values of these blocks alternate between /// -1.0 and 1.0. /// /// This noise function is not very useful by itself, but it can be used for /// debugging purposes. #[derive(Clone, Copy, Debug)] pub struct Checkerboard { /// Controls the size of the block in 2^(size). size: usize, } impl Checkerboard { const DEFAULT_SIZE: usize = 0; pub fn new(size: usize) -> Self { Self { size: 1 << size } } pub fn set_size(self, size: usize) -> Self { Self { size: 1 << size } } pub fn size(self) -> usize { self.size } } impl Default for Checkerboard { fn default() -> Self { Self { size: 1 << Checkerboard::DEFAULT_SIZE, } } } // These impl's should be made generic over Point, but there is no higher Point // type. Keep the code the same anyway. impl NoiseFn<[f64; 2]> for Checkerboard { fn get(&self, point: [f64; 2]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 3]> for Checkerboard { fn get(&self, point: [f64; 3]) -> f64 { calculate_checkerboard(&point, self.size) } } impl NoiseFn<[f64; 4]> for Checkerboard { fn get(&self, point: [f64; 4]) -> f64 { calculate_checkerboard(&point, self.size) } } fn calculate_checkerboard(point: &[f64], size: usize) -> f64
{ let result = point .iter() .map(|&a| a.floor() as usize) .fold(0, |a, b| (a & size) ^ (b & size)); if result > 0 { -1.0 } else { 1.0 } }
identifier_body
expr-match-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests for match as expressions resulting in struct types struct R { i: int } fn test_rec() { let rs = match true { true => R {i: 100}, _ => panic!() }; assert_eq!(rs.i, 100); } #[deriving(Show)] enum mood { happy, sad, } impl PartialEq for mood { fn
(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag() { let rs = match true { true => { mood::happy } false => { mood::sad } }; assert_eq!(rs, mood::happy); } pub fn main() { test_rec(); test_tag(); }
eq
identifier_name
expr-match-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests for match as expressions resulting in struct types struct R { i: int } fn test_rec() { let rs = match true { true => R {i: 100}, _ => panic!() }; assert_eq!(rs.i, 100); } #[deriving(Show)] enum mood { happy, sad, } impl PartialEq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag()
pub fn main() { test_rec(); test_tag(); }
{ let rs = match true { true => { mood::happy } false => { mood::sad } }; assert_eq!(rs, mood::happy); }
identifier_body
expr-match-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests for match as expressions resulting in struct types struct R { i: int } fn test_rec() { let rs = match true { true => R {i: 100}, _ => panic!() };
#[deriving(Show)] enum mood { happy, sad, } impl PartialEq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool {!(*self).eq(other) } } fn test_tag() { let rs = match true { true => { mood::happy } false => { mood::sad } }; assert_eq!(rs, mood::happy); } pub fn main() { test_rec(); test_tag(); }
assert_eq!(rs.i, 100); }
random_line_split
threads.rs
//! Threading code. use std::mem; use remacs_macros::lisp_fn; use remacs_sys::{current_thread, thread_state}; use buffers::LispBufferRef; use lisp::{ExternalPtr, LispObject}; use lisp::defsubr; pub type ThreadStateRef = ExternalPtr<thread_state>; pub struct ThreadState {} impl ThreadState { pub fn current_buffer() -> LispBufferRef { unsafe { mem::transmute((*current_thread).m_current_buffer) } } } impl ThreadStateRef { #[inline] pub fn name(self) -> LispObject { LispObject::from_raw(self.name) } #[inline] pub fn is_alive(self) -> bool { !self.m_specpdl.is_null() } } /// Return the name of the THREAD. /// The name is the same object that was passed to `make-thread'. #[lisp_fn] pub fn thread_name(thread: ThreadStateRef) -> LispObject
/// Return t if THREAD is alive, or nil if it has exited. #[lisp_fn] pub fn thread_alive_p(thread: ThreadStateRef) -> bool { thread.is_alive() } include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
{ thread.name() }
identifier_body
threads.rs
//! Threading code. use std::mem; use remacs_macros::lisp_fn; use remacs_sys::{current_thread, thread_state}; use buffers::LispBufferRef; use lisp::{ExternalPtr, LispObject}; use lisp::defsubr; pub type ThreadStateRef = ExternalPtr<thread_state>; pub struct ThreadState {} impl ThreadState { pub fn current_buffer() -> LispBufferRef { unsafe { mem::transmute((*current_thread).m_current_buffer) } } } impl ThreadStateRef { #[inline] pub fn name(self) -> LispObject { LispObject::from_raw(self.name) } #[inline] pub fn is_alive(self) -> bool { !self.m_specpdl.is_null() } } /// Return the name of the THREAD. /// The name is the same object that was passed to `make-thread'. #[lisp_fn] pub fn thread_name(thread: ThreadStateRef) -> LispObject { thread.name() } /// Return t if THREAD is alive, or nil if it has exited. #[lisp_fn] pub fn
(thread: ThreadStateRef) -> bool { thread.is_alive() } include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
thread_alive_p
identifier_name
threads.rs
//! Threading code. use std::mem; use remacs_macros::lisp_fn; use remacs_sys::{current_thread, thread_state}; use buffers::LispBufferRef; use lisp::{ExternalPtr, LispObject}; use lisp::defsubr; pub type ThreadStateRef = ExternalPtr<thread_state>; pub struct ThreadState {} impl ThreadState { pub fn current_buffer() -> LispBufferRef { unsafe { mem::transmute((*current_thread).m_current_buffer) } } } impl ThreadStateRef { #[inline] pub fn name(self) -> LispObject { LispObject::from_raw(self.name) } #[inline] pub fn is_alive(self) -> bool { !self.m_specpdl.is_null() }
#[lisp_fn] pub fn thread_name(thread: ThreadStateRef) -> LispObject { thread.name() } /// Return t if THREAD is alive, or nil if it has exited. #[lisp_fn] pub fn thread_alive_p(thread: ThreadStateRef) -> bool { thread.is_alive() } include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
} /// Return the name of the THREAD. /// The name is the same object that was passed to `make-thread'.
random_line_split
bad-lit-suffixes.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only extern "C"suffix //~ ERROR ABI spec with a suffix is invalid fn
() {} extern "C"suffix //~ ERROR ABI spec with a suffix is invalid {} fn main() { ""suffix; //~ ERROR str literal with a suffix is invalid b""suffix; //~ ERROR binary str literal with a suffix is invalid r#""#suffix; //~ ERROR str literal with a suffix is invalid br#""#suffix; //~ ERROR binary str literal with a suffix is invalid 'a'suffix; //~ ERROR char literal with a suffix is invalid b'a'suffix; //~ ERROR byte literal with a suffix is invalid 1234u1024; //~ ERROR invalid width `1024` for integer literal 1234i1024; //~ ERROR invalid width `1024` for integer literal 1234f1024; //~ ERROR invalid width `1024` for float literal 1234.5f1024; //~ ERROR invalid width `1024` for float literal 1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal 0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal 1.0suffix; //~ ERROR invalid suffix `suffix` for float literal 1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal }
foo
identifier_name
bad-lit-suffixes.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only extern "C"suffix //~ ERROR ABI spec with a suffix is invalid fn foo() {} extern "C"suffix //~ ERROR ABI spec with a suffix is invalid {} fn main() { ""suffix; //~ ERROR str literal with a suffix is invalid b""suffix; //~ ERROR binary str literal with a suffix is invalid r#""#suffix; //~ ERROR str literal with a suffix is invalid br#""#suffix; //~ ERROR binary str literal with a suffix is invalid 'a'suffix; //~ ERROR char literal with a suffix is invalid b'a'suffix; //~ ERROR byte literal with a suffix is invalid
1234i1024; //~ ERROR invalid width `1024` for integer literal 1234f1024; //~ ERROR invalid width `1024` for float literal 1234.5f1024; //~ ERROR invalid width `1024` for float literal 1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal 0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal 1.0suffix; //~ ERROR invalid suffix `suffix` for float literal 1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal }
1234u1024; //~ ERROR invalid width `1024` for integer literal
random_line_split
bad-lit-suffixes.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -Z parse-only extern "C"suffix //~ ERROR ABI spec with a suffix is invalid fn foo()
extern "C"suffix //~ ERROR ABI spec with a suffix is invalid {} fn main() { ""suffix; //~ ERROR str literal with a suffix is invalid b""suffix; //~ ERROR binary str literal with a suffix is invalid r#""#suffix; //~ ERROR str literal with a suffix is invalid br#""#suffix; //~ ERROR binary str literal with a suffix is invalid 'a'suffix; //~ ERROR char literal with a suffix is invalid b'a'suffix; //~ ERROR byte literal with a suffix is invalid 1234u1024; //~ ERROR invalid width `1024` for integer literal 1234i1024; //~ ERROR invalid width `1024` for integer literal 1234f1024; //~ ERROR invalid width `1024` for float literal 1234.5f1024; //~ ERROR invalid width `1024` for float literal 1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal 0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal 1.0suffix; //~ ERROR invalid suffix `suffix` for float literal 1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal }
{}
identifier_body
generic-fn.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // -*- rust -*- fn id<T:Copy>(x: T) -> T { return x; } struct Triple {x: int, y: int, z: int}
pub fn main() { let mut x = 62; let mut y = 63; let a = 'a'; let mut b = 'b'; let p: Triple = Triple {x: 65, y: 66, z: 67}; let mut q: Triple = Triple {x: 68, y: 69, z: 70}; y = id::<int>(x); debug!(y); assert!((x == y)); b = id::<char>(a); debug!(b); assert!((a == b)); q = id::<Triple>(p); x = p.z; y = q.z; debug!(y); assert!((x == y)); }
random_line_split
generic-fn.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // -*- rust -*- fn id<T:Copy>(x: T) -> T { return x; } struct Triple {x: int, y: int, z: int} pub fn main()
{ let mut x = 62; let mut y = 63; let a = 'a'; let mut b = 'b'; let p: Triple = Triple {x: 65, y: 66, z: 67}; let mut q: Triple = Triple {x: 68, y: 69, z: 70}; y = id::<int>(x); debug!(y); assert!((x == y)); b = id::<char>(a); debug!(b); assert!((a == b)); q = id::<Triple>(p); x = p.z; y = q.z; debug!(y); assert!((x == y)); }
identifier_body
generic-fn.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // -*- rust -*- fn id<T:Copy>(x: T) -> T { return x; } struct Triple {x: int, y: int, z: int} pub fn
() { let mut x = 62; let mut y = 63; let a = 'a'; let mut b = 'b'; let p: Triple = Triple {x: 65, y: 66, z: 67}; let mut q: Triple = Triple {x: 68, y: 69, z: 70}; y = id::<int>(x); debug!(y); assert!((x == y)); b = id::<char>(a); debug!(b); assert!((a == b)); q = id::<Triple>(p); x = p.z; y = q.z; debug!(y); assert!((x == y)); }
main
identifier_name
physics.rs
//inherited mutability: player is mutable if let is mutable //todo: Test in ticks // Implement player acceleration based on ticks between inputs. // Potentially ticks holding a button and ticks not // Rotation accel/vel use game; use std::cmp::{max, min}; pub use self::collision::collide; #[deriving(Eq)] pub enum Direction { Forward, Backward, Still } #[deriving(Eq)] pub enum Rotation { Left, Right, Norot }
p.rotation += PI / 20.0; } if p.rot == Right{ p.rotation -= PI / 20.0; } } pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod); if p.velocity >= -0.15 && p.velocity <= 0.15 { p.velocity += p.accel * 0.0001; } if p.velocity < -0.008 { p.velocity = -0.008; } if p.velocity >= 0.008 { p.velocity = 0.008 } p.positionx += p.rotation.cos() * p.velocity; p.positiony += p.rotation.sin() * p.velocity; p.accel = acc; p.accel_mod = amod; } pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) { //this will use accel/accel_mod to compute the rate of increase of acceleration. if dir == Forward { let bounds = [ (-85, -75, 25), (-75, -60, 22), (-60, -41, 19), (-40, -15, 17), (0, 15, 12), (14, 40, 10), (40, 60, 8), (60, 75, 5), (75, 85, 2) ]; accel_mod = max(accel_mod, -84); if accel_mod == 0 { accel_mod = 15; } else if accel_mod >= -15 && accel_mod < 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } else if dir == Backward { let bounds = [ (-85, -75, -10), (-75, -60, -5), (-60, -41, -8), (-40, -15, -10), (-15, 0, -12), (15, 40, -17), (40, 60, -19), (60, 75, -22), (75, 85, -25) ]; accel_mod = min(accel_mod, 84); if accel_mod == 0 { accel_mod = -15; } else if accel_mod <= 15 && accel_mod > 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } let max = 0.04; if accel >= -max && accel <= max { accel += 0.08 * (accel_mod as f32); } else { accel = accel.signum() * max; } (accel, accel_mod) //returns accel and accel mod } mod collision { use cgmath::angle::Rad; use cgmath::vector::{Vector, Vector2}; use cgmath::matrix::{Matrix, Matrix2}; use gl::types::GLfloat; use render::Sprite; use std::f32::consts::PI; type V = Vector2<GLfloat>; fn min(a: GLfloat, b: GLfloat) -> GLfloat { a.min(b) } fn max(a: GLfloat, b: GLfloat) -> GLfloat { a.max(b) } fn slope(a: V, b: V) -> GLfloat { (a.y - b.y) / (a.x - b.x) } fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 { let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2)); ((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2) } fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> { debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2); let x = line_intercept((a1, a2), (b1, b2)); debug!("The lines, were they infinite, intersect at x = {}", x); let y = slope(a1, a2)*(x - a1.x) + a1.y; debug!("The corresponding y is {}", y); if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) { debug!("It's within the first line's x values"); if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) { debug!("It's within the second line's x values"); if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) { debug!("It's within the first line's y values"); if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) { debug!("It's within the second line's y values"); return Some(Vector2::new(x, y)); } } } } None } #[test] fn test_intersect() { let a = Vector2::new(1f32, 1f32); let b = Vector2::new(-1f32, -1f32); let c = Vector2::new(-1f32, 1f32); let d = Vector2::new(1f32, -1f32); assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32))); } /// Determines if two Sprites collide, assuming that they collide iff their /// (possibly rotated) bounding boxes collide, not using the texture in any /// way. pub fn collide(a: &Sprite, b: &Sprite) -> bool { // make lists of points making up each sprite, transformed with the // rotation let mut arot = a.rot; let mut brot = b.rot; // make sure their slopes aren't NaN :( if arot % (PI / 4.0) == 0.0 { arot += 0.01; } if brot % (PI / 4.0) == 0.0 { brot += 0.01; } let amat = Matrix2::from_angle(Rad { s: arot }); let bmat = Matrix2::from_angle(Rad { s: brot }); let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about? let &Sprite {x, y, width, height,.. } = a; let apoints = [ amat.mul_v(&Vector2::new(x, y)), amat.mul_v(&Vector2::new(x + width, y)), amat.mul_v(&Vector2::new(x + width, y + height)), amat.mul_v(&Vector2::new(x, y + height)) ]; let &Sprite {x, y, width, height,.. } = b; let bpoints = [ bmat.mul_v(&Vector2::new(x, y)), bmat.mul_v(&Vector2::new(x + width, y)), bmat.mul_v(&Vector2::new(x + width, y + height)), bmat.mul_v(&Vector2::new(x, y + height)) ]; for &(a1, a2) in pairs.iter() { for &(b1, b2) in pairs.iter() { if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2]))!= None { return true; } } } false } #[test] fn test_collide() { use std; let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } } }
pub fn rotate(p: &mut game::Player){ use std::f32::consts::PI; if p.rot == Left{
random_line_split
physics.rs
//inherited mutability: player is mutable if let is mutable //todo: Test in ticks // Implement player acceleration based on ticks between inputs. // Potentially ticks holding a button and ticks not // Rotation accel/vel use game; use std::cmp::{max, min}; pub use self::collision::collide; #[deriving(Eq)] pub enum Direction { Forward, Backward, Still } #[deriving(Eq)] pub enum Rotation { Left, Right, Norot } pub fn rotate(p: &mut game::Player){ use std::f32::consts::PI; if p.rot == Left{ p.rotation += PI / 20.0; } if p.rot == Right{ p.rotation -= PI / 20.0; } } pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod); if p.velocity >= -0.15 && p.velocity <= 0.15 { p.velocity += p.accel * 0.0001; } if p.velocity < -0.008 { p.velocity = -0.008; } if p.velocity >= 0.008 { p.velocity = 0.008 } p.positionx += p.rotation.cos() * p.velocity; p.positiony += p.rotation.sin() * p.velocity; p.accel = acc; p.accel_mod = amod; } pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) { //this will use accel/accel_mod to compute the rate of increase of acceleration. if dir == Forward { let bounds = [ (-85, -75, 25), (-75, -60, 22), (-60, -41, 19), (-40, -15, 17), (0, 15, 12), (14, 40, 10), (40, 60, 8), (60, 75, 5), (75, 85, 2) ]; accel_mod = max(accel_mod, -84); if accel_mod == 0 { accel_mod = 15; } else if accel_mod >= -15 && accel_mod < 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } else if dir == Backward { let bounds = [ (-85, -75, -10), (-75, -60, -5), (-60, -41, -8), (-40, -15, -10), (-15, 0, -12), (15, 40, -17), (40, 60, -19), (60, 75, -22), (75, 85, -25) ]; accel_mod = min(accel_mod, 84); if accel_mod == 0 { accel_mod = -15; } else if accel_mod <= 15 && accel_mod > 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } let max = 0.04; if accel >= -max && accel <= max { accel += 0.08 * (accel_mod as f32); } else { accel = accel.signum() * max; } (accel, accel_mod) //returns accel and accel mod } mod collision { use cgmath::angle::Rad; use cgmath::vector::{Vector, Vector2}; use cgmath::matrix::{Matrix, Matrix2}; use gl::types::GLfloat; use render::Sprite; use std::f32::consts::PI; type V = Vector2<GLfloat>; fn min(a: GLfloat, b: GLfloat) -> GLfloat { a.min(b) } fn max(a: GLfloat, b: GLfloat) -> GLfloat { a.max(b) } fn slope(a: V, b: V) -> GLfloat { (a.y - b.y) / (a.x - b.x) } fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 { let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2)); ((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2) } fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> { debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2); let x = line_intercept((a1, a2), (b1, b2)); debug!("The lines, were they infinite, intersect at x = {}", x); let y = slope(a1, a2)*(x - a1.x) + a1.y; debug!("The corresponding y is {}", y); if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) { debug!("It's within the first line's x values"); if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) { debug!("It's within the second line's x values"); if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) { debug!("It's within the first line's y values"); if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) { debug!("It's within the second line's y values"); return Some(Vector2::new(x, y)); } } } } None } #[test] fn
() { let a = Vector2::new(1f32, 1f32); let b = Vector2::new(-1f32, -1f32); let c = Vector2::new(-1f32, 1f32); let d = Vector2::new(1f32, -1f32); assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32))); } /// Determines if two Sprites collide, assuming that they collide iff their /// (possibly rotated) bounding boxes collide, not using the texture in any /// way. pub fn collide(a: &Sprite, b: &Sprite) -> bool { // make lists of points making up each sprite, transformed with the // rotation let mut arot = a.rot; let mut brot = b.rot; // make sure their slopes aren't NaN :( if arot % (PI / 4.0) == 0.0 { arot += 0.01; } if brot % (PI / 4.0) == 0.0 { brot += 0.01; } let amat = Matrix2::from_angle(Rad { s: arot }); let bmat = Matrix2::from_angle(Rad { s: brot }); let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about? let &Sprite {x, y, width, height,.. } = a; let apoints = [ amat.mul_v(&Vector2::new(x, y)), amat.mul_v(&Vector2::new(x + width, y)), amat.mul_v(&Vector2::new(x + width, y + height)), amat.mul_v(&Vector2::new(x, y + height)) ]; let &Sprite {x, y, width, height,.. } = b; let bpoints = [ bmat.mul_v(&Vector2::new(x, y)), bmat.mul_v(&Vector2::new(x + width, y)), bmat.mul_v(&Vector2::new(x + width, y + height)), bmat.mul_v(&Vector2::new(x, y + height)) ]; for &(a1, a2) in pairs.iter() { for &(b1, b2) in pairs.iter() { if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2]))!= None { return true; } } } false } #[test] fn test_collide() { use std; let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } } }
test_intersect
identifier_name
physics.rs
//inherited mutability: player is mutable if let is mutable //todo: Test in ticks // Implement player acceleration based on ticks between inputs. // Potentially ticks holding a button and ticks not // Rotation accel/vel use game; use std::cmp::{max, min}; pub use self::collision::collide; #[deriving(Eq)] pub enum Direction { Forward, Backward, Still } #[deriving(Eq)] pub enum Rotation { Left, Right, Norot } pub fn rotate(p: &mut game::Player){ use std::f32::consts::PI; if p.rot == Left{ p.rotation += PI / 20.0; } if p.rot == Right{ p.rotation -= PI / 20.0; } } pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod); if p.velocity >= -0.15 && p.velocity <= 0.15 { p.velocity += p.accel * 0.0001; } if p.velocity < -0.008 { p.velocity = -0.008; } if p.velocity >= 0.008 { p.velocity = 0.008 } p.positionx += p.rotation.cos() * p.velocity; p.positiony += p.rotation.sin() * p.velocity; p.accel = acc; p.accel_mod = amod; } pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) { //this will use accel/accel_mod to compute the rate of increase of acceleration. if dir == Forward { let bounds = [ (-85, -75, 25), (-75, -60, 22), (-60, -41, 19), (-40, -15, 17), (0, 15, 12), (14, 40, 10), (40, 60, 8), (60, 75, 5), (75, 85, 2) ]; accel_mod = max(accel_mod, -84); if accel_mod == 0 { accel_mod = 15; } else if accel_mod >= -15 && accel_mod < 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } else if dir == Backward { let bounds = [ (-85, -75, -10), (-75, -60, -5), (-60, -41, -8), (-40, -15, -10), (-15, 0, -12), (15, 40, -17), (40, 60, -19), (60, 75, -22), (75, 85, -25) ]; accel_mod = min(accel_mod, 84); if accel_mod == 0 { accel_mod = -15; } else if accel_mod <= 15 && accel_mod > 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } let max = 0.04; if accel >= -max && accel <= max { accel += 0.08 * (accel_mod as f32); } else { accel = accel.signum() * max; } (accel, accel_mod) //returns accel and accel mod } mod collision { use cgmath::angle::Rad; use cgmath::vector::{Vector, Vector2}; use cgmath::matrix::{Matrix, Matrix2}; use gl::types::GLfloat; use render::Sprite; use std::f32::consts::PI; type V = Vector2<GLfloat>; fn min(a: GLfloat, b: GLfloat) -> GLfloat { a.min(b) } fn max(a: GLfloat, b: GLfloat) -> GLfloat { a.max(b) } fn slope(a: V, b: V) -> GLfloat { (a.y - b.y) / (a.x - b.x) } fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 { let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2)); ((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2) } fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> { debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2); let x = line_intercept((a1, a2), (b1, b2)); debug!("The lines, were they infinite, intersect at x = {}", x); let y = slope(a1, a2)*(x - a1.x) + a1.y; debug!("The corresponding y is {}", y); if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) { debug!("It's within the first line's x values"); if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) { debug!("It's within the second line's x values"); if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) { debug!("It's within the first line's y values"); if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) { debug!("It's within the second line's y values"); return Some(Vector2::new(x, y)); } } } } None } #[test] fn test_intersect() { let a = Vector2::new(1f32, 1f32); let b = Vector2::new(-1f32, -1f32); let c = Vector2::new(-1f32, 1f32); let d = Vector2::new(1f32, -1f32); assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32))); } /// Determines if two Sprites collide, assuming that they collide iff their /// (possibly rotated) bounding boxes collide, not using the texture in any /// way. pub fn collide(a: &Sprite, b: &Sprite) -> bool
let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about? let &Sprite {x, y, width, height,.. } = a; let apoints = [ amat.mul_v(&Vector2::new(x, y)), amat.mul_v(&Vector2::new(x + width, y)), amat.mul_v(&Vector2::new(x + width, y + height)), amat.mul_v(&Vector2::new(x, y + height)) ]; let &Sprite {x, y, width, height,.. } = b; let bpoints = [ bmat.mul_v(&Vector2::new(x, y)), bmat.mul_v(&Vector2::new(x + width, y)), bmat.mul_v(&Vector2::new(x + width, y + height)), bmat.mul_v(&Vector2::new(x, y + height)) ]; for &(a1, a2) in pairs.iter() { for &(b1, b2) in pairs.iter() { if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2]))!= None { return true; } } } false } #[test] fn test_collide() { use std; let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } } }
{ // make lists of points making up each sprite, transformed with the // rotation let mut arot = a.rot; let mut brot = b.rot; // make sure their slopes aren't NaN :( if arot % (PI / 4.0) == 0.0 { arot += 0.01; } if brot % (PI / 4.0) == 0.0 { brot += 0.01; } let amat = Matrix2::from_angle(Rad { s: arot }); let bmat = Matrix2::from_angle(Rad { s: brot });
identifier_body
physics.rs
//inherited mutability: player is mutable if let is mutable //todo: Test in ticks // Implement player acceleration based on ticks between inputs. // Potentially ticks holding a button and ticks not // Rotation accel/vel use game; use std::cmp::{max, min}; pub use self::collision::collide; #[deriving(Eq)] pub enum Direction { Forward, Backward, Still } #[deriving(Eq)] pub enum Rotation { Left, Right, Norot } pub fn rotate(p: &mut game::Player){ use std::f32::consts::PI; if p.rot == Left{ p.rotation += PI / 20.0; } if p.rot == Right{ p.rotation -= PI / 20.0; } } pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod); if p.velocity >= -0.15 && p.velocity <= 0.15 { p.velocity += p.accel * 0.0001; } if p.velocity < -0.008 { p.velocity = -0.008; } if p.velocity >= 0.008 { p.velocity = 0.008 } p.positionx += p.rotation.cos() * p.velocity; p.positiony += p.rotation.sin() * p.velocity; p.accel = acc; p.accel_mod = amod; } pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) { //this will use accel/accel_mod to compute the rate of increase of acceleration. if dir == Forward { let bounds = [ (-85, -75, 25), (-75, -60, 22), (-60, -41, 19), (-40, -15, 17), (0, 15, 12), (14, 40, 10), (40, 60, 8), (60, 75, 5), (75, 85, 2) ]; accel_mod = max(accel_mod, -84); if accel_mod == 0 { accel_mod = 15; } else if accel_mod >= -15 && accel_mod < 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } else if dir == Backward { let bounds = [ (-85, -75, -10), (-75, -60, -5), (-60, -41, -8), (-40, -15, -10), (-15, 0, -12), (15, 40, -17), (40, 60, -19), (60, 75, -22), (75, 85, -25) ]; accel_mod = min(accel_mod, 84); if accel_mod == 0 { accel_mod = -15; } else if accel_mod <= 15 && accel_mod > 0 { accel_mod = 0; } else { for &(lower, upper, increment) in bounds.iter() { if accel_mod >= lower && accel_mod <= upper { accel_mod += increment; break } } } } let max = 0.04; if accel >= -max && accel <= max { accel += 0.08 * (accel_mod as f32); } else { accel = accel.signum() * max; } (accel, accel_mod) //returns accel and accel mod } mod collision { use cgmath::angle::Rad; use cgmath::vector::{Vector, Vector2}; use cgmath::matrix::{Matrix, Matrix2}; use gl::types::GLfloat; use render::Sprite; use std::f32::consts::PI; type V = Vector2<GLfloat>; fn min(a: GLfloat, b: GLfloat) -> GLfloat { a.min(b) } fn max(a: GLfloat, b: GLfloat) -> GLfloat { a.max(b) } fn slope(a: V, b: V) -> GLfloat { (a.y - b.y) / (a.x - b.x) } fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 { let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2)); ((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2) } fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> { debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2); let x = line_intercept((a1, a2), (b1, b2)); debug!("The lines, were they infinite, intersect at x = {}", x); let y = slope(a1, a2)*(x - a1.x) + a1.y; debug!("The corresponding y is {}", y); if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) { debug!("It's within the first line's x values"); if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) { debug!("It's within the second line's x values"); if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y)
} } None } #[test] fn test_intersect() { let a = Vector2::new(1f32, 1f32); let b = Vector2::new(-1f32, -1f32); let c = Vector2::new(-1f32, 1f32); let d = Vector2::new(1f32, -1f32); assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32))); } /// Determines if two Sprites collide, assuming that they collide iff their /// (possibly rotated) bounding boxes collide, not using the texture in any /// way. pub fn collide(a: &Sprite, b: &Sprite) -> bool { // make lists of points making up each sprite, transformed with the // rotation let mut arot = a.rot; let mut brot = b.rot; // make sure their slopes aren't NaN :( if arot % (PI / 4.0) == 0.0 { arot += 0.01; } if brot % (PI / 4.0) == 0.0 { brot += 0.01; } let amat = Matrix2::from_angle(Rad { s: arot }); let bmat = Matrix2::from_angle(Rad { s: brot }); let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about? let &Sprite {x, y, width, height,.. } = a; let apoints = [ amat.mul_v(&Vector2::new(x, y)), amat.mul_v(&Vector2::new(x + width, y)), amat.mul_v(&Vector2::new(x + width, y + height)), amat.mul_v(&Vector2::new(x, y + height)) ]; let &Sprite {x, y, width, height,.. } = b; let bpoints = [ bmat.mul_v(&Vector2::new(x, y)), bmat.mul_v(&Vector2::new(x + width, y)), bmat.mul_v(&Vector2::new(x + width, y + height)), bmat.mul_v(&Vector2::new(x, y + height)) ]; for &(a1, a2) in pairs.iter() { for &(b1, b2) in pairs.iter() { if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2]))!= None { return true; } } } false } #[test] fn test_collide() { use std; let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() }); let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() }); assert_eq!(collide(&s1, &s2), true); unsafe { // since we're stubbing out the texture std::cast::forget(s1); std::cast::forget(s2); } } }
{ debug!("It's within the first line's y values"); if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) { debug!("It's within the second line's y values"); return Some(Vector2::new(x, y)); } }
conditional_block
cmp.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The `Ord` and `Eq` comparison traits This module contains the definition of both `Ord` and `Eq` which define the common interfaces for doing comparison. Both are language items that the compiler uses to implement the comparison operators. Rust code may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators, and `Eq` to overload the `==` and `!=` operators. */ #[allow(missing_doc)]; /** * Trait for values that can be compared for equality and inequality. * * This trait allows partial equality, where types can be unordered instead of strictly equal or * unequal. For example, with the built-in floating-point types `a == b` and `a!= b` will both * evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11). * * Eq only requires the `eq` method to be implemented; `ne` is its negation by default. * * Eventually, this will be implemented by default for types that implement `TotalEq`. */ #[lang="eq"] pub trait Eq { fn eq(&self, other: &Self) -> bool; #[inline] fn ne(&self, other: &Self) -> bool {!self.eq(other) } } /// Trait for equality comparisons where `a == b` and `a!= b` are strict inverses. pub trait TotalEq { fn equals(&self, other: &Self) -> bool; } macro_rules! totaleq_impl( ($t:ty) => { impl TotalEq for $t { #[inline] fn equals(&self, other: &$t) -> bool { *self == *other } } } ) totaleq_impl!(bool) totaleq_impl!(u8) totaleq_impl!(u16) totaleq_impl!(u32) totaleq_impl!(u64) totaleq_impl!(i8) totaleq_impl!(i16) totaleq_impl!(i32) totaleq_impl!(i64) totaleq_impl!(int) totaleq_impl!(uint) totaleq_impl!(char) /// Trait for testing approximate equality pub trait ApproxEq<Eps> { fn approx_epsilon() -> Eps; fn approx_eq(&self, other: &Self) -> bool; fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool; } #[deriving(Clone, Eq)] pub enum Ordering { Less = -1, Equal = 0, Greater = 1 } /// Trait for types that form a total order pub trait TotalOrd: TotalEq { fn cmp(&self, other: &Self) -> Ordering; } impl TotalEq for Ordering { #[inline] fn equals(&self, other: &Ordering) -> bool { *self == *other } } impl TotalOrd for Ordering { #[inline] fn cmp(&self, other: &Ordering) -> Ordering { (*self as int).cmp(&(*other as int)) }
impl Ord for Ordering { #[inline] fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) } } macro_rules! totalord_impl( ($t:ty) => { impl TotalOrd for $t { #[inline] fn cmp(&self, other: &$t) -> Ordering { if *self < *other { Less } else if *self > *other { Greater } else { Equal } } } } ) totalord_impl!(u8) totalord_impl!(u16) totalord_impl!(u32) totalord_impl!(u64) totalord_impl!(i8) totalord_impl!(i16) totalord_impl!(i32) totalord_impl!(i64) totalord_impl!(int) totalord_impl!(uint) totalord_impl!(char) /// Compares (a1, b1) against (a2, b2), where the a values are more significant. pub fn cmp2<A:TotalOrd,B:TotalOrd>( a1: &A, b1: &B, a2: &A, b2: &B) -> Ordering { match a1.cmp(a2) { Less => Less, Greater => Greater, Equal => b1.cmp(b2) } } /** Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the lexical ordering on a type `(int, int)`. */ #[inline] pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering { match o1 { Equal => o2, _ => o1 } } /** * Trait for values that can be compared for a sort-order. * * Ord only requires implementation of the `lt` method, * with the others generated from default implementations. * * However it remains possible to implement the others separately, * for compatibility with floating-point NaN semantics * (cf. IEEE 754-2008 section 5.11). */ #[lang="ord"] pub trait Ord { fn lt(&self, other: &Self) -> bool; #[inline] fn le(&self, other: &Self) -> bool {!other.lt(self) } #[inline] fn gt(&self, other: &Self) -> bool { other.lt(self) } #[inline] fn ge(&self, other: &Self) -> bool {!self.lt(other) } } /// The equivalence relation. Two values may be equivalent even if they are /// of different types. The most common use case for this relation is /// container types; e.g. it is often desirable to be able to use `&str` /// values to look up entries in a container with `~str` keys. pub trait Equiv<T> { fn equiv(&self, other: &T) -> bool; } #[inline] pub fn min<T:Ord>(v1: T, v2: T) -> T { if v1 < v2 { v1 } else { v2 } } #[inline] pub fn max<T:Ord>(v1: T, v2: T) -> T { if v1 > v2 { v1 } else { v2 } } #[cfg(test)] mod test { use super::lexical_ordering; #[test] fn test_int_totalord() { assert_eq!(5.cmp(&10), Less); assert_eq!(10.cmp(&5), Greater); assert_eq!(5.cmp(&5), Equal); assert_eq!((-5).cmp(&12), Less); assert_eq!(12.cmp(-5), Greater); } #[test] fn test_cmp2() { assert_eq!(cmp2(1, 2, 3, 4), Less); assert_eq!(cmp2(3, 2, 3, 4), Less); assert_eq!(cmp2(5, 2, 3, 4), Greater); assert_eq!(cmp2(5, 5, 5, 4), Greater); } #[test] fn test_int_totaleq() { assert!(5.equals(&5)); assert!(!2.equals(&17)); } #[test] fn test_ordering_order() { assert!(Less < Equal); assert_eq!(Greater.cmp(&Less), Greater); } #[test] fn test_lexical_ordering() { fn t(o1: Ordering, o2: Ordering, e: Ordering) { assert_eq!(lexical_ordering(o1, o2), e); } let xs = [Less, Equal, Greater]; for &o in xs.iter() { t(Less, o, Less); t(Equal, o, o); t(Greater, o, Greater); } } }
}
random_line_split
cmp.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The `Ord` and `Eq` comparison traits This module contains the definition of both `Ord` and `Eq` which define the common interfaces for doing comparison. Both are language items that the compiler uses to implement the comparison operators. Rust code may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators, and `Eq` to overload the `==` and `!=` operators. */ #[allow(missing_doc)]; /** * Trait for values that can be compared for equality and inequality. * * This trait allows partial equality, where types can be unordered instead of strictly equal or * unequal. For example, with the built-in floating-point types `a == b` and `a!= b` will both * evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11). * * Eq only requires the `eq` method to be implemented; `ne` is its negation by default. * * Eventually, this will be implemented by default for types that implement `TotalEq`. */ #[lang="eq"] pub trait Eq { fn eq(&self, other: &Self) -> bool; #[inline] fn ne(&self, other: &Self) -> bool
} /// Trait for equality comparisons where `a == b` and `a!= b` are strict inverses. pub trait TotalEq { fn equals(&self, other: &Self) -> bool; } macro_rules! totaleq_impl( ($t:ty) => { impl TotalEq for $t { #[inline] fn equals(&self, other: &$t) -> bool { *self == *other } } } ) totaleq_impl!(bool) totaleq_impl!(u8) totaleq_impl!(u16) totaleq_impl!(u32) totaleq_impl!(u64) totaleq_impl!(i8) totaleq_impl!(i16) totaleq_impl!(i32) totaleq_impl!(i64) totaleq_impl!(int) totaleq_impl!(uint) totaleq_impl!(char) /// Trait for testing approximate equality pub trait ApproxEq<Eps> { fn approx_epsilon() -> Eps; fn approx_eq(&self, other: &Self) -> bool; fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool; } #[deriving(Clone, Eq)] pub enum Ordering { Less = -1, Equal = 0, Greater = 1 } /// Trait for types that form a total order pub trait TotalOrd: TotalEq { fn cmp(&self, other: &Self) -> Ordering; } impl TotalEq for Ordering { #[inline] fn equals(&self, other: &Ordering) -> bool { *self == *other } } impl TotalOrd for Ordering { #[inline] fn cmp(&self, other: &Ordering) -> Ordering { (*self as int).cmp(&(*other as int)) } } impl Ord for Ordering { #[inline] fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) } } macro_rules! totalord_impl( ($t:ty) => { impl TotalOrd for $t { #[inline] fn cmp(&self, other: &$t) -> Ordering { if *self < *other { Less } else if *self > *other { Greater } else { Equal } } } } ) totalord_impl!(u8) totalord_impl!(u16) totalord_impl!(u32) totalord_impl!(u64) totalord_impl!(i8) totalord_impl!(i16) totalord_impl!(i32) totalord_impl!(i64) totalord_impl!(int) totalord_impl!(uint) totalord_impl!(char) /// Compares (a1, b1) against (a2, b2), where the a values are more significant. pub fn cmp2<A:TotalOrd,B:TotalOrd>( a1: &A, b1: &B, a2: &A, b2: &B) -> Ordering { match a1.cmp(a2) { Less => Less, Greater => Greater, Equal => b1.cmp(b2) } } /** Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the lexical ordering on a type `(int, int)`. */ #[inline] pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering { match o1 { Equal => o2, _ => o1 } } /** * Trait for values that can be compared for a sort-order. * * Ord only requires implementation of the `lt` method, * with the others generated from default implementations. * * However it remains possible to implement the others separately, * for compatibility with floating-point NaN semantics * (cf. IEEE 754-2008 section 5.11). */ #[lang="ord"] pub trait Ord { fn lt(&self, other: &Self) -> bool; #[inline] fn le(&self, other: &Self) -> bool {!other.lt(self) } #[inline] fn gt(&self, other: &Self) -> bool { other.lt(self) } #[inline] fn ge(&self, other: &Self) -> bool {!self.lt(other) } } /// The equivalence relation. Two values may be equivalent even if they are /// of different types. The most common use case for this relation is /// container types; e.g. it is often desirable to be able to use `&str` /// values to look up entries in a container with `~str` keys. pub trait Equiv<T> { fn equiv(&self, other: &T) -> bool; } #[inline] pub fn min<T:Ord>(v1: T, v2: T) -> T { if v1 < v2 { v1 } else { v2 } } #[inline] pub fn max<T:Ord>(v1: T, v2: T) -> T { if v1 > v2 { v1 } else { v2 } } #[cfg(test)] mod test { use super::lexical_ordering; #[test] fn test_int_totalord() { assert_eq!(5.cmp(&10), Less); assert_eq!(10.cmp(&5), Greater); assert_eq!(5.cmp(&5), Equal); assert_eq!((-5).cmp(&12), Less); assert_eq!(12.cmp(-5), Greater); } #[test] fn test_cmp2() { assert_eq!(cmp2(1, 2, 3, 4), Less); assert_eq!(cmp2(3, 2, 3, 4), Less); assert_eq!(cmp2(5, 2, 3, 4), Greater); assert_eq!(cmp2(5, 5, 5, 4), Greater); } #[test] fn test_int_totaleq() { assert!(5.equals(&5)); assert!(!2.equals(&17)); } #[test] fn test_ordering_order() { assert!(Less < Equal); assert_eq!(Greater.cmp(&Less), Greater); } #[test] fn test_lexical_ordering() { fn t(o1: Ordering, o2: Ordering, e: Ordering) { assert_eq!(lexical_ordering(o1, o2), e); } let xs = [Less, Equal, Greater]; for &o in xs.iter() { t(Less, o, Less); t(Equal, o, o); t(Greater, o, Greater); } } }
{ !self.eq(other) }
identifier_body
cmp.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The `Ord` and `Eq` comparison traits This module contains the definition of both `Ord` and `Eq` which define the common interfaces for doing comparison. Both are language items that the compiler uses to implement the comparison operators. Rust code may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators, and `Eq` to overload the `==` and `!=` operators. */ #[allow(missing_doc)]; /** * Trait for values that can be compared for equality and inequality. * * This trait allows partial equality, where types can be unordered instead of strictly equal or * unequal. For example, with the built-in floating-point types `a == b` and `a!= b` will both * evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11). * * Eq only requires the `eq` method to be implemented; `ne` is its negation by default. * * Eventually, this will be implemented by default for types that implement `TotalEq`. */ #[lang="eq"] pub trait Eq { fn eq(&self, other: &Self) -> bool; #[inline] fn
(&self, other: &Self) -> bool {!self.eq(other) } } /// Trait for equality comparisons where `a == b` and `a!= b` are strict inverses. pub trait TotalEq { fn equals(&self, other: &Self) -> bool; } macro_rules! totaleq_impl( ($t:ty) => { impl TotalEq for $t { #[inline] fn equals(&self, other: &$t) -> bool { *self == *other } } } ) totaleq_impl!(bool) totaleq_impl!(u8) totaleq_impl!(u16) totaleq_impl!(u32) totaleq_impl!(u64) totaleq_impl!(i8) totaleq_impl!(i16) totaleq_impl!(i32) totaleq_impl!(i64) totaleq_impl!(int) totaleq_impl!(uint) totaleq_impl!(char) /// Trait for testing approximate equality pub trait ApproxEq<Eps> { fn approx_epsilon() -> Eps; fn approx_eq(&self, other: &Self) -> bool; fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool; } #[deriving(Clone, Eq)] pub enum Ordering { Less = -1, Equal = 0, Greater = 1 } /// Trait for types that form a total order pub trait TotalOrd: TotalEq { fn cmp(&self, other: &Self) -> Ordering; } impl TotalEq for Ordering { #[inline] fn equals(&self, other: &Ordering) -> bool { *self == *other } } impl TotalOrd for Ordering { #[inline] fn cmp(&self, other: &Ordering) -> Ordering { (*self as int).cmp(&(*other as int)) } } impl Ord for Ordering { #[inline] fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) } } macro_rules! totalord_impl( ($t:ty) => { impl TotalOrd for $t { #[inline] fn cmp(&self, other: &$t) -> Ordering { if *self < *other { Less } else if *self > *other { Greater } else { Equal } } } } ) totalord_impl!(u8) totalord_impl!(u16) totalord_impl!(u32) totalord_impl!(u64) totalord_impl!(i8) totalord_impl!(i16) totalord_impl!(i32) totalord_impl!(i64) totalord_impl!(int) totalord_impl!(uint) totalord_impl!(char) /// Compares (a1, b1) against (a2, b2), where the a values are more significant. pub fn cmp2<A:TotalOrd,B:TotalOrd>( a1: &A, b1: &B, a2: &A, b2: &B) -> Ordering { match a1.cmp(a2) { Less => Less, Greater => Greater, Equal => b1.cmp(b2) } } /** Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the lexical ordering on a type `(int, int)`. */ #[inline] pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering { match o1 { Equal => o2, _ => o1 } } /** * Trait for values that can be compared for a sort-order. * * Ord only requires implementation of the `lt` method, * with the others generated from default implementations. * * However it remains possible to implement the others separately, * for compatibility with floating-point NaN semantics * (cf. IEEE 754-2008 section 5.11). */ #[lang="ord"] pub trait Ord { fn lt(&self, other: &Self) -> bool; #[inline] fn le(&self, other: &Self) -> bool {!other.lt(self) } #[inline] fn gt(&self, other: &Self) -> bool { other.lt(self) } #[inline] fn ge(&self, other: &Self) -> bool {!self.lt(other) } } /// The equivalence relation. Two values may be equivalent even if they are /// of different types. The most common use case for this relation is /// container types; e.g. it is often desirable to be able to use `&str` /// values to look up entries in a container with `~str` keys. pub trait Equiv<T> { fn equiv(&self, other: &T) -> bool; } #[inline] pub fn min<T:Ord>(v1: T, v2: T) -> T { if v1 < v2 { v1 } else { v2 } } #[inline] pub fn max<T:Ord>(v1: T, v2: T) -> T { if v1 > v2 { v1 } else { v2 } } #[cfg(test)] mod test { use super::lexical_ordering; #[test] fn test_int_totalord() { assert_eq!(5.cmp(&10), Less); assert_eq!(10.cmp(&5), Greater); assert_eq!(5.cmp(&5), Equal); assert_eq!((-5).cmp(&12), Less); assert_eq!(12.cmp(-5), Greater); } #[test] fn test_cmp2() { assert_eq!(cmp2(1, 2, 3, 4), Less); assert_eq!(cmp2(3, 2, 3, 4), Less); assert_eq!(cmp2(5, 2, 3, 4), Greater); assert_eq!(cmp2(5, 5, 5, 4), Greater); } #[test] fn test_int_totaleq() { assert!(5.equals(&5)); assert!(!2.equals(&17)); } #[test] fn test_ordering_order() { assert!(Less < Equal); assert_eq!(Greater.cmp(&Less), Greater); } #[test] fn test_lexical_ordering() { fn t(o1: Ordering, o2: Ordering, e: Ordering) { assert_eq!(lexical_ordering(o1, o2), e); } let xs = [Less, Equal, Greater]; for &o in xs.iter() { t(Less, o, Less); t(Equal, o, o); t(Greater, o, Greater); } } }
ne
identifier_name
static-mut-not-pat.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// except according to those terms. // Constants (static variables) can be used to match in patterns, but mutable // statics cannot. This ensures that there's some form of error if this is // attempted. static mut a: int = 3; fn main() { // If they can't be matched against, then it's possible to capture the same // name as a variable, hence this should be an unreachable pattern situation // instead of spitting out a custom error about some identifier collisions // (we should allow shadowing) match 4i { a => {} //~ ERROR mutable static variables cannot be referenced in a pattern _ => {} } } struct NewBool(bool); enum Direction { North, East, South, West } static NEW_FALSE: NewBool = NewBool(false); struct Foo { bar: Option<Direction>, baz: NewBool } static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE }; fn mutable_statics() { match (Foo { bar: Some(North), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => (), STATIC_MUT_FOO => (), //~^ ERROR mutable static variables cannot be referenced in a pattern Foo { bar: Some(South),.. } => (), Foo { bar: Some(EAST),.. } => (), Foo { bar: Some(North), baz: NewBool(true) } => (), Foo { bar: Some(EAST), baz: NewBool(false) } => () } }
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
static-mut-not-pat.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Constants (static variables) can be used to match in patterns, but mutable // statics cannot. This ensures that there's some form of error if this is // attempted. static mut a: int = 3; fn
() { // If they can't be matched against, then it's possible to capture the same // name as a variable, hence this should be an unreachable pattern situation // instead of spitting out a custom error about some identifier collisions // (we should allow shadowing) match 4i { a => {} //~ ERROR mutable static variables cannot be referenced in a pattern _ => {} } } struct NewBool(bool); enum Direction { North, East, South, West } static NEW_FALSE: NewBool = NewBool(false); struct Foo { bar: Option<Direction>, baz: NewBool } static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE }; fn mutable_statics() { match (Foo { bar: Some(North), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => (), STATIC_MUT_FOO => (), //~^ ERROR mutable static variables cannot be referenced in a pattern Foo { bar: Some(South),.. } => (), Foo { bar: Some(EAST),.. } => (), Foo { bar: Some(North), baz: NewBool(true) } => (), Foo { bar: Some(EAST), baz: NewBool(false) } => () } }
main
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate gfx_traits; extern crate ipc_channel; #[macro_use] extern crate log; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate msg; extern crate profile_traits; extern crate script_traits; extern crate servo_config; extern crate servo_url; extern crate time; use gfx_traits::{Epoch, DisplayList}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data}; use profile_traits::time::TimerMetadata; use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType}; use servo_config::opts; use servo_url::ServoUrl; use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::HashMap; use time::precise_time_ns; pub trait ProfilerMetadataFactory { fn new_metadata(&self) -> Option<TimerMetadata>; } pub trait ProgressiveWebMetric { fn get_navigation_start(&self) -> Option<u64>; fn set_navigation_start(&mut self, time: u64); fn get_time_profiler_chan(&self) -> &ProfilerChan; fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64); fn get_url(&self) -> &ServoUrl; } /// TODO make this configurable /// maximum task time is 50ms (in ns) pub const MAX_TASK_NS: u64 = 50000000; /// 10 second window (in ns) const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000; pub trait ToMs<T> { fn to_ms(&self) -> T; } impl ToMs<f64> for u64 { fn to_ms(&self) -> f64 { *self as f64 / 1000000. } } fn set_metric<U: ProgressiveWebMetric>( pwm: &U, metadata: Option<TimerMetadata>, metric_type: ProgressiveWebMetricType, category: ProfilerCategory, attr: &Cell<Option<u64>>, metric_time: Option<u64>, url: &ServoUrl, ) { let navigation_start = match pwm.get_navigation_start() { Some(time) => time, None => { warn!("Trying to set metric before navigation start"); return; }, }; let now = match metric_time { Some(time) => time, None => precise_time_ns(), }; let time = now - navigation_start; attr.set(Some(time)); // Queue performance observer notification. pwm.send_queued_constellation_msg(metric_type, time); // Send the metric to the time profiler. send_profile_data( category, metadata, &pwm.get_time_profiler_chan(), time, time, 0, 0, ); // Print the metric to console if the print-pwm option was given. if opts::get().print_pwm { println!( "Navigation start: {}", pwm.get_navigation_start().unwrap().to_ms() ); println!("{:?} {:?} {:?}", url, metric_type, time.to_ms()); } } // spec: https://github.com/WICG/time-to-interactive // https://github.com/GoogleChrome/lighthouse/issues/27 // we can look at three different metrics here: // navigation start -> visually ready (dom content loaded) // navigation start -> thread ready (main thread available) // visually ready -> thread ready #[derive(MallocSizeOf)] pub struct InteractiveMetrics { /// when we navigated to the page navigation_start: Option<u64>, /// indicates if the page is visually ready dom_content_loaded: Cell<Option<u64>>, /// main thread is available -- there's been a 10s window with no tasks longer than 50ms main_thread_available: Cell<Option<u64>>, // max(main_thread_available, dom_content_loaded) time_to_interactive: Cell<Option<u64>>, #[ignore_malloc_size_of = "can't measure channels"] time_profiler_chan: ProfilerChan, url: ServoUrl, } #[derive(Clone, Copy, Debug, MallocSizeOf)] pub struct InteractiveWindow { start: u64, } impl InteractiveWindow { pub fn new() -> InteractiveWindow { InteractiveWindow { start: precise_time_ns(), } } // We need to either start or restart the 10s window // start: we've added a new document // restart: there was a task > 50ms // not all documents are interactive pub fn start_window(&mut self) { self.start = precise_time_ns(); } /// check if 10s has elapsed since start pub fn needs_check(&self) -> bool { precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS } pub fn get_start(&self) -> u64 { self.start } } #[derive(Debug)] pub enum InteractiveFlag { DOMContentLoaded, TimeToInteractive(u64), } impl InteractiveMetrics { pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics { InteractiveMetrics { navigation_start: None, dom_content_loaded: Cell::new(None), main_thread_available: Cell::new(None), time_to_interactive: Cell::new(None), time_profiler_chan: time_profiler_chan, url, } } pub fn set_dom_content_loaded(&self) { if self.dom_content_loaded.get().is_none() { self.dom_content_loaded.set(Some(precise_time_ns())); } } pub fn set_main_thread_available(&self, time: u64) { if self.main_thread_available.get().is_none() { self.main_thread_available.set(Some(time)); } } pub fn get_dom_content_loaded(&self) -> Option<u64> { self.dom_content_loaded.get() } pub fn get_main_thread_available(&self) -> Option<u64> { self.main_thread_available.get() } // can set either dlc or tti first, but both must be set to actually calc metric // when the second is set, set_tti is called with appropriate time pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag) where T: ProfilerMetadataFactory, { if self.get_tti().is_some() { return; } match metric { InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(), InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time), } let dcl = self.dom_content_loaded.get(); let mta = self.main_thread_available.get(); let (dcl, mta) = match (dcl, mta) { (Some(dcl), Some(mta)) => (dcl, mta), _ => return, }; let metric_time = match dcl.partial_cmp(&mta) { Some(Ordering::Less) => mta, Some(_) => dcl, None => panic!("no ordering possible. something bad happened"), }; set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::TimeToInteractive, ProfilerCategory::TimeToInteractive, &self.time_to_interactive, Some(metric_time), &self.url, ); } pub fn
(&self) -> Option<u64> { self.time_to_interactive.get() } pub fn needs_tti(&self) -> bool { self.get_tti().is_none() } } impl ProgressiveWebMetric for InteractiveMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {} fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } } // https://w3c.github.io/paint-timing/ pub struct PaintTimeMetrics { pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>, navigation_start: Option<u64>, first_paint: Cell<Option<u64>>, first_contentful_paint: Cell<Option<u64>>, pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, } impl PaintTimeMetrics { pub fn new( pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, ) -> PaintTimeMetrics { PaintTimeMetrics { pending_metrics: RefCell::new(HashMap::new()), navigation_start: None, first_paint: Cell::new(None), first_contentful_paint: Cell::new(None), pipeline_id, time_profiler_chan, constellation_chan, script_chan, url, } } pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() { return; } set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, None, &self.url, ); } pub fn maybe_observe_paint_time<T>( &self, profiler_metadata_factory: &T, epoch: Epoch, display_list: &DisplayList, ) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() { // If we already set all paint metrics, we just bail out. return; } self.pending_metrics.borrow_mut().insert( epoch, ( profiler_metadata_factory.new_metadata(), display_list.is_contentful(), ), ); // Send the pending metric information to the compositor thread. // The compositor will record the current time after painting the // frame with the given ID and will send the metric back to us. let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch); if let Err(e) = self.constellation_chan.send(msg) { warn!("Failed to send PendingPaintMetric {:?}", e); } } pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() || self.navigation_start.is_none() { // If we already set all paint metrics or we have not set navigation start yet, // we just bail out. return; } if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) { let profiler_metadata = pending_metric.0; set_metric( self, profiler_metadata.clone(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, Some(paint_time), &self.url, ); if pending_metric.1 { set_metric( self, profiler_metadata, ProgressiveWebMetricType::FirstContentfulPaint, ProfilerCategory::TimeToFirstContentfulPaint, &self.first_contentful_paint, Some(paint_time), &self.url, ); } } } pub fn get_first_paint(&self) -> Option<u64> { self.first_paint.get() } pub fn get_first_contentful_paint(&self) -> Option<u64> { self.first_contentful_paint.get() } } impl ProgressiveWebMetric for PaintTimeMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) { let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time); if let Err(e) = self.script_chan.send(msg) { warn!("Sending metric to script thread failed ({}).", e); } } fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } }
get_tti
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate gfx_traits; extern crate ipc_channel; #[macro_use] extern crate log; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate msg; extern crate profile_traits; extern crate script_traits; extern crate servo_config; extern crate servo_url; extern crate time; use gfx_traits::{Epoch, DisplayList}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data}; use profile_traits::time::TimerMetadata; use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType}; use servo_config::opts; use servo_url::ServoUrl; use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::HashMap; use time::precise_time_ns; pub trait ProfilerMetadataFactory { fn new_metadata(&self) -> Option<TimerMetadata>; } pub trait ProgressiveWebMetric { fn get_navigation_start(&self) -> Option<u64>; fn set_navigation_start(&mut self, time: u64); fn get_time_profiler_chan(&self) -> &ProfilerChan; fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64); fn get_url(&self) -> &ServoUrl; } /// TODO make this configurable /// maximum task time is 50ms (in ns) pub const MAX_TASK_NS: u64 = 50000000; /// 10 second window (in ns) const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000; pub trait ToMs<T> { fn to_ms(&self) -> T; } impl ToMs<f64> for u64 { fn to_ms(&self) -> f64
} fn set_metric<U: ProgressiveWebMetric>( pwm: &U, metadata: Option<TimerMetadata>, metric_type: ProgressiveWebMetricType, category: ProfilerCategory, attr: &Cell<Option<u64>>, metric_time: Option<u64>, url: &ServoUrl, ) { let navigation_start = match pwm.get_navigation_start() { Some(time) => time, None => { warn!("Trying to set metric before navigation start"); return; }, }; let now = match metric_time { Some(time) => time, None => precise_time_ns(), }; let time = now - navigation_start; attr.set(Some(time)); // Queue performance observer notification. pwm.send_queued_constellation_msg(metric_type, time); // Send the metric to the time profiler. send_profile_data( category, metadata, &pwm.get_time_profiler_chan(), time, time, 0, 0, ); // Print the metric to console if the print-pwm option was given. if opts::get().print_pwm { println!( "Navigation start: {}", pwm.get_navigation_start().unwrap().to_ms() ); println!("{:?} {:?} {:?}", url, metric_type, time.to_ms()); } } // spec: https://github.com/WICG/time-to-interactive // https://github.com/GoogleChrome/lighthouse/issues/27 // we can look at three different metrics here: // navigation start -> visually ready (dom content loaded) // navigation start -> thread ready (main thread available) // visually ready -> thread ready #[derive(MallocSizeOf)] pub struct InteractiveMetrics { /// when we navigated to the page navigation_start: Option<u64>, /// indicates if the page is visually ready dom_content_loaded: Cell<Option<u64>>, /// main thread is available -- there's been a 10s window with no tasks longer than 50ms main_thread_available: Cell<Option<u64>>, // max(main_thread_available, dom_content_loaded) time_to_interactive: Cell<Option<u64>>, #[ignore_malloc_size_of = "can't measure channels"] time_profiler_chan: ProfilerChan, url: ServoUrl, } #[derive(Clone, Copy, Debug, MallocSizeOf)] pub struct InteractiveWindow { start: u64, } impl InteractiveWindow { pub fn new() -> InteractiveWindow { InteractiveWindow { start: precise_time_ns(), } } // We need to either start or restart the 10s window // start: we've added a new document // restart: there was a task > 50ms // not all documents are interactive pub fn start_window(&mut self) { self.start = precise_time_ns(); } /// check if 10s has elapsed since start pub fn needs_check(&self) -> bool { precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS } pub fn get_start(&self) -> u64 { self.start } } #[derive(Debug)] pub enum InteractiveFlag { DOMContentLoaded, TimeToInteractive(u64), } impl InteractiveMetrics { pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics { InteractiveMetrics { navigation_start: None, dom_content_loaded: Cell::new(None), main_thread_available: Cell::new(None), time_to_interactive: Cell::new(None), time_profiler_chan: time_profiler_chan, url, } } pub fn set_dom_content_loaded(&self) { if self.dom_content_loaded.get().is_none() { self.dom_content_loaded.set(Some(precise_time_ns())); } } pub fn set_main_thread_available(&self, time: u64) { if self.main_thread_available.get().is_none() { self.main_thread_available.set(Some(time)); } } pub fn get_dom_content_loaded(&self) -> Option<u64> { self.dom_content_loaded.get() } pub fn get_main_thread_available(&self) -> Option<u64> { self.main_thread_available.get() } // can set either dlc or tti first, but both must be set to actually calc metric // when the second is set, set_tti is called with appropriate time pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag) where T: ProfilerMetadataFactory, { if self.get_tti().is_some() { return; } match metric { InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(), InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time), } let dcl = self.dom_content_loaded.get(); let mta = self.main_thread_available.get(); let (dcl, mta) = match (dcl, mta) { (Some(dcl), Some(mta)) => (dcl, mta), _ => return, }; let metric_time = match dcl.partial_cmp(&mta) { Some(Ordering::Less) => mta, Some(_) => dcl, None => panic!("no ordering possible. something bad happened"), }; set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::TimeToInteractive, ProfilerCategory::TimeToInteractive, &self.time_to_interactive, Some(metric_time), &self.url, ); } pub fn get_tti(&self) -> Option<u64> { self.time_to_interactive.get() } pub fn needs_tti(&self) -> bool { self.get_tti().is_none() } } impl ProgressiveWebMetric for InteractiveMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {} fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } } // https://w3c.github.io/paint-timing/ pub struct PaintTimeMetrics { pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>, navigation_start: Option<u64>, first_paint: Cell<Option<u64>>, first_contentful_paint: Cell<Option<u64>>, pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, } impl PaintTimeMetrics { pub fn new( pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, ) -> PaintTimeMetrics { PaintTimeMetrics { pending_metrics: RefCell::new(HashMap::new()), navigation_start: None, first_paint: Cell::new(None), first_contentful_paint: Cell::new(None), pipeline_id, time_profiler_chan, constellation_chan, script_chan, url, } } pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() { return; } set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, None, &self.url, ); } pub fn maybe_observe_paint_time<T>( &self, profiler_metadata_factory: &T, epoch: Epoch, display_list: &DisplayList, ) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() { // If we already set all paint metrics, we just bail out. return; } self.pending_metrics.borrow_mut().insert( epoch, ( profiler_metadata_factory.new_metadata(), display_list.is_contentful(), ), ); // Send the pending metric information to the compositor thread. // The compositor will record the current time after painting the // frame with the given ID and will send the metric back to us. let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch); if let Err(e) = self.constellation_chan.send(msg) { warn!("Failed to send PendingPaintMetric {:?}", e); } } pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() || self.navigation_start.is_none() { // If we already set all paint metrics or we have not set navigation start yet, // we just bail out. return; } if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) { let profiler_metadata = pending_metric.0; set_metric( self, profiler_metadata.clone(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, Some(paint_time), &self.url, ); if pending_metric.1 { set_metric( self, profiler_metadata, ProgressiveWebMetricType::FirstContentfulPaint, ProfilerCategory::TimeToFirstContentfulPaint, &self.first_contentful_paint, Some(paint_time), &self.url, ); } } } pub fn get_first_paint(&self) -> Option<u64> { self.first_paint.get() } pub fn get_first_contentful_paint(&self) -> Option<u64> { self.first_contentful_paint.get() } } impl ProgressiveWebMetric for PaintTimeMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) { let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time); if let Err(e) = self.script_chan.send(msg) { warn!("Sending metric to script thread failed ({}).", e); } } fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } }
{ *self as f64 / 1000000. }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate gfx_traits; extern crate ipc_channel; #[macro_use] extern crate log; extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; extern crate msg; extern crate profile_traits; extern crate script_traits; extern crate servo_config; extern crate servo_url; extern crate time; use gfx_traits::{Epoch, DisplayList}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data}; use profile_traits::time::TimerMetadata; use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType}; use servo_config::opts; use servo_url::ServoUrl; use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::HashMap; use time::precise_time_ns; pub trait ProfilerMetadataFactory { fn new_metadata(&self) -> Option<TimerMetadata>; } pub trait ProgressiveWebMetric { fn get_navigation_start(&self) -> Option<u64>; fn set_navigation_start(&mut self, time: u64); fn get_time_profiler_chan(&self) -> &ProfilerChan; fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64); fn get_url(&self) -> &ServoUrl; } /// TODO make this configurable /// maximum task time is 50ms (in ns) pub const MAX_TASK_NS: u64 = 50000000; /// 10 second window (in ns) const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000; pub trait ToMs<T> { fn to_ms(&self) -> T; } impl ToMs<f64> for u64 { fn to_ms(&self) -> f64 { *self as f64 / 1000000. } } fn set_metric<U: ProgressiveWebMetric>( pwm: &U, metadata: Option<TimerMetadata>, metric_type: ProgressiveWebMetricType, category: ProfilerCategory, attr: &Cell<Option<u64>>, metric_time: Option<u64>, url: &ServoUrl, ) { let navigation_start = match pwm.get_navigation_start() { Some(time) => time, None => { warn!("Trying to set metric before navigation start"); return; }, }; let now = match metric_time { Some(time) => time, None => precise_time_ns(), }; let time = now - navigation_start; attr.set(Some(time)); // Queue performance observer notification. pwm.send_queued_constellation_msg(metric_type, time); // Send the metric to the time profiler. send_profile_data( category, metadata, &pwm.get_time_profiler_chan(), time, time, 0, 0, ); // Print the metric to console if the print-pwm option was given. if opts::get().print_pwm { println!( "Navigation start: {}", pwm.get_navigation_start().unwrap().to_ms() ); println!("{:?} {:?} {:?}", url, metric_type, time.to_ms()); } } // spec: https://github.com/WICG/time-to-interactive // https://github.com/GoogleChrome/lighthouse/issues/27 // we can look at three different metrics here: // navigation start -> visually ready (dom content loaded) // navigation start -> thread ready (main thread available) // visually ready -> thread ready #[derive(MallocSizeOf)] pub struct InteractiveMetrics { /// when we navigated to the page navigation_start: Option<u64>, /// indicates if the page is visually ready dom_content_loaded: Cell<Option<u64>>, /// main thread is available -- there's been a 10s window with no tasks longer than 50ms main_thread_available: Cell<Option<u64>>, // max(main_thread_available, dom_content_loaded) time_to_interactive: Cell<Option<u64>>, #[ignore_malloc_size_of = "can't measure channels"] time_profiler_chan: ProfilerChan, url: ServoUrl, } #[derive(Clone, Copy, Debug, MallocSizeOf)] pub struct InteractiveWindow { start: u64, } impl InteractiveWindow { pub fn new() -> InteractiveWindow { InteractiveWindow { start: precise_time_ns(), } } // We need to either start or restart the 10s window // start: we've added a new document // restart: there was a task > 50ms // not all documents are interactive pub fn start_window(&mut self) { self.start = precise_time_ns(); } /// check if 10s has elapsed since start pub fn needs_check(&self) -> bool { precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS } pub fn get_start(&self) -> u64 { self.start } } #[derive(Debug)] pub enum InteractiveFlag { DOMContentLoaded, TimeToInteractive(u64), } impl InteractiveMetrics { pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics { InteractiveMetrics { navigation_start: None, dom_content_loaded: Cell::new(None), main_thread_available: Cell::new(None), time_to_interactive: Cell::new(None), time_profiler_chan: time_profiler_chan, url, } } pub fn set_dom_content_loaded(&self) { if self.dom_content_loaded.get().is_none() { self.dom_content_loaded.set(Some(precise_time_ns())); } } pub fn set_main_thread_available(&self, time: u64) {
pub fn get_dom_content_loaded(&self) -> Option<u64> { self.dom_content_loaded.get() } pub fn get_main_thread_available(&self) -> Option<u64> { self.main_thread_available.get() } // can set either dlc or tti first, but both must be set to actually calc metric // when the second is set, set_tti is called with appropriate time pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag) where T: ProfilerMetadataFactory, { if self.get_tti().is_some() { return; } match metric { InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(), InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time), } let dcl = self.dom_content_loaded.get(); let mta = self.main_thread_available.get(); let (dcl, mta) = match (dcl, mta) { (Some(dcl), Some(mta)) => (dcl, mta), _ => return, }; let metric_time = match dcl.partial_cmp(&mta) { Some(Ordering::Less) => mta, Some(_) => dcl, None => panic!("no ordering possible. something bad happened"), }; set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::TimeToInteractive, ProfilerCategory::TimeToInteractive, &self.time_to_interactive, Some(metric_time), &self.url, ); } pub fn get_tti(&self) -> Option<u64> { self.time_to_interactive.get() } pub fn needs_tti(&self) -> bool { self.get_tti().is_none() } } impl ProgressiveWebMetric for InteractiveMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {} fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } } // https://w3c.github.io/paint-timing/ pub struct PaintTimeMetrics { pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>, navigation_start: Option<u64>, first_paint: Cell<Option<u64>>, first_contentful_paint: Cell<Option<u64>>, pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, } impl PaintTimeMetrics { pub fn new( pipeline_id: PipelineId, time_profiler_chan: ProfilerChan, constellation_chan: IpcSender<LayoutMsg>, script_chan: IpcSender<ConstellationControlMsg>, url: ServoUrl, ) -> PaintTimeMetrics { PaintTimeMetrics { pending_metrics: RefCell::new(HashMap::new()), navigation_start: None, first_paint: Cell::new(None), first_contentful_paint: Cell::new(None), pipeline_id, time_profiler_chan, constellation_chan, script_chan, url, } } pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() { return; } set_metric( self, profiler_metadata_factory.new_metadata(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, None, &self.url, ); } pub fn maybe_observe_paint_time<T>( &self, profiler_metadata_factory: &T, epoch: Epoch, display_list: &DisplayList, ) where T: ProfilerMetadataFactory, { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() { // If we already set all paint metrics, we just bail out. return; } self.pending_metrics.borrow_mut().insert( epoch, ( profiler_metadata_factory.new_metadata(), display_list.is_contentful(), ), ); // Send the pending metric information to the compositor thread. // The compositor will record the current time after painting the // frame with the given ID and will send the metric back to us. let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch); if let Err(e) = self.constellation_chan.send(msg) { warn!("Failed to send PendingPaintMetric {:?}", e); } } pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) { if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() || self.navigation_start.is_none() { // If we already set all paint metrics or we have not set navigation start yet, // we just bail out. return; } if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) { let profiler_metadata = pending_metric.0; set_metric( self, profiler_metadata.clone(), ProgressiveWebMetricType::FirstPaint, ProfilerCategory::TimeToFirstPaint, &self.first_paint, Some(paint_time), &self.url, ); if pending_metric.1 { set_metric( self, profiler_metadata, ProgressiveWebMetricType::FirstContentfulPaint, ProfilerCategory::TimeToFirstContentfulPaint, &self.first_contentful_paint, Some(paint_time), &self.url, ); } } } pub fn get_first_paint(&self) -> Option<u64> { self.first_paint.get() } pub fn get_first_contentful_paint(&self) -> Option<u64> { self.first_contentful_paint.get() } } impl ProgressiveWebMetric for PaintTimeMetrics { fn get_navigation_start(&self) -> Option<u64> { self.navigation_start } fn set_navigation_start(&mut self, time: u64) { self.navigation_start = Some(time); } fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) { let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time); if let Err(e) = self.script_chan.send(msg) { warn!("Sending metric to script thread failed ({}).", e); } } fn get_time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } fn get_url(&self) -> &ServoUrl { &self.url } }
if self.main_thread_available.get().is_none() { self.main_thread_available.set(Some(time)); } }
random_line_split
browsercontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Reflectable; use dom::document::Document; use dom::window::Window; use js::jsapi::JSObject; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::rust::with_compartment; use libc::c_void; use std::ptr; #[allow(raw_pointer_deriving)] #[deriving(Encodable)] pub struct BrowserContext { history: Vec<SessionHistoryEntry>, active_index: uint, window_proxy: Traceable<*mut JSObject>, } impl BrowserContext { pub fn new(document: JSRef<Document>) -> BrowserContext { let mut context = BrowserContext { history: vec!(SessionHistoryEntry::new(document)), active_index: 0, window_proxy: Traceable::new(ptr::null_mut()), }; context.create_window_proxy(); context } pub fn active_document(&self) -> Temporary<Document> { Temporary::new(self.history[self.active_index].document.clone()) } pub fn active_window(&self) -> Temporary<Window> { let doc = self.active_document().root(); Temporary::new(doc.deref().window.clone()) } pub fn window_proxy(&self) -> *mut JSObject { assert!(self.window_proxy.deref().is_not_null()); *self.window_proxy } fn
(&mut self) { let win = self.active_window().root(); let page = win.deref().page(); let js_info = page.js_info(); let handler = js_info.as_ref().unwrap().dom_static.windowproxy_handler; assert!(handler.deref().is_not_null()); let parent = win.deref().reflector().get_jsobject(); let cx = js_info.as_ref().unwrap().js_context.deref().deref().ptr; let wrapper = with_compartment(cx, parent, || unsafe { WrapperNew(cx, parent, *handler.deref()) }); assert!(wrapper.is_not_null()); self.window_proxy = Traceable::new(wrapper); } } #[deriving(Encodable)] #[must_root] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<BrowserContext> } impl SessionHistoryEntry { fn new(document: JSRef<Document>) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_rooted(document), children: vec!() } } } static proxy_handler: ProxyTraps = ProxyTraps { getPropertyDescriptor: None, getOwnPropertyDescriptor: None, defineProperty: None, getOwnPropertyNames: 0 as *const u8, delete_: None, enumerate: 0 as *const u8, has: None, hasOwn: None, get: None, set: None, keys: 0 as *const u8, iterate: None, call: None, construct: None, nativeCall: 0 as *const u8, hasInstance: None, typeOf: None, objectClassIs: None, obj_toString: None, fun_toString: None, //regexp_toShared: 0 as *u8, defaultValue: None, iteratorNext: None, finalize: None, getElementIfPresent: None, getPrototypeOf: None, trace: None }; pub fn new_window_proxy_handler() -> *const c_void { unsafe { CreateWrapperProxyHandler(&proxy_handler) } }
create_window_proxy
identifier_name
browsercontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Reflectable; use dom::document::Document; use dom::window::Window; use js::jsapi::JSObject; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::rust::with_compartment; use libc::c_void; use std::ptr; #[allow(raw_pointer_deriving)] #[deriving(Encodable)] pub struct BrowserContext { history: Vec<SessionHistoryEntry>, active_index: uint, window_proxy: Traceable<*mut JSObject>, } impl BrowserContext { pub fn new(document: JSRef<Document>) -> BrowserContext { let mut context = BrowserContext { history: vec!(SessionHistoryEntry::new(document)), active_index: 0, window_proxy: Traceable::new(ptr::null_mut()), }; context.create_window_proxy(); context } pub fn active_document(&self) -> Temporary<Document>
pub fn active_window(&self) -> Temporary<Window> { let doc = self.active_document().root(); Temporary::new(doc.deref().window.clone()) } pub fn window_proxy(&self) -> *mut JSObject { assert!(self.window_proxy.deref().is_not_null()); *self.window_proxy } fn create_window_proxy(&mut self) { let win = self.active_window().root(); let page = win.deref().page(); let js_info = page.js_info(); let handler = js_info.as_ref().unwrap().dom_static.windowproxy_handler; assert!(handler.deref().is_not_null()); let parent = win.deref().reflector().get_jsobject(); let cx = js_info.as_ref().unwrap().js_context.deref().deref().ptr; let wrapper = with_compartment(cx, parent, || unsafe { WrapperNew(cx, parent, *handler.deref()) }); assert!(wrapper.is_not_null()); self.window_proxy = Traceable::new(wrapper); } } #[deriving(Encodable)] #[must_root] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<BrowserContext> } impl SessionHistoryEntry { fn new(document: JSRef<Document>) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_rooted(document), children: vec!() } } } static proxy_handler: ProxyTraps = ProxyTraps { getPropertyDescriptor: None, getOwnPropertyDescriptor: None, defineProperty: None, getOwnPropertyNames: 0 as *const u8, delete_: None, enumerate: 0 as *const u8, has: None, hasOwn: None, get: None, set: None, keys: 0 as *const u8, iterate: None, call: None, construct: None, nativeCall: 0 as *const u8, hasInstance: None, typeOf: None, objectClassIs: None, obj_toString: None, fun_toString: None, //regexp_toShared: 0 as *u8, defaultValue: None, iteratorNext: None, finalize: None, getElementIfPresent: None, getPrototypeOf: None, trace: None }; pub fn new_window_proxy_handler() -> *const c_void { unsafe { CreateWrapperProxyHandler(&proxy_handler) } }
{ Temporary::new(self.history[self.active_index].document.clone()) }
identifier_body
browsercontext.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Reflectable; use dom::document::Document;
use dom::window::Window; use js::jsapi::JSObject; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::rust::with_compartment; use libc::c_void; use std::ptr; #[allow(raw_pointer_deriving)] #[deriving(Encodable)] pub struct BrowserContext { history: Vec<SessionHistoryEntry>, active_index: uint, window_proxy: Traceable<*mut JSObject>, } impl BrowserContext { pub fn new(document: JSRef<Document>) -> BrowserContext { let mut context = BrowserContext { history: vec!(SessionHistoryEntry::new(document)), active_index: 0, window_proxy: Traceable::new(ptr::null_mut()), }; context.create_window_proxy(); context } pub fn active_document(&self) -> Temporary<Document> { Temporary::new(self.history[self.active_index].document.clone()) } pub fn active_window(&self) -> Temporary<Window> { let doc = self.active_document().root(); Temporary::new(doc.deref().window.clone()) } pub fn window_proxy(&self) -> *mut JSObject { assert!(self.window_proxy.deref().is_not_null()); *self.window_proxy } fn create_window_proxy(&mut self) { let win = self.active_window().root(); let page = win.deref().page(); let js_info = page.js_info(); let handler = js_info.as_ref().unwrap().dom_static.windowproxy_handler; assert!(handler.deref().is_not_null()); let parent = win.deref().reflector().get_jsobject(); let cx = js_info.as_ref().unwrap().js_context.deref().deref().ptr; let wrapper = with_compartment(cx, parent, || unsafe { WrapperNew(cx, parent, *handler.deref()) }); assert!(wrapper.is_not_null()); self.window_proxy = Traceable::new(wrapper); } } #[deriving(Encodable)] #[must_root] pub struct SessionHistoryEntry { document: JS<Document>, children: Vec<BrowserContext> } impl SessionHistoryEntry { fn new(document: JSRef<Document>) -> SessionHistoryEntry { SessionHistoryEntry { document: JS::from_rooted(document), children: vec!() } } } static proxy_handler: ProxyTraps = ProxyTraps { getPropertyDescriptor: None, getOwnPropertyDescriptor: None, defineProperty: None, getOwnPropertyNames: 0 as *const u8, delete_: None, enumerate: 0 as *const u8, has: None, hasOwn: None, get: None, set: None, keys: 0 as *const u8, iterate: None, call: None, construct: None, nativeCall: 0 as *const u8, hasInstance: None, typeOf: None, objectClassIs: None, obj_toString: None, fun_toString: None, //regexp_toShared: 0 as *u8, defaultValue: None, iteratorNext: None, finalize: None, getElementIfPresent: None, getPrototypeOf: None, trace: None }; pub fn new_window_proxy_handler() -> *const c_void { unsafe { CreateWrapperProxyHandler(&proxy_handler) } }
random_line_split
htmlmodelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct
{ htmlelement: HTMLElement, } impl HTMLModElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLModElement> { Node::reflect_node( Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), document, HTMLModElementBinding::Wrap, ) } }
HTMLModElement
identifier_name
htmlmodelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLModElement { htmlelement: HTMLElement, } impl HTMLModElement { fn new_inherited( local_name: LocalName,
prefix: Option<Prefix>, document: &Document, ) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLModElement> { Node::reflect_node( Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), document, HTMLModElementBinding::Wrap, ) } }
random_line_split
htmlmodelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLModElement { htmlelement: HTMLElement, } impl HTMLModElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLModElement>
}
{ Node::reflect_node( Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), document, HTMLModElementBinding::Wrap, ) }
identifier_body
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main()
let _ = tx.send(()); // let mut line = String::new(); // let stdin = io::stdin(); // for _ in 0..4 { // let _ = stdin.lock().read_line(&mut line); // let _ = tx.send(()); // } }
{ println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { Ok(_) => { println!("Terminating."); break; } Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::sleep(Duration::from_millis(50000));
identifier_body
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending...");
Ok(_) => { println!("Terminating."); break; } Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::sleep(Duration::from_millis(50000)); let _ = tx.send(()); // let mut line = String::new(); // let stdin = io::stdin(); // for _ in 0..4 { // let _ = stdin.lock().read_line(&mut line); // let _ = tx.send(()); // } }
match rx.try_recv() {
random_line_split
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn
() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { Ok(_) => { println!("Terminating."); break; } Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::sleep(Duration::from_millis(50000)); let _ = tx.send(()); // let mut line = String::new(); // let stdin = io::stdin(); // for _ in 0..4 { // let _ = stdin.lock().read_line(&mut line); // let _ = tx.send(()); // } }
main
identifier_name
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { Ok(_) =>
Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::sleep(Duration::from_millis(50000)); let _ = tx.send(()); // let mut line = String::new(); // let stdin = io::stdin(); // for _ in 0..4 { // let _ = stdin.lock().read_line(&mut line); // let _ = tx.send(()); // } }
{ println!("Terminating."); break; }
conditional_block
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; use log::SetLoggerError; use slog::{self, DrainExt, FilterLevel, Level}; use slog_envlogger::LogBuilder; use slog_stdlog; use slog_stream; use time; // Default logging level defined using the two enums used by slog. // Both values must correspond to the same level. (This is checked by a test). const DEFAULT_LEVEL: Level = Level::Info; const DEFAULT_FILTER_LEVEL: FilterLevel = FilterLevel::Info; // Arrays of log levels, indexed by verbosity. const POSITIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Debug, FilterLevel::Trace, ]; const NEGATIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Warning, FilterLevel::Error, FilterLevel::Critical, FilterLevel::Off, ]; /// Initialize logging with given verbosity. /// The verbosity value has the same meaning as in args::Options::verbosity. pub fn init(verbosity: isize) -> Result<(), SetLoggerError> { let istty = cfg!(unix) && isatty::stderr_isatty(); let stderr = slog_stream::stream(io::stderr(), LogFormat{tty: istty}); // Determine the log filtering level based on verbosity. // If the argument is excessive, log that but clamp to the highest/lowest log level. let mut verbosity = verbosity; let mut excessive = false; let level = if verbosity >= 0 { if verbosity >= POSITIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = POSITIVE_VERBOSITY_LEVELS.len() as isize - 1; } POSITIVE_VERBOSITY_LEVELS[verbosity as usize] } else { verbosity = -verbosity; if verbosity >= NEGATIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = NEGATIVE_VERBOSITY_LEVELS.len() as isize - 1; } NEGATIVE_VERBOSITY_LEVELS[verbosity as usize] }; // Include universal logger options, like the level. let mut builder = LogBuilder::new(stderr); builder = builder.filter(None, level); // Make some of the libraries less chatty. builder = builder .filter(Some("html5ever"), FilterLevel::Info) .filter(Some("hyper"), FilterLevel::Info); // Include any additional config from environmental variables. // This will override the options above if necessary, // so e.g. it is still possible to get full debug output from hyper. if let Ok(ref conf) = env::var("RUST_LOG") { builder = builder.parse(conf); } // Initialize the logger, possibly logging the excessive verbosity option. // TODO: migrate off of `log` macro to slog completely, // so that slog_scope is used to set up the application's logger // and slog_stdlog is only for the libraries like hyper that use `log` macros let env_logger_drain = builder.build(); let logger = slog::Logger::root(env_logger_drain.fuse(), o!()); try!(slog_stdlog::set_logger(logger)); if excessive { warn!("-v/-q flag passed too many times, logging level {:?} assumed", level); } Ok(()) } // Log formatting /// Token type that's only uses to tell slog-stream how to format our log entries. struct LogFormat { pub tty: bool, } impl slog_stream::Format for LogFormat { /// Format a single log Record and write it to given output. fn format(&self, output: &mut io::Write, record: &slog::Record, _logger_kvp: &slog::OwnedKeyValueList) -> io::Result<()> { // Format the higher level (more fine-grained) messages with greater detail, // as they are only visible when user explicitly enables verbose logging. let msg = if record.level() > DEFAULT_LEVEL { let logtime = format_log_time(); let level: String = { let first_char = record.level().as_str().chars().next().unwrap(); first_char.to_uppercase().collect() }; let module = { let module = record.module(); match module.find("::") { Some(idx) => Cow::Borrowed(&module[idx + 2..]), None => "main".into(), } }; // Dim the prefix (everything that's not a message) if we're outputting to a TTY. let prefix_style = if self.tty { *TTY_FINE_PREFIX_STYLE } else { Style::default() }; let prefix = format!("{}{} {}#{}]", level, logtime, module, record.line()); format!("{} {}\n", prefix_style.paint(prefix), record.msg()) } else { // Colorize the level label if we're outputting to a TTY. let level: Cow<str> = if self.tty { let style = TTY_LEVEL_STYLES.get(&record.level().as_usize()) .cloned() .unwrap_or_else(Style::default); format!("{}", style.paint(record.level().as_str())).into() } else { record.level().as_str().into() }; format!("{}: {}\n", level, record.msg()) }; try!(output.write_all(msg.as_bytes())); Ok(()) } } /// Format the timestamp part of a detailed log entry. fn
() -> String { let utc_now = time::now().to_utc(); let mut logtime = format!("{}", utc_now.rfc3339()); // E.g.: 2012-02-22T14:53:18Z // Insert millisecond count before the Z. let millis = utc_now.tm_nsec / NANOS_IN_MILLISEC; logtime.pop(); format!("{}.{:04}Z", logtime, millis) } const NANOS_IN_MILLISEC: i32 = 1000000; lazy_static! { /// Map of log levels to their ANSI terminal styles. // (Level doesn't implement Hash so it has to be usize). static ref TTY_LEVEL_STYLES: HashMap<usize, Style> = hashmap!{ Level::Info.as_usize() => Colour::Green.normal(), Level::Warning.as_usize() => Colour::Yellow.normal(), Level::Error.as_usize() => Colour::Red.normal(), Level::Critical.as_usize() => Colour::Purple.normal(), }; /// ANSI terminal style for the prefix (timestamp etc.) of a fine log message. static ref TTY_FINE_PREFIX_STYLE: Style = Style::new().dimmed(); } #[cfg(test)] mod tests { use slog::FilterLevel; use super::{DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL, NEGATIVE_VERBOSITY_LEVELS, POSITIVE_VERBOSITY_LEVELS}; /// Check that default logging level is defined consistently. #[test] fn default_level() { let level = DEFAULT_LEVEL.as_usize(); let filter_level = DEFAULT_FILTER_LEVEL.as_usize(); assert_eq!(level, filter_level, "Default logging level is defined inconsistently: Level::{:?} vs. FilterLevel::{:?}", DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL); } #[test] fn verbosity_levels() { assert_eq!(NEGATIVE_VERBOSITY_LEVELS[0], POSITIVE_VERBOSITY_LEVELS[0]); assert!(NEGATIVE_VERBOSITY_LEVELS.contains(&FilterLevel::Off), "Verbosity levels don't allow to turn logging off completely"); } }
format_log_time
identifier_name
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; use log::SetLoggerError; use slog::{self, DrainExt, FilterLevel, Level}; use slog_envlogger::LogBuilder; use slog_stdlog; use slog_stream; use time; // Default logging level defined using the two enums used by slog. // Both values must correspond to the same level. (This is checked by a test). const DEFAULT_LEVEL: Level = Level::Info; const DEFAULT_FILTER_LEVEL: FilterLevel = FilterLevel::Info; // Arrays of log levels, indexed by verbosity. const POSITIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Debug, FilterLevel::Trace, ]; const NEGATIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Warning, FilterLevel::Error, FilterLevel::Critical, FilterLevel::Off, ]; /// Initialize logging with given verbosity. /// The verbosity value has the same meaning as in args::Options::verbosity. pub fn init(verbosity: isize) -> Result<(), SetLoggerError> { let istty = cfg!(unix) && isatty::stderr_isatty(); let stderr = slog_stream::stream(io::stderr(), LogFormat{tty: istty}); // Determine the log filtering level based on verbosity. // If the argument is excessive, log that but clamp to the highest/lowest log level. let mut verbosity = verbosity; let mut excessive = false; let level = if verbosity >= 0 { if verbosity >= POSITIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = POSITIVE_VERBOSITY_LEVELS.len() as isize - 1; } POSITIVE_VERBOSITY_LEVELS[verbosity as usize] } else { verbosity = -verbosity; if verbosity >= NEGATIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = NEGATIVE_VERBOSITY_LEVELS.len() as isize - 1; } NEGATIVE_VERBOSITY_LEVELS[verbosity as usize] }; // Include universal logger options, like the level. let mut builder = LogBuilder::new(stderr); builder = builder.filter(None, level); // Make some of the libraries less chatty. builder = builder .filter(Some("html5ever"), FilterLevel::Info) .filter(Some("hyper"), FilterLevel::Info); // Include any additional config from environmental variables. // This will override the options above if necessary, // so e.g. it is still possible to get full debug output from hyper. if let Ok(ref conf) = env::var("RUST_LOG") { builder = builder.parse(conf); } // Initialize the logger, possibly logging the excessive verbosity option. // TODO: migrate off of `log` macro to slog completely, // so that slog_scope is used to set up the application's logger // and slog_stdlog is only for the libraries like hyper that use `log` macros let env_logger_drain = builder.build(); let logger = slog::Logger::root(env_logger_drain.fuse(), o!()); try!(slog_stdlog::set_logger(logger)); if excessive { warn!("-v/-q flag passed too many times, logging level {:?} assumed", level); } Ok(()) } // Log formatting /// Token type that's only uses to tell slog-stream how to format our log entries. struct LogFormat { pub tty: bool, } impl slog_stream::Format for LogFormat { /// Format a single log Record and write it to given output. fn format(&self, output: &mut io::Write, record: &slog::Record, _logger_kvp: &slog::OwnedKeyValueList) -> io::Result<()> { // Format the higher level (more fine-grained) messages with greater detail, // as they are only visible when user explicitly enables verbose logging. let msg = if record.level() > DEFAULT_LEVEL { let logtime = format_log_time(); let level: String = { let first_char = record.level().as_str().chars().next().unwrap(); first_char.to_uppercase().collect() }; let module = { let module = record.module(); match module.find("::") { Some(idx) => Cow::Borrowed(&module[idx + 2..]), None => "main".into(), } }; // Dim the prefix (everything that's not a message) if we're outputting to a TTY. let prefix_style = if self.tty { *TTY_FINE_PREFIX_STYLE } else { Style::default() }; let prefix = format!("{}{} {}#{}]", level, logtime, module, record.line()); format!("{} {}\n", prefix_style.paint(prefix), record.msg()) } else { // Colorize the level label if we're outputting to a TTY. let level: Cow<str> = if self.tty { let style = TTY_LEVEL_STYLES.get(&record.level().as_usize()) .cloned() .unwrap_or_else(Style::default); format!("{}", style.paint(record.level().as_str())).into() } else { record.level().as_str().into() }; format!("{}: {}\n", level, record.msg()) }; try!(output.write_all(msg.as_bytes())); Ok(()) } } /// Format the timestamp part of a detailed log entry. fn format_log_time() -> String { let utc_now = time::now().to_utc(); let mut logtime = format!("{}", utc_now.rfc3339()); // E.g.: 2012-02-22T14:53:18Z // Insert millisecond count before the Z. let millis = utc_now.tm_nsec / NANOS_IN_MILLISEC; logtime.pop(); format!("{}.{:04}Z", logtime, millis) } const NANOS_IN_MILLISEC: i32 = 1000000; lazy_static! { /// Map of log levels to their ANSI terminal styles. // (Level doesn't implement Hash so it has to be usize). static ref TTY_LEVEL_STYLES: HashMap<usize, Style> = hashmap!{ Level::Info.as_usize() => Colour::Green.normal(), Level::Warning.as_usize() => Colour::Yellow.normal(), Level::Error.as_usize() => Colour::Red.normal(), Level::Critical.as_usize() => Colour::Purple.normal(), }; /// ANSI terminal style for the prefix (timestamp etc.) of a fine log message. static ref TTY_FINE_PREFIX_STYLE: Style = Style::new().dimmed(); } #[cfg(test)] mod tests { use slog::FilterLevel; use super::{DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL, NEGATIVE_VERBOSITY_LEVELS, POSITIVE_VERBOSITY_LEVELS}; /// Check that default logging level is defined consistently. #[test] fn default_level() { let level = DEFAULT_LEVEL.as_usize(); let filter_level = DEFAULT_FILTER_LEVEL.as_usize(); assert_eq!(level, filter_level, "Default logging level is defined inconsistently: Level::{:?} vs. FilterLevel::{:?}", DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL); } #[test] fn verbosity_levels()
}
{ assert_eq!(NEGATIVE_VERBOSITY_LEVELS[0], POSITIVE_VERBOSITY_LEVELS[0]); assert!(NEGATIVE_VERBOSITY_LEVELS.contains(&FilterLevel::Off), "Verbosity levels don't allow to turn logging off completely"); }
identifier_body
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; use log::SetLoggerError; use slog::{self, DrainExt, FilterLevel, Level}; use slog_envlogger::LogBuilder; use slog_stdlog; use slog_stream; use time; // Default logging level defined using the two enums used by slog. // Both values must correspond to the same level. (This is checked by a test). const DEFAULT_LEVEL: Level = Level::Info; const DEFAULT_FILTER_LEVEL: FilterLevel = FilterLevel::Info; // Arrays of log levels, indexed by verbosity. const POSITIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Debug, FilterLevel::Trace, ]; const NEGATIVE_VERBOSITY_LEVELS: &'static [FilterLevel] = &[ DEFAULT_FILTER_LEVEL, FilterLevel::Warning, FilterLevel::Error, FilterLevel::Critical, FilterLevel::Off, ]; /// Initialize logging with given verbosity. /// The verbosity value has the same meaning as in args::Options::verbosity. pub fn init(verbosity: isize) -> Result<(), SetLoggerError> { let istty = cfg!(unix) && isatty::stderr_isatty(); let stderr = slog_stream::stream(io::stderr(), LogFormat{tty: istty}); // Determine the log filtering level based on verbosity. // If the argument is excessive, log that but clamp to the highest/lowest log level. let mut verbosity = verbosity; let mut excessive = false; let level = if verbosity >= 0 { if verbosity >= POSITIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = POSITIVE_VERBOSITY_LEVELS.len() as isize - 1; } POSITIVE_VERBOSITY_LEVELS[verbosity as usize] } else { verbosity = -verbosity; if verbosity >= NEGATIVE_VERBOSITY_LEVELS.len() as isize { excessive = true; verbosity = NEGATIVE_VERBOSITY_LEVELS.len() as isize - 1; } NEGATIVE_VERBOSITY_LEVELS[verbosity as usize] }; // Include universal logger options, like the level. let mut builder = LogBuilder::new(stderr); builder = builder.filter(None, level); // Make some of the libraries less chatty. builder = builder .filter(Some("html5ever"), FilterLevel::Info) .filter(Some("hyper"), FilterLevel::Info); // Include any additional config from environmental variables. // This will override the options above if necessary, // so e.g. it is still possible to get full debug output from hyper. if let Ok(ref conf) = env::var("RUST_LOG") { builder = builder.parse(conf); } // Initialize the logger, possibly logging the excessive verbosity option. // TODO: migrate off of `log` macro to slog completely, // so that slog_scope is used to set up the application's logger // and slog_stdlog is only for the libraries like hyper that use `log` macros let env_logger_drain = builder.build(); let logger = slog::Logger::root(env_logger_drain.fuse(), o!()); try!(slog_stdlog::set_logger(logger)); if excessive { warn!("-v/-q flag passed too many times, logging level {:?} assumed", level); } Ok(()) } // Log formatting /// Token type that's only uses to tell slog-stream how to format our log entries. struct LogFormat { pub tty: bool, } impl slog_stream::Format for LogFormat { /// Format a single log Record and write it to given output. fn format(&self, output: &mut io::Write, record: &slog::Record, _logger_kvp: &slog::OwnedKeyValueList) -> io::Result<()> { // Format the higher level (more fine-grained) messages with greater detail, // as they are only visible when user explicitly enables verbose logging. let msg = if record.level() > DEFAULT_LEVEL { let logtime = format_log_time(); let level: String = { let first_char = record.level().as_str().chars().next().unwrap(); first_char.to_uppercase().collect() }; let module = { let module = record.module(); match module.find("::") { Some(idx) => Cow::Borrowed(&module[idx + 2..]), None => "main".into(), } }; // Dim the prefix (everything that's not a message) if we're outputting to a TTY. let prefix_style = if self.tty { *TTY_FINE_PREFIX_STYLE } else { Style::default() }; let prefix = format!("{}{} {}#{}]", level, logtime, module, record.line()); format!("{} {}\n", prefix_style.paint(prefix), record.msg()) } else { // Colorize the level label if we're outputting to a TTY. let level: Cow<str> = if self.tty { let style = TTY_LEVEL_STYLES.get(&record.level().as_usize()) .cloned() .unwrap_or_else(Style::default); format!("{}", style.paint(record.level().as_str())).into() } else { record.level().as_str().into() }; format!("{}: {}\n", level, record.msg()) }; try!(output.write_all(msg.as_bytes())); Ok(()) } } /// Format the timestamp part of a detailed log entry. fn format_log_time() -> String { let utc_now = time::now().to_utc(); let mut logtime = format!("{}", utc_now.rfc3339()); // E.g.: 2012-02-22T14:53:18Z // Insert millisecond count before the Z. let millis = utc_now.tm_nsec / NANOS_IN_MILLISEC; logtime.pop(); format!("{}.{:04}Z", logtime, millis) } const NANOS_IN_MILLISEC: i32 = 1000000;
Level::Info.as_usize() => Colour::Green.normal(), Level::Warning.as_usize() => Colour::Yellow.normal(), Level::Error.as_usize() => Colour::Red.normal(), Level::Critical.as_usize() => Colour::Purple.normal(), }; /// ANSI terminal style for the prefix (timestamp etc.) of a fine log message. static ref TTY_FINE_PREFIX_STYLE: Style = Style::new().dimmed(); } #[cfg(test)] mod tests { use slog::FilterLevel; use super::{DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL, NEGATIVE_VERBOSITY_LEVELS, POSITIVE_VERBOSITY_LEVELS}; /// Check that default logging level is defined consistently. #[test] fn default_level() { let level = DEFAULT_LEVEL.as_usize(); let filter_level = DEFAULT_FILTER_LEVEL.as_usize(); assert_eq!(level, filter_level, "Default logging level is defined inconsistently: Level::{:?} vs. FilterLevel::{:?}", DEFAULT_LEVEL, DEFAULT_FILTER_LEVEL); } #[test] fn verbosity_levels() { assert_eq!(NEGATIVE_VERBOSITY_LEVELS[0], POSITIVE_VERBOSITY_LEVELS[0]); assert!(NEGATIVE_VERBOSITY_LEVELS.contains(&FilterLevel::Off), "Verbosity levels don't allow to turn logging off completely"); } }
lazy_static! { /// Map of log levels to their ANSI terminal styles. // (Level doesn't implement Hash so it has to be usize). static ref TTY_LEVEL_STYLES: HashMap<usize, Style> = hashmap!{
random_line_split
kvstore.rs
//! test was move from base (it could not compile in base since its trait just change //! (bidirectional dependency)) //! TODO seems pretty useless : remove?? use keyval::KeyVal; use node::{Node,NodeID}; use peer::{Peer,Shadow}; use std::cmp::Eq; use std::cmp::PartialEq; use keyval::{Attachment,SettableAttachment}; use rustc_serialize::{Encodable, Encoder, Decoder}; // Testing only nodeK, with key different from id #[derive(RustcDecodable,RustcEncodable,Debug,Clone)] struct NodeK2(Node,String); impl Eq for NodeK2 {} impl PartialEq<NodeK2> for NodeK2 { fn eq(&self, other: &NodeK2) -> bool { other.0 == self.0 && other.1 == self.1 } } impl KeyVal for NodeK2 { type Key = String; fn get_key(&self) -> NodeID { self.1.clone() } /* fn get_key_ref<'a>(&'a self) -> &'a NodeID { &self.1 }*/ noattachment!(); } impl SettableAttachment for NodeK2 { } impl Peer for NodeK2 { type Address = <Node as Peer>::Address; type Shadow = <Node as Peer>::Shadow; #[inline] fn get_address(&self) -> &<Node as Peer>::Address { self.0.get_address() } #[inline] fn get_shadower (&self, write : bool) -> Self::Shadow { self.0.get_shadower(write) } fn
(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_auth_mode() } fn default_message_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_message_mode() } fn default_header_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_header_mode() } }
default_auth_mode
identifier_name
kvstore.rs
//! test was move from base (it could not compile in base since its trait just change //! (bidirectional dependency)) //! TODO seems pretty useless : remove?? use keyval::KeyVal; use node::{Node,NodeID}; use peer::{Peer,Shadow}; use std::cmp::Eq; use std::cmp::PartialEq;
use rustc_serialize::{Encodable, Encoder, Decoder}; // Testing only nodeK, with key different from id #[derive(RustcDecodable,RustcEncodable,Debug,Clone)] struct NodeK2(Node,String); impl Eq for NodeK2 {} impl PartialEq<NodeK2> for NodeK2 { fn eq(&self, other: &NodeK2) -> bool { other.0 == self.0 && other.1 == self.1 } } impl KeyVal for NodeK2 { type Key = String; fn get_key(&self) -> NodeID { self.1.clone() } /* fn get_key_ref<'a>(&'a self) -> &'a NodeID { &self.1 }*/ noattachment!(); } impl SettableAttachment for NodeK2 { } impl Peer for NodeK2 { type Address = <Node as Peer>::Address; type Shadow = <Node as Peer>::Shadow; #[inline] fn get_address(&self) -> &<Node as Peer>::Address { self.0.get_address() } #[inline] fn get_shadower (&self, write : bool) -> Self::Shadow { self.0.get_shadower(write) } fn default_auth_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_auth_mode() } fn default_message_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_message_mode() } fn default_header_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_header_mode() } }
use keyval::{Attachment,SettableAttachment};
random_line_split
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera; use camera::Camera_Movement::*; use cgmath::{Matrix4, vec3, Deg, perspective, Point3}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 1280; const SCR_HEIGHT: u32 = 720; pub fn main_5_1() { let mut blinn = false; let mut blinnKeyPressed = false; let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and last frame let mut lastFrame: f32 = 0.0; // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_framebuffer_size_polling(true); window.set_cursor_pos_polling(true); window.set_scroll_polling(true); // tell GLFW to capture our mouse window.set_cursor_mode(glfw::CursorMode::Disabled); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (shader, planeVBO, planeVAO, floorTexture) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // build and compile shaders // ------------------------------------ let shader = Shader::new( "src/_5_advanced_lighting/shaders/1.advanced_lighting.vs", "src/_5_advanced_lighting/shaders/1.advanced_lighting.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let planeVertices: [f32; 48] = [ // positions // normals // texcoords 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 10.0, 10.0 ]; // plane VAO let (mut planeVAO, mut planeVBO) = (0, 0); gl::GenVertexArrays(1, &mut planeVAO); gl::GenBuffers(1, &mut planeVBO); gl::BindVertexArray(planeVAO); gl::BindBuffer(gl::ARRAY_BUFFER, planeVBO); gl::BufferData(gl::ARRAY_BUFFER, (planeVertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &planeVertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::EnableVertexAttribArray(0); let stride = 8 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(1); gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(2); gl::VertexAttribPointer(2, 2, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const c_void); gl::BindVertexArray(0); // load textures // ------------- let floorTexture = loadTexture("resources/textures/wood.png"); // shader configuration // -------------------- shader.useProgram(); shader.setInt(c_str!("texture1"), 0); (shader, planeVBO, planeVAO, floorTexture) }; // lighting info // ------------- let lightPos = vec3(0.0, 0.0, 0.0); // render loop // ----------- while!window.should_close() { // per-frame time logic // -------------------- let currentFrame = glfw.get_time() as f32; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // events // ----- process_events(&events, &mut firstMouse, &mut lastX, &mut lastY, &mut camera); // input // ----- processInput(&mut window, deltaTime, &mut camera, &mut blinn, &mut blinnKeyPressed); // render // ------ unsafe { gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // draw objects shader.useProgram(); let projection: Matrix4<f32> = perspective(Deg(camera.Zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); let view = camera.GetViewMatrix(); shader.setMat4(c_str!("projection"), &projection); shader.setMat4(c_str!("view"), &view); // set light uniforms shader.setVector3(c_str!("viewPos"), &camera.Position.to_vec()); shader.setVector3(c_str!("lightPos"), &lightPos); shader.setInt(c_str!("blinn"), blinn as i32); // floor gl::BindVertexArray(planeVAO); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, floorTexture); gl::DrawArrays(gl::TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &planeVAO); gl::DeleteBuffers(1, &planeVBO); } } // NOTE: not the same version as in common.rs pub fn processInput(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::Press { camera.ProcessKeyboard(FORWARD, deltaTime); } if window.get_key(Key::S) == Action::Press { camera.ProcessKeyboard(BACKWARD, deltaTime); } if window.get_key(Key::A) == Action::Press { camera.ProcessKeyboard(LEFT, deltaTime); } if window.get_key(Key::D) == Action::Press { camera.ProcessKeyboard(RIGHT, deltaTime); } if window.get_key(Key::B) == Action::Press &&!(*blinnKeyPressed) { *blinn =!(*blinn); *blinnKeyPressed = true; println!("{}", if *blinn { "Blinn-Phong" } else { "Phong" }) } if window.get_key(Key::B) == Action::Release
}
{ *blinnKeyPressed = false; }
conditional_block
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera; use camera::Camera_Movement::*; use cgmath::{Matrix4, vec3, Deg, perspective, Point3}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 1280; const SCR_HEIGHT: u32 = 720; pub fn main_5_1()
glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_framebuffer_size_polling(true); window.set_cursor_pos_polling(true); window.set_scroll_polling(true); // tell GLFW to capture our mouse window.set_cursor_mode(glfw::CursorMode::Disabled); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (shader, planeVBO, planeVAO, floorTexture) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // build and compile shaders // ------------------------------------ let shader = Shader::new( "src/_5_advanced_lighting/shaders/1.advanced_lighting.vs", "src/_5_advanced_lighting/shaders/1.advanced_lighting.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let planeVertices: [f32; 48] = [ // positions // normals // texcoords 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 10.0, 10.0 ]; // plane VAO let (mut planeVAO, mut planeVBO) = (0, 0); gl::GenVertexArrays(1, &mut planeVAO); gl::GenBuffers(1, &mut planeVBO); gl::BindVertexArray(planeVAO); gl::BindBuffer(gl::ARRAY_BUFFER, planeVBO); gl::BufferData(gl::ARRAY_BUFFER, (planeVertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &planeVertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::EnableVertexAttribArray(0); let stride = 8 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(1); gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(2); gl::VertexAttribPointer(2, 2, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const c_void); gl::BindVertexArray(0); // load textures // ------------- let floorTexture = loadTexture("resources/textures/wood.png"); // shader configuration // -------------------- shader.useProgram(); shader.setInt(c_str!("texture1"), 0); (shader, planeVBO, planeVAO, floorTexture) }; // lighting info // ------------- let lightPos = vec3(0.0, 0.0, 0.0); // render loop // ----------- while!window.should_close() { // per-frame time logic // -------------------- let currentFrame = glfw.get_time() as f32; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // events // ----- process_events(&events, &mut firstMouse, &mut lastX, &mut lastY, &mut camera); // input // ----- processInput(&mut window, deltaTime, &mut camera, &mut blinn, &mut blinnKeyPressed); // render // ------ unsafe { gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // draw objects shader.useProgram(); let projection: Matrix4<f32> = perspective(Deg(camera.Zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); let view = camera.GetViewMatrix(); shader.setMat4(c_str!("projection"), &projection); shader.setMat4(c_str!("view"), &view); // set light uniforms shader.setVector3(c_str!("viewPos"), &camera.Position.to_vec()); shader.setVector3(c_str!("lightPos"), &lightPos); shader.setInt(c_str!("blinn"), blinn as i32); // floor gl::BindVertexArray(planeVAO); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, floorTexture); gl::DrawArrays(gl::TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &planeVAO); gl::DeleteBuffers(1, &planeVBO); } } // NOTE: not the same version as in common.rs pub fn processInput(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::Press { camera.ProcessKeyboard(FORWARD, deltaTime); } if window.get_key(Key::S) == Action::Press { camera.ProcessKeyboard(BACKWARD, deltaTime); } if window.get_key(Key::A) == Action::Press { camera.ProcessKeyboard(LEFT, deltaTime); } if window.get_key(Key::D) == Action::Press { camera.ProcessKeyboard(RIGHT, deltaTime); } if window.get_key(Key::B) == Action::Press &&!(*blinnKeyPressed) { *blinn =!(*blinn); *blinnKeyPressed = true; println!("{}", if *blinn { "Blinn-Phong" } else { "Phong" }) } if window.get_key(Key::B) == Action::Release { *blinnKeyPressed = false; } }
{ let mut blinn = false; let mut blinnKeyPressed = false; let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and last frame let mut lastFrame: f32 = 0.0; // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
identifier_body
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera; use camera::Camera_Movement::*; use cgmath::{Matrix4, vec3, Deg, perspective, Point3}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 1280; const SCR_HEIGHT: u32 = 720; pub fn main_5_1() { let mut blinn = false; let mut blinnKeyPressed = false; let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and last frame let mut lastFrame: f32 = 0.0; // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_framebuffer_size_polling(true); window.set_cursor_pos_polling(true); window.set_scroll_polling(true); // tell GLFW to capture our mouse window.set_cursor_mode(glfw::CursorMode::Disabled); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (shader, planeVBO, planeVAO, floorTexture) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // build and compile shaders // ------------------------------------ let shader = Shader::new( "src/_5_advanced_lighting/shaders/1.advanced_lighting.vs", "src/_5_advanced_lighting/shaders/1.advanced_lighting.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let planeVertices: [f32; 48] = [ // positions // normals // texcoords 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 10.0, 10.0 ]; // plane VAO let (mut planeVAO, mut planeVBO) = (0, 0); gl::GenVertexArrays(1, &mut planeVAO); gl::GenBuffers(1, &mut planeVBO); gl::BindVertexArray(planeVAO); gl::BindBuffer(gl::ARRAY_BUFFER, planeVBO); gl::BufferData(gl::ARRAY_BUFFER, (planeVertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &planeVertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::EnableVertexAttribArray(0); let stride = 8 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(1); gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(2); gl::VertexAttribPointer(2, 2, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const c_void); gl::BindVertexArray(0); // load textures // ------------- let floorTexture = loadTexture("resources/textures/wood.png"); // shader configuration // -------------------- shader.useProgram(); shader.setInt(c_str!("texture1"), 0); (shader, planeVBO, planeVAO, floorTexture) }; // lighting info // -------------
while!window.should_close() { // per-frame time logic // -------------------- let currentFrame = glfw.get_time() as f32; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // events // ----- process_events(&events, &mut firstMouse, &mut lastX, &mut lastY, &mut camera); // input // ----- processInput(&mut window, deltaTime, &mut camera, &mut blinn, &mut blinnKeyPressed); // render // ------ unsafe { gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // draw objects shader.useProgram(); let projection: Matrix4<f32> = perspective(Deg(camera.Zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); let view = camera.GetViewMatrix(); shader.setMat4(c_str!("projection"), &projection); shader.setMat4(c_str!("view"), &view); // set light uniforms shader.setVector3(c_str!("viewPos"), &camera.Position.to_vec()); shader.setVector3(c_str!("lightPos"), &lightPos); shader.setInt(c_str!("blinn"), blinn as i32); // floor gl::BindVertexArray(planeVAO); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, floorTexture); gl::DrawArrays(gl::TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &planeVAO); gl::DeleteBuffers(1, &planeVBO); } } // NOTE: not the same version as in common.rs pub fn processInput(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::Press { camera.ProcessKeyboard(FORWARD, deltaTime); } if window.get_key(Key::S) == Action::Press { camera.ProcessKeyboard(BACKWARD, deltaTime); } if window.get_key(Key::A) == Action::Press { camera.ProcessKeyboard(LEFT, deltaTime); } if window.get_key(Key::D) == Action::Press { camera.ProcessKeyboard(RIGHT, deltaTime); } if window.get_key(Key::B) == Action::Press &&!(*blinnKeyPressed) { *blinn =!(*blinn); *blinnKeyPressed = true; println!("{}", if *blinn { "Blinn-Phong" } else { "Phong" }) } if window.get_key(Key::B) == Action::Release { *blinnKeyPressed = false; } }
let lightPos = vec3(0.0, 0.0, 0.0); // render loop // -----------
random_line_split
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera; use camera::Camera_Movement::*; use cgmath::{Matrix4, vec3, Deg, perspective, Point3}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 1280; const SCR_HEIGHT: u32 = 720; pub fn main_5_1() { let mut blinn = false; let mut blinnKeyPressed = false; let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and last frame let mut lastFrame: f32 = 0.0; // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); window.set_framebuffer_size_polling(true); window.set_cursor_pos_polling(true); window.set_scroll_polling(true); // tell GLFW to capture our mouse window.set_cursor_mode(glfw::CursorMode::Disabled); // gl: load all OpenGL function pointers // --------------------------------------- gl::load_with(|symbol| window.get_proc_address(symbol) as *const _); let (shader, planeVBO, planeVAO, floorTexture) = unsafe { // configure global opengl state // ----------------------------- gl::Enable(gl::DEPTH_TEST); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // build and compile shaders // ------------------------------------ let shader = Shader::new( "src/_5_advanced_lighting/shaders/1.advanced_lighting.vs", "src/_5_advanced_lighting/shaders/1.advanced_lighting.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ let planeVertices: [f32; 48] = [ // positions // normals // texcoords 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 0.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, 10.0, 0.0, 1.0, 0.0, 10.0, 0.0, -10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 0.0, 10.0, 10.0, -0.5, -10.0, 0.0, 1.0, 0.0, 10.0, 10.0 ]; // plane VAO let (mut planeVAO, mut planeVBO) = (0, 0); gl::GenVertexArrays(1, &mut planeVAO); gl::GenBuffers(1, &mut planeVBO); gl::BindVertexArray(planeVAO); gl::BindBuffer(gl::ARRAY_BUFFER, planeVBO); gl::BufferData(gl::ARRAY_BUFFER, (planeVertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &planeVertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); gl::EnableVertexAttribArray(0); let stride = 8 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(1); gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(2); gl::VertexAttribPointer(2, 2, gl::FLOAT, gl::FALSE, stride, (6 * mem::size_of::<GLfloat>()) as *const c_void); gl::BindVertexArray(0); // load textures // ------------- let floorTexture = loadTexture("resources/textures/wood.png"); // shader configuration // -------------------- shader.useProgram(); shader.setInt(c_str!("texture1"), 0); (shader, planeVBO, planeVAO, floorTexture) }; // lighting info // ------------- let lightPos = vec3(0.0, 0.0, 0.0); // render loop // ----------- while!window.should_close() { // per-frame time logic // -------------------- let currentFrame = glfw.get_time() as f32; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // events // ----- process_events(&events, &mut firstMouse, &mut lastX, &mut lastY, &mut camera); // input // ----- processInput(&mut window, deltaTime, &mut camera, &mut blinn, &mut blinnKeyPressed); // render // ------ unsafe { gl::ClearColor(0.1, 0.1, 0.1, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); // draw objects shader.useProgram(); let projection: Matrix4<f32> = perspective(Deg(camera.Zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0); let view = camera.GetViewMatrix(); shader.setMat4(c_str!("projection"), &projection); shader.setMat4(c_str!("view"), &view); // set light uniforms shader.setVector3(c_str!("viewPos"), &camera.Position.to_vec()); shader.setVector3(c_str!("lightPos"), &lightPos); shader.setInt(c_str!("blinn"), blinn as i32); // floor gl::BindVertexArray(planeVAO); gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, floorTexture); gl::DrawArrays(gl::TRIANGLES, 0, 6); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- window.swap_buffers(); glfw.poll_events(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ unsafe { gl::DeleteVertexArrays(1, &planeVAO); gl::DeleteBuffers(1, &planeVBO); } } // NOTE: not the same version as in common.rs pub fn
(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::Press { camera.ProcessKeyboard(FORWARD, deltaTime); } if window.get_key(Key::S) == Action::Press { camera.ProcessKeyboard(BACKWARD, deltaTime); } if window.get_key(Key::A) == Action::Press { camera.ProcessKeyboard(LEFT, deltaTime); } if window.get_key(Key::D) == Action::Press { camera.ProcessKeyboard(RIGHT, deltaTime); } if window.get_key(Key::B) == Action::Press &&!(*blinnKeyPressed) { *blinn =!(*blinn); *blinnKeyPressed = true; println!("{}", if *blinn { "Blinn-Phong" } else { "Phong" }) } if window.get_key(Key::B) == Action::Release { *blinnKeyPressed = false; } }
processInput
identifier_name
unpin_chat_message.rs
use crate::requests::*; use crate::types::*; ///Use this method to unpin a message in a supergroup or a channel. /// The bot must be an administrator in the chat for this to work /// and must have the ‘can_pin_messages’ admin right in the /// supergroup or ‘can_edit_messages’ admin right in the channel. #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] #[must_use = "requests do nothing unless sent"] pub struct UnpinCha
hat_id: ChatRef, } impl Request for UnpinChatMessage { type Type = JsonRequestType<Self>; type Response = JsonTrueToUnitResponse; fn serialize(&self) -> Result<HttpRequest, Error> { Self::Type::serialize(RequestUrl::method("unpinChatMessage"), self) } } impl UnpinChatMessage { fn new<C>(chat: C) -> Self where C: ToChatRef, { Self { chat_id: chat.to_chat_ref(), } } } pub trait CanUnpinMessage { fn unpin_message(&self) -> UnpinChatMessage; } impl<C> CanUnpinMessage for C where C: ToChatRef, { fn unpin_message(&self) -> UnpinChatMessage { UnpinChatMessage::new(self) } }
tMessage { c
identifier_name
unpin_chat_message.rs
use crate::requests::*; use crate::types::*; ///Use this method to unpin a message in a supergroup or a channel. /// The bot must be an administrator in the chat for this to work /// and must have the ‘can_pin_messages’ admin right in the /// supergroup or ‘can_edit_messages’ admin right in the channel. #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] #[must_use = "requests do nothing unless sent"] pub struct UnpinChatMessage { chat_id: ChatRef, } impl Request for UnpinChatMessage { type Type = JsonRequestType<Self>; type Response = JsonTrueToUnitResponse; fn serialize(&self) -> Result<HttpRequest, Error> { Self::Type::serialize(RequestUrl::method("unpinChatMessage"), self) } } impl UnpinChatMessage { fn new<C>(chat: C) -> Self where C: ToChatRef, { Self { chat_id: chat.to_chat_ref(), } } } pub trait CanUnpinMessage { fn unpin_message(&self) -> UnpinChatMessage; } impl<C> CanUnpinMessage for C where C: ToChatRef, { fn unpin_message(&self) -> UnpinChatMessage { UnpinChatMessage::new(self)
}
}
random_line_split
puntata.rs
use crate::die::Die; use std::{collections::HashSet, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Puntata { value: Die, count: i32, } impl Puntata { pub fn new(count: i32, value: i32) -> Self { Puntata { value: Die::new(value), count, } } pub fn new_lama(count: i32) -> Self { Puntata { value: Die::new_lama(), count, } } pub fn get_value(self) -> i32 { self.value.get_value() } pub fn get_count(self) -> i32 { self.count } pub fn is_lama(self) -> bool { self.value.is_lama() } pub fn with_count(self, count: i32) -> Self { Puntata { value: Die::new(self.value.get_value()), count, } } } impl fmt::Display for Puntata { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.is_lama() { write!(fmt, "Puntata di {} Lama", self.count) } else { write!(fmt, "Puntata di {} {}", self.count, self.value.get_value()) } } } pub fn least_gt_puntate(p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut puntate = vec![]; if!p.is_lama() { for i in (p.value.get_value() + 1)..7 { puntate.push(Puntata::new(p.count, i)); } for i in 2..7 { puntate.push(Puntata::new(p.count + 1, i)); } puntate.push(Puntata::new_lama((p.count + 1) / 2)); } else { puntate.push(Puntata::new_lama(p.count + 1)); for i in 2..7 { puntate.push(Puntata::new(p.count * 2 + 1, i)); } } if is_palifico { puntate.retain(|pv| pv.value == p.value) } puntate } pub fn
(total_dices: i32, p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut v = (p.count..total_dices) .flat_map(|v| { let px = p.with_count(v); least_gt_puntate(px, is_palifico) }) .collect::<HashSet<_>>(); if!is_palifico || p.is_lama() { for i in p.count..=total_dices { v.insert(Puntata::new_lama(i)); } } v.remove(&p); v.insert(p); v.into_iter().collect() }
all_gt_puntate
identifier_name
puntata.rs
use crate::die::Die; use std::{collections::HashSet, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Puntata { value: Die, count: i32, } impl Puntata { pub fn new(count: i32, value: i32) -> Self { Puntata { value: Die::new(value), count, } } pub fn new_lama(count: i32) -> Self { Puntata { value: Die::new_lama(), count, } } pub fn get_value(self) -> i32 { self.value.get_value() } pub fn get_count(self) -> i32 { self.count } pub fn is_lama(self) -> bool { self.value.is_lama() } pub fn with_count(self, count: i32) -> Self { Puntata { value: Die::new(self.value.get_value()), count, } } } impl fmt::Display for Puntata { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.is_lama() { write!(fmt, "Puntata di {} Lama", self.count) } else { write!(fmt, "Puntata di {} {}", self.count, self.value.get_value()) } } } pub fn least_gt_puntate(p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut puntate = vec![]; if!p.is_lama() { for i in (p.value.get_value() + 1)..7 { puntate.push(Puntata::new(p.count, i)); } for i in 2..7 { puntate.push(Puntata::new(p.count + 1, i)); } puntate.push(Puntata::new_lama((p.count + 1) / 2)); } else { puntate.push(Puntata::new_lama(p.count + 1)); for i in 2..7 { puntate.push(Puntata::new(p.count * 2 + 1, i)); } } if is_palifico { puntate.retain(|pv| pv.value == p.value) } puntate } pub fn all_gt_puntate(total_dices: i32, p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut v = (p.count..total_dices) .flat_map(|v| { let px = p.with_count(v); least_gt_puntate(px, is_palifico) }) .collect::<HashSet<_>>(); if!is_palifico || p.is_lama() { for i in p.count..=total_dices { v.insert(Puntata::new_lama(i)); } } v.remove(&p);
v.into_iter().collect() }
v.insert(p);
random_line_split
puntata.rs
use crate::die::Die; use std::{collections::HashSet, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Puntata { value: Die, count: i32, } impl Puntata { pub fn new(count: i32, value: i32) -> Self { Puntata { value: Die::new(value), count, } } pub fn new_lama(count: i32) -> Self { Puntata { value: Die::new_lama(), count, } } pub fn get_value(self) -> i32 { self.value.get_value() } pub fn get_count(self) -> i32 { self.count } pub fn is_lama(self) -> bool { self.value.is_lama() } pub fn with_count(self, count: i32) -> Self { Puntata { value: Die::new(self.value.get_value()), count, } } } impl fmt::Display for Puntata { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.is_lama() { write!(fmt, "Puntata di {} Lama", self.count) } else { write!(fmt, "Puntata di {} {}", self.count, self.value.get_value()) } } } pub fn least_gt_puntate(p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut puntate = vec![]; if!p.is_lama()
else { puntate.push(Puntata::new_lama(p.count + 1)); for i in 2..7 { puntate.push(Puntata::new(p.count * 2 + 1, i)); } } if is_palifico { puntate.retain(|pv| pv.value == p.value) } puntate } pub fn all_gt_puntate(total_dices: i32, p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut v = (p.count..total_dices) .flat_map(|v| { let px = p.with_count(v); least_gt_puntate(px, is_palifico) }) .collect::<HashSet<_>>(); if!is_palifico || p.is_lama() { for i in p.count..=total_dices { v.insert(Puntata::new_lama(i)); } } v.remove(&p); v.insert(p); v.into_iter().collect() }
{ for i in (p.value.get_value() + 1)..7 { puntate.push(Puntata::new(p.count, i)); } for i in 2..7 { puntate.push(Puntata::new(p.count + 1, i)); } puntate.push(Puntata::new_lama((p.count + 1) / 2)); }
conditional_block
puntata.rs
use crate::die::Die; use std::{collections::HashSet, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct Puntata { value: Die, count: i32, } impl Puntata { pub fn new(count: i32, value: i32) -> Self { Puntata { value: Die::new(value), count, } } pub fn new_lama(count: i32) -> Self
pub fn get_value(self) -> i32 { self.value.get_value() } pub fn get_count(self) -> i32 { self.count } pub fn is_lama(self) -> bool { self.value.is_lama() } pub fn with_count(self, count: i32) -> Self { Puntata { value: Die::new(self.value.get_value()), count, } } } impl fmt::Display for Puntata { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.is_lama() { write!(fmt, "Puntata di {} Lama", self.count) } else { write!(fmt, "Puntata di {} {}", self.count, self.value.get_value()) } } } pub fn least_gt_puntate(p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut puntate = vec![]; if!p.is_lama() { for i in (p.value.get_value() + 1)..7 { puntate.push(Puntata::new(p.count, i)); } for i in 2..7 { puntate.push(Puntata::new(p.count + 1, i)); } puntate.push(Puntata::new_lama((p.count + 1) / 2)); } else { puntate.push(Puntata::new_lama(p.count + 1)); for i in 2..7 { puntate.push(Puntata::new(p.count * 2 + 1, i)); } } if is_palifico { puntate.retain(|pv| pv.value == p.value) } puntate } pub fn all_gt_puntate(total_dices: i32, p: Puntata, is_palifico: bool) -> Vec<Puntata> { let mut v = (p.count..total_dices) .flat_map(|v| { let px = p.with_count(v); least_gt_puntate(px, is_palifico) }) .collect::<HashSet<_>>(); if!is_palifico || p.is_lama() { for i in p.count..=total_dices { v.insert(Puntata::new_lama(i)); } } v.remove(&p); v.insert(p); v.into_iter().collect() }
{ Puntata { value: Die::new_lama(), count, } }
identifier_body
htmldataelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLDataElement { htmlelement: HTMLElement } impl HTMLDataElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLDataElement { HTMLDataElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataElement>
}
{ let element = HTMLDataElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataElementBinding::Wrap) }
identifier_body
htmldataelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLDataElement { htmlelement: HTMLElement } impl HTMLDataElement { fn
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLDataElement { HTMLDataElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataElement> { let element = HTMLDataElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataElementBinding::Wrap) } }
new_inherited
identifier_name
htmldataelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use util::str::DOMString; #[dom_struct]
htmlelement: HTMLElement } impl HTMLDataElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLDataElement { HTMLDataElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataElement> { let element = HTMLDataElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataElementBinding::Wrap) } }
pub struct HTMLDataElement {
random_line_split
transport.rs
use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr}; use std::time::Duration; use std::u32; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, Bytes, BytesMut, IntoBuf}; use futures::{Async, Future, Poll}; use prost::{decode_length_delimiter, length_delimiter_len, Message}; use tokio::net::{ConnectFuture, TcpStream}; use pb::rpc::{ErrorStatusPb, RemoteMethodPb, RequestHeader, ResponseHeader}; use Error; use Options; use RequestBody; use RpcError; use RpcErrorCode; const INITIAL_CAPACITY: usize = 8 * 1024; const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY; pub type TransportResponse = (Bytes, Vec<BytesMut>); /// `Transport` handles sending and receiving raw KRPC messages to a TCP stream. /// /// The transport manages send and receive buffers, encoding and decoding of messages, message /// framing, headers, and RPC errors. /// /// The transport wraps a single TCP connection. When the TCP connection is shutdown or fails, the /// transport should no longer be used. TCP connection shutdown is indicated by a fatal error being /// returned from `poll_ready()`, `send()`, or `poll()`. pub(crate) struct Transport { addr: SocketAddr, options: Options, stream: TcpStream, send_buf: BytesMut, recv_buf: BytesMut, request_header: RequestHeader, response_header: ResponseHeader, } impl Transport { /// Returns a future which will yield a new transport. pub fn connect(addr: SocketAddr, options: Options) -> TransportNew { let connect = TcpStream::connect(&addr); TransportNew { addr, options, connect, } } /// Returns `true` if the transport is ready to send an RPC to the peer. /// /// An error return indicates a fatal error. pub fn poll_ready(&mut self) -> Poll<(), Error> { let result = || -> Poll<(), Error> { // If the buffer is already over 8KiB, then attempt to flush it. If after flushing it's // *still* over 8KiB, then apply backpressure (reject the send). if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { self.poll_flush()?; if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { return Ok(Async::NotReady); } } Ok(Async::Ready(())) }(); if result.is_err() { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Sends an RPC to the peer. /// /// This method does not provide backpressure, so callers should always check that `poll_ready` /// indicates that there is send capacity available. /// /// If a fatal error is returned the transport is shut down. If a non-fatal error is returned, /// the RPC should be failed. pub fn send( &mut self, call_id: i32, service: &str, method: &str, required_feature_flags: &[u32], body: &RequestBody, timeout: Option<Duration>, ) -> Result<(), Error> { let result = || -> Result<(), Error> { // Set the header fields. self.request_header.call_id = call_id; { let remote_method = self .request_header .remote_method .get_or_insert(RemoteMethodPb::default()); remote_method.clear(); remote_method.service_name.push_str(service); remote_method.method_name.push_str(method); } if let Some(timeout) = timeout { self.request_header.timeout_millis = Some(duration_to_ms(timeout)); } self.request_header.required_feature_flags.clear(); self.request_header .required_feature_flags .extend_from_slice(required_feature_flags); let header_len = Message::encoded_len(&self.request_header); let body_len = body.encoded_len(); let len = length_delimiter_len(header_len) + length_delimiter_len(body_len) + header_len + body_len; if len > self.options.max_message_length as usize { return Err(RpcError { code: RpcErrorCode::ErrorInvalidRequest, message: format!( "RPC request exceeds maximum length ({}/{})", len, self.options.max_message_length ), unsupported_feature_flags: Vec::new(), }.into()); } self.send_buf.put_u32_be(len as u32); Message::encode_length_delimited(&self.request_header, &mut self.send_buf).unwrap(); body.encode_length_delimited(&mut self.send_buf); Ok(()) }(); if let Err(ref error) = result { if error.is_fatal() { let _ = self.stream.shutdown(Shutdown::Both); } } result } /// Attempts to receive a response from the peer. pub fn poll(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { self.poll_flush()?; self.poll_recv() } /// Attempts to read a response from the TCP stream. fn poll_recv(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { let result = || -> Poll<(i32, Result<TransportResponse, Error>), Error> { // Read, or continue reading, an RPC response message from the socket into the receive // buffer. Every RPC response is prefixed with a 4 bytes length header. if self.recv_buf.len() < 4 { let needed = 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let msg_len = BigEndian::read_u32(&self.recv_buf[..4]) as usize; if msg_len > self.options.max_message_length as usize { return Err(Error::Serialization(format!( "RPC response exceeds maximum length ({}/{})", msg_len, self.options.max_message_length ))); } if self.recv_buf.len() - 4 < msg_len { let needed = msg_len + 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let _ = self.recv_buf.split_to(4); let mut buf = self.recv_buf.split_to(msg_len); // Decode the header. let header_len = { let mut cursor = buf.clone().into_buf(); self.response_header.clear(); self.response_header.merge_length_delimited(&mut cursor)?; cursor.position() as usize }; buf.split_to(header_len); let call_id = self.response_header.call_id; if self.response_header.is_error() { let error = Error::Rpc(ErrorStatusPb::decode_length_delimited(buf)?.into()); Ok(Async::Ready((call_id, Err(error)))) } else { // KRPC inserts a len integer before the main message whose value is the length of // the main message and sidecars. This is completely useless since this can be // solved for easily using the header length and the overall length. Unfortunately // stripping this integer is not trivial, since it's variable length. In order to // know its width we are forced to read it. Who designed this crap? // // There's probably a way to solve for the width of the varint based on the // remaining length of the buffer, but it's unfortunately not as simple as just // calling length_delimiter_len since the buffer contains the varint itself. let main_message_len = decode_length_delimiter(&mut (&buf).into_buf()).unwrap(); buf.split_to(length_delimiter_len(main_message_len)); let mut sidecars = Vec::new(); let body; if self.response_header.sidecar_offsets.is_empty() { body = buf.freeze(); } else { let mut prev_offset = self.response_header.sidecar_offsets[0] as usize; body = buf.split_to(prev_offset).freeze(); for &offset in &self.response_header.sidecar_offsets[1..] { let offset = offset as usize; sidecars.push(buf.split_to(offset - prev_offset)); prev_offset = offset; } sidecars.push(buf); } Ok(Async::Ready((call_id, Ok((body, sidecars))))) } }(); let is_fatal = match result { Ok(Async::Ready((_, Err(ref error)))) => error.is_fatal(), Err(_) => true, _ => false, }; if is_fatal { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Reads at least `at_least` bytes into the receive buffer. /// /// Based on tokio-io's [`FramedRead`][1] and [`AsyncRead`][2]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/master/src/framed_read.rs#L259-L294 /// [2]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/lib.rs#L138-L157 fn poll_fill(&mut self, mut at_least: usize) -> Result<Async<()>, io::Error> { self.recv_buf.reserve(at_least); while at_least > 0 { let n = unsafe { let n = try_nb!(self.stream.read(self.recv_buf.bytes_mut())); self.recv_buf.advance_mut(n); n }; at_least = at_least.saturating_sub(n); if n == 0 { return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); } } Ok(Async::Ready(())) } /// Flushes bytes from send buffer to the stream. /// /// Based on tokio-io's [`FramedWrite`][1]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/framed_write.rs#L202-L225 /// /// An error return indicates a fatal error. fn poll_flush(&mut self) -> Result<Async<()>, io::Error> { while!self.send_buf.is_empty() { let n = try_nb!(self.stream.write(&self.send_buf)); if n == 0 { return Err(io::Error::from(io::ErrorKind::WriteZero)); } let _ = self.send_buf.split_to(n); } Ok(Async::Ready(())) } pub fn addr(&self) -> &SocketAddr { &self.addr } pub fn options(&self) -> &Options { &self.options } pub fn send_buf_len(&self) -> usize { self.send_buf.len() } pub fn recv_buf_len(&self) -> usize { self.recv_buf.len() } } /// Future returned by `Transport::connect` which will resolve to a `Transport` when the TCP stream /// is connected. pub(crate) struct TransportNew { addr: SocketAddr, options: Options, connect: ConnectFuture, } impl Future for TransportNew { type Item = Transport; type Error = io::Error; fn poll(&mut self) -> Result<Async<Transport>, io::Error> { let stream = try_ready!(self.connect.poll()); stream.set_nodelay(self.options.nodelay)?; // Write the connection header to the send buffer. let mut send_buf = BytesMut::with_capacity(INITIAL_CAPACITY); send_buf.put_slice(b"hrpc\x09\0\0"); Ok(Async::Ready(Transport { addr: self.addr, options: self.options.clone(), stream, send_buf, recv_buf: BytesMut::with_capacity(INITIAL_CAPACITY), request_header: RequestHeader::default(), response_header: ResponseHeader::default(), })) } } /// Converts a duration to milliseconds. fn
(duration: Duration) -> u32 { let millis = duration .as_secs() .saturating_mul(1000) .saturating_add(u64::from(duration.subsec_nanos()) / 1_000_000); if millis > u64::from(u32::MAX) { u32::MAX } else { millis as u32 } }
duration_to_ms
identifier_name
transport.rs
use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr}; use std::time::Duration; use std::u32; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, Bytes, BytesMut, IntoBuf}; use futures::{Async, Future, Poll}; use prost::{decode_length_delimiter, length_delimiter_len, Message}; use tokio::net::{ConnectFuture, TcpStream}; use pb::rpc::{ErrorStatusPb, RemoteMethodPb, RequestHeader, ResponseHeader}; use Error; use Options; use RequestBody; use RpcError; use RpcErrorCode; const INITIAL_CAPACITY: usize = 8 * 1024; const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY; pub type TransportResponse = (Bytes, Vec<BytesMut>); /// `Transport` handles sending and receiving raw KRPC messages to a TCP stream. /// /// The transport manages send and receive buffers, encoding and decoding of messages, message /// framing, headers, and RPC errors. /// /// The transport wraps a single TCP connection. When the TCP connection is shutdown or fails, the /// transport should no longer be used. TCP connection shutdown is indicated by a fatal error being /// returned from `poll_ready()`, `send()`, or `poll()`. pub(crate) struct Transport { addr: SocketAddr, options: Options, stream: TcpStream, send_buf: BytesMut, recv_buf: BytesMut, request_header: RequestHeader, response_header: ResponseHeader, } impl Transport { /// Returns a future which will yield a new transport. pub fn connect(addr: SocketAddr, options: Options) -> TransportNew { let connect = TcpStream::connect(&addr); TransportNew { addr, options, connect, } } /// Returns `true` if the transport is ready to send an RPC to the peer. /// /// An error return indicates a fatal error. pub fn poll_ready(&mut self) -> Poll<(), Error> { let result = || -> Poll<(), Error> { // If the buffer is already over 8KiB, then attempt to flush it. If after flushing it's // *still* over 8KiB, then apply backpressure (reject the send). if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { self.poll_flush()?; if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { return Ok(Async::NotReady); } } Ok(Async::Ready(())) }(); if result.is_err() { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Sends an RPC to the peer. /// /// This method does not provide backpressure, so callers should always check that `poll_ready` /// indicates that there is send capacity available. /// /// If a fatal error is returned the transport is shut down. If a non-fatal error is returned, /// the RPC should be failed. pub fn send( &mut self, call_id: i32, service: &str, method: &str, required_feature_flags: &[u32], body: &RequestBody, timeout: Option<Duration>, ) -> Result<(), Error> { let result = || -> Result<(), Error> { // Set the header fields. self.request_header.call_id = call_id; { let remote_method = self .request_header .remote_method .get_or_insert(RemoteMethodPb::default()); remote_method.clear(); remote_method.service_name.push_str(service); remote_method.method_name.push_str(method); } if let Some(timeout) = timeout { self.request_header.timeout_millis = Some(duration_to_ms(timeout)); } self.request_header.required_feature_flags.clear(); self.request_header .required_feature_flags .extend_from_slice(required_feature_flags); let header_len = Message::encoded_len(&self.request_header); let body_len = body.encoded_len(); let len = length_delimiter_len(header_len) + length_delimiter_len(body_len) + header_len + body_len; if len > self.options.max_message_length as usize { return Err(RpcError { code: RpcErrorCode::ErrorInvalidRequest, message: format!( "RPC request exceeds maximum length ({}/{})", len, self.options.max_message_length ), unsupported_feature_flags: Vec::new(), }.into()); } self.send_buf.put_u32_be(len as u32); Message::encode_length_delimited(&self.request_header, &mut self.send_buf).unwrap(); body.encode_length_delimited(&mut self.send_buf); Ok(()) }(); if let Err(ref error) = result { if error.is_fatal() { let _ = self.stream.shutdown(Shutdown::Both); } } result } /// Attempts to receive a response from the peer. pub fn poll(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { self.poll_flush()?; self.poll_recv() } /// Attempts to read a response from the TCP stream. fn poll_recv(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { let result = || -> Poll<(i32, Result<TransportResponse, Error>), Error> { // Read, or continue reading, an RPC response message from the socket into the receive // buffer. Every RPC response is prefixed with a 4 bytes length header. if self.recv_buf.len() < 4 { let needed = 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let msg_len = BigEndian::read_u32(&self.recv_buf[..4]) as usize; if msg_len > self.options.max_message_length as usize { return Err(Error::Serialization(format!( "RPC response exceeds maximum length ({}/{})", msg_len, self.options.max_message_length ))); } if self.recv_buf.len() - 4 < msg_len { let needed = msg_len + 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let _ = self.recv_buf.split_to(4); let mut buf = self.recv_buf.split_to(msg_len); // Decode the header. let header_len = { let mut cursor = buf.clone().into_buf(); self.response_header.clear(); self.response_header.merge_length_delimited(&mut cursor)?; cursor.position() as usize }; buf.split_to(header_len); let call_id = self.response_header.call_id; if self.response_header.is_error() { let error = Error::Rpc(ErrorStatusPb::decode_length_delimited(buf)?.into()); Ok(Async::Ready((call_id, Err(error)))) } else { // KRPC inserts a len integer before the main message whose value is the length of // the main message and sidecars. This is completely useless since this can be // solved for easily using the header length and the overall length. Unfortunately // stripping this integer is not trivial, since it's variable length. In order to // know its width we are forced to read it. Who designed this crap? // // There's probably a way to solve for the width of the varint based on the // remaining length of the buffer, but it's unfortunately not as simple as just // calling length_delimiter_len since the buffer contains the varint itself. let main_message_len = decode_length_delimiter(&mut (&buf).into_buf()).unwrap(); buf.split_to(length_delimiter_len(main_message_len)); let mut sidecars = Vec::new(); let body; if self.response_header.sidecar_offsets.is_empty() { body = buf.freeze(); } else { let mut prev_offset = self.response_header.sidecar_offsets[0] as usize; body = buf.split_to(prev_offset).freeze(); for &offset in &self.response_header.sidecar_offsets[1..] { let offset = offset as usize; sidecars.push(buf.split_to(offset - prev_offset)); prev_offset = offset; } sidecars.push(buf); } Ok(Async::Ready((call_id, Ok((body, sidecars))))) } }(); let is_fatal = match result { Ok(Async::Ready((_, Err(ref error)))) => error.is_fatal(), Err(_) => true, _ => false, }; if is_fatal { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Reads at least `at_least` bytes into the receive buffer. /// /// Based on tokio-io's [`FramedRead`][1] and [`AsyncRead`][2]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/master/src/framed_read.rs#L259-L294 /// [2]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/lib.rs#L138-L157 fn poll_fill(&mut self, mut at_least: usize) -> Result<Async<()>, io::Error>
/// Flushes bytes from send buffer to the stream. /// /// Based on tokio-io's [`FramedWrite`][1]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/framed_write.rs#L202-L225 /// /// An error return indicates a fatal error. fn poll_flush(&mut self) -> Result<Async<()>, io::Error> { while!self.send_buf.is_empty() { let n = try_nb!(self.stream.write(&self.send_buf)); if n == 0 { return Err(io::Error::from(io::ErrorKind::WriteZero)); } let _ = self.send_buf.split_to(n); } Ok(Async::Ready(())) } pub fn addr(&self) -> &SocketAddr { &self.addr } pub fn options(&self) -> &Options { &self.options } pub fn send_buf_len(&self) -> usize { self.send_buf.len() } pub fn recv_buf_len(&self) -> usize { self.recv_buf.len() } } /// Future returned by `Transport::connect` which will resolve to a `Transport` when the TCP stream /// is connected. pub(crate) struct TransportNew { addr: SocketAddr, options: Options, connect: ConnectFuture, } impl Future for TransportNew { type Item = Transport; type Error = io::Error; fn poll(&mut self) -> Result<Async<Transport>, io::Error> { let stream = try_ready!(self.connect.poll()); stream.set_nodelay(self.options.nodelay)?; // Write the connection header to the send buffer. let mut send_buf = BytesMut::with_capacity(INITIAL_CAPACITY); send_buf.put_slice(b"hrpc\x09\0\0"); Ok(Async::Ready(Transport { addr: self.addr, options: self.options.clone(), stream, send_buf, recv_buf: BytesMut::with_capacity(INITIAL_CAPACITY), request_header: RequestHeader::default(), response_header: ResponseHeader::default(), })) } } /// Converts a duration to milliseconds. fn duration_to_ms(duration: Duration) -> u32 { let millis = duration .as_secs() .saturating_mul(1000) .saturating_add(u64::from(duration.subsec_nanos()) / 1_000_000); if millis > u64::from(u32::MAX) { u32::MAX } else { millis as u32 } }
{ self.recv_buf.reserve(at_least); while at_least > 0 { let n = unsafe { let n = try_nb!(self.stream.read(self.recv_buf.bytes_mut())); self.recv_buf.advance_mut(n); n }; at_least = at_least.saturating_sub(n); if n == 0 { return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); } } Ok(Async::Ready(())) }
identifier_body
transport.rs
use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr}; use std::time::Duration; use std::u32; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, Bytes, BytesMut, IntoBuf}; use futures::{Async, Future, Poll}; use prost::{decode_length_delimiter, length_delimiter_len, Message}; use tokio::net::{ConnectFuture, TcpStream}; use pb::rpc::{ErrorStatusPb, RemoteMethodPb, RequestHeader, ResponseHeader}; use Error; use Options; use RequestBody; use RpcError; use RpcErrorCode; const INITIAL_CAPACITY: usize = 8 * 1024; const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY; pub type TransportResponse = (Bytes, Vec<BytesMut>); /// `Transport` handles sending and receiving raw KRPC messages to a TCP stream. /// /// The transport manages send and receive buffers, encoding and decoding of messages, message /// framing, headers, and RPC errors. /// /// The transport wraps a single TCP connection. When the TCP connection is shutdown or fails, the /// transport should no longer be used. TCP connection shutdown is indicated by a fatal error being /// returned from `poll_ready()`, `send()`, or `poll()`. pub(crate) struct Transport { addr: SocketAddr, options: Options, stream: TcpStream, send_buf: BytesMut, recv_buf: BytesMut, request_header: RequestHeader, response_header: ResponseHeader, } impl Transport { /// Returns a future which will yield a new transport. pub fn connect(addr: SocketAddr, options: Options) -> TransportNew { let connect = TcpStream::connect(&addr); TransportNew { addr, options, connect, } } /// Returns `true` if the transport is ready to send an RPC to the peer. /// /// An error return indicates a fatal error. pub fn poll_ready(&mut self) -> Poll<(), Error> { let result = || -> Poll<(), Error> { // If the buffer is already over 8KiB, then attempt to flush it. If after flushing it's // *still* over 8KiB, then apply backpressure (reject the send). if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { self.poll_flush()?; if self.send_buf.len() >= BACKPRESSURE_BOUNDARY { return Ok(Async::NotReady); } } Ok(Async::Ready(())) }(); if result.is_err() { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Sends an RPC to the peer. /// /// This method does not provide backpressure, so callers should always check that `poll_ready` /// indicates that there is send capacity available. /// /// If a fatal error is returned the transport is shut down. If a non-fatal error is returned, /// the RPC should be failed. pub fn send( &mut self,
service: &str, method: &str, required_feature_flags: &[u32], body: &RequestBody, timeout: Option<Duration>, ) -> Result<(), Error> { let result = || -> Result<(), Error> { // Set the header fields. self.request_header.call_id = call_id; { let remote_method = self .request_header .remote_method .get_or_insert(RemoteMethodPb::default()); remote_method.clear(); remote_method.service_name.push_str(service); remote_method.method_name.push_str(method); } if let Some(timeout) = timeout { self.request_header.timeout_millis = Some(duration_to_ms(timeout)); } self.request_header.required_feature_flags.clear(); self.request_header .required_feature_flags .extend_from_slice(required_feature_flags); let header_len = Message::encoded_len(&self.request_header); let body_len = body.encoded_len(); let len = length_delimiter_len(header_len) + length_delimiter_len(body_len) + header_len + body_len; if len > self.options.max_message_length as usize { return Err(RpcError { code: RpcErrorCode::ErrorInvalidRequest, message: format!( "RPC request exceeds maximum length ({}/{})", len, self.options.max_message_length ), unsupported_feature_flags: Vec::new(), }.into()); } self.send_buf.put_u32_be(len as u32); Message::encode_length_delimited(&self.request_header, &mut self.send_buf).unwrap(); body.encode_length_delimited(&mut self.send_buf); Ok(()) }(); if let Err(ref error) = result { if error.is_fatal() { let _ = self.stream.shutdown(Shutdown::Both); } } result } /// Attempts to receive a response from the peer. pub fn poll(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { self.poll_flush()?; self.poll_recv() } /// Attempts to read a response from the TCP stream. fn poll_recv(&mut self) -> Poll<(i32, Result<TransportResponse, Error>), Error> { let result = || -> Poll<(i32, Result<TransportResponse, Error>), Error> { // Read, or continue reading, an RPC response message from the socket into the receive // buffer. Every RPC response is prefixed with a 4 bytes length header. if self.recv_buf.len() < 4 { let needed = 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let msg_len = BigEndian::read_u32(&self.recv_buf[..4]) as usize; if msg_len > self.options.max_message_length as usize { return Err(Error::Serialization(format!( "RPC response exceeds maximum length ({}/{})", msg_len, self.options.max_message_length ))); } if self.recv_buf.len() - 4 < msg_len { let needed = msg_len + 4 - self.recv_buf.len(); try_ready!(self.poll_fill(needed)); } let _ = self.recv_buf.split_to(4); let mut buf = self.recv_buf.split_to(msg_len); // Decode the header. let header_len = { let mut cursor = buf.clone().into_buf(); self.response_header.clear(); self.response_header.merge_length_delimited(&mut cursor)?; cursor.position() as usize }; buf.split_to(header_len); let call_id = self.response_header.call_id; if self.response_header.is_error() { let error = Error::Rpc(ErrorStatusPb::decode_length_delimited(buf)?.into()); Ok(Async::Ready((call_id, Err(error)))) } else { // KRPC inserts a len integer before the main message whose value is the length of // the main message and sidecars. This is completely useless since this can be // solved for easily using the header length and the overall length. Unfortunately // stripping this integer is not trivial, since it's variable length. In order to // know its width we are forced to read it. Who designed this crap? // // There's probably a way to solve for the width of the varint based on the // remaining length of the buffer, but it's unfortunately not as simple as just // calling length_delimiter_len since the buffer contains the varint itself. let main_message_len = decode_length_delimiter(&mut (&buf).into_buf()).unwrap(); buf.split_to(length_delimiter_len(main_message_len)); let mut sidecars = Vec::new(); let body; if self.response_header.sidecar_offsets.is_empty() { body = buf.freeze(); } else { let mut prev_offset = self.response_header.sidecar_offsets[0] as usize; body = buf.split_to(prev_offset).freeze(); for &offset in &self.response_header.sidecar_offsets[1..] { let offset = offset as usize; sidecars.push(buf.split_to(offset - prev_offset)); prev_offset = offset; } sidecars.push(buf); } Ok(Async::Ready((call_id, Ok((body, sidecars))))) } }(); let is_fatal = match result { Ok(Async::Ready((_, Err(ref error)))) => error.is_fatal(), Err(_) => true, _ => false, }; if is_fatal { let _ = self.stream.shutdown(Shutdown::Both); } result } /// Reads at least `at_least` bytes into the receive buffer. /// /// Based on tokio-io's [`FramedRead`][1] and [`AsyncRead`][2]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/master/src/framed_read.rs#L259-L294 /// [2]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/lib.rs#L138-L157 fn poll_fill(&mut self, mut at_least: usize) -> Result<Async<()>, io::Error> { self.recv_buf.reserve(at_least); while at_least > 0 { let n = unsafe { let n = try_nb!(self.stream.read(self.recv_buf.bytes_mut())); self.recv_buf.advance_mut(n); n }; at_least = at_least.saturating_sub(n); if n == 0 { return Err(io::Error::from(io::ErrorKind::UnexpectedEof)); } } Ok(Async::Ready(())) } /// Flushes bytes from send buffer to the stream. /// /// Based on tokio-io's [`FramedWrite`][1]. /// [1]: https://github.com/tokio-rs/tokio-io/blob/0.1.3/src/framed_write.rs#L202-L225 /// /// An error return indicates a fatal error. fn poll_flush(&mut self) -> Result<Async<()>, io::Error> { while!self.send_buf.is_empty() { let n = try_nb!(self.stream.write(&self.send_buf)); if n == 0 { return Err(io::Error::from(io::ErrorKind::WriteZero)); } let _ = self.send_buf.split_to(n); } Ok(Async::Ready(())) } pub fn addr(&self) -> &SocketAddr { &self.addr } pub fn options(&self) -> &Options { &self.options } pub fn send_buf_len(&self) -> usize { self.send_buf.len() } pub fn recv_buf_len(&self) -> usize { self.recv_buf.len() } } /// Future returned by `Transport::connect` which will resolve to a `Transport` when the TCP stream /// is connected. pub(crate) struct TransportNew { addr: SocketAddr, options: Options, connect: ConnectFuture, } impl Future for TransportNew { type Item = Transport; type Error = io::Error; fn poll(&mut self) -> Result<Async<Transport>, io::Error> { let stream = try_ready!(self.connect.poll()); stream.set_nodelay(self.options.nodelay)?; // Write the connection header to the send buffer. let mut send_buf = BytesMut::with_capacity(INITIAL_CAPACITY); send_buf.put_slice(b"hrpc\x09\0\0"); Ok(Async::Ready(Transport { addr: self.addr, options: self.options.clone(), stream, send_buf, recv_buf: BytesMut::with_capacity(INITIAL_CAPACITY), request_header: RequestHeader::default(), response_header: ResponseHeader::default(), })) } } /// Converts a duration to milliseconds. fn duration_to_ms(duration: Duration) -> u32 { let millis = duration .as_secs() .saturating_mul(1000) .saturating_add(u64::from(duration.subsec_nanos()) / 1_000_000); if millis > u64::from(u32::MAX) { u32::MAX } else { millis as u32 } }
call_id: i32,
random_line_split
helper_objects.rs
//! Defines some structs, enums, and constants mainly useful for passing information around //! over the FFI and over threads. use std::collections::HashMap; use std::sync::Mutex; use libc::{c_char, c_void, uint64_t, c_double, c_int}; use futures::sync::mpsc::UnboundedSender; use futures::Stream; use futures::stream::BoxStream; use tickgrinder_util::transport::command_server::CommandServer; use tickgrinder_util::trading::broker::*; use tickgrinder_util::trading::tick::*; pub const NULL: *mut c_void = 0 as *mut c_void; /// Contains all possible commands that can be received by the broker server. #[repr(C)] #[derive(Clone)] #[allow(dead_code)] pub enum ServerCommand { MARKET_OPEN, MARKET_CLOSE, LIST_ACCOUNTS, DISCONNECT, PING, INIT_TICK_SUB, GET_OFFER_ROW, DELETE_ORDER, MODIFY_ORDER, } /// Contains all possible responses that can be received by the broker server. #[repr(C)] #[derive(Clone, Debug)] #[allow(dead_code)] pub enum ServerResponse { POSITION_OPENED, POSITION_CLOSED, TRADE_EXECUTED, TRADE_CLOSED, SESSION_TERMINATED, PONG, ERROR, TICK_SUB_SUCCESSFUL, OFFER_ROW, ORDER_MODIFIED, } /// A packet of information asynchronously received from the broker server. #[repr(C)] #[derive(Clone)] pub struct ServerMessage { pub response: ServerResponse, pub payload: *mut c_void, } /// A packet of information that can be sent to the broker server. #[repr(C)] #[derive(Clone)] pub struct
{ pub command: ServerCommand, pub payload: *mut c_void, } pub struct FXCMNative { pub settings_hash: HashMap<String, String>, pub server_environment: *mut c_void, pub raw_rx: Option<BoxStream<(u64, BrokerResult), ()>>, pub tickstream_obj: Mutex<Tickstream>, } // TODO: Move to Util #[derive(Debug)] #[repr(C)] #[allow(dead_code)] pub struct CTick { pub timestamp: uint64_t, pub bid: c_double, pub ask: c_double, } // TODO: Move to Util #[derive(Debug)] #[repr(C)] pub struct CSymbolTick { pub symbol: *const c_char, pub timestamp: uint64_t, pub bid: c_double, pub ask: c_double, } impl CSymbolTick { /// Converts a CSymbolTick into a Tick given the amount of decimal places precision. pub fn to_tick(&self, decimals: usize) -> Tick { let multiplier = 10usize.pow(decimals as u32) as f64; let bid_pips = self.bid * multiplier; let ask_pips = self.ask * multiplier; Tick { timestamp: self.timestamp, bid: bid_pips as usize, ask: ask_pips as usize, } } } /// Contains data necessary to initialize a tickstream #[repr(C)] pub struct TickstreamDef { pub env_ptr: *mut c_void, pub cb: Option<extern fn (tx_ptr: *mut c_void, cst: CSymbolTick)>, } /// Holds the currently subscribed symbols as well as a channel to send them through pub struct Tickstream { pub subbed_pairs: Vec<SubbedPair>, pub cs: CommandServer, } /// A pair that a user has subscribed to containing the symbol, an sender through which to /// send ticks, and the decimal precision of the exchange rate's float value. pub struct SubbedPair { pub symbol: *const c_char, pub sender: UnboundedSender<Tick>, pub decimals: usize, } /// Holds the state for the `handle_message` function pub struct HandlerState { pub sender: UnboundedSender<(u64, BrokerResult)>, pub cs: CommandServer, } /// A request to open or close a position at market price. #[repr(C)] #[allow(dead_code)] struct MarketRequest{ pub symbol: *const c_char, pub quantity: c_int, // when opening a long or closing a short, should be true // when opening a short or closing a long, should be false pub is_long: bool, pub uuid: *const c_char, } // something to hold our environment so we can convince Rust to send it between threads #[derive(Clone)] pub struct Spaceship(pub *mut c_void); unsafe impl Send for Spaceship{} unsafe impl Send for FXCMNative {} unsafe impl Send for ServerMessage {} unsafe impl Send for ClientMessage {}
ClientMessage
identifier_name
helper_objects.rs
//! Defines some structs, enums, and constants mainly useful for passing information around //! over the FFI and over threads. use std::collections::HashMap; use std::sync::Mutex; use libc::{c_char, c_void, uint64_t, c_double, c_int}; use futures::sync::mpsc::UnboundedSender; use futures::Stream; use futures::stream::BoxStream; use tickgrinder_util::transport::command_server::CommandServer; use tickgrinder_util::trading::broker::*; use tickgrinder_util::trading::tick::*; pub const NULL: *mut c_void = 0 as *mut c_void; /// Contains all possible commands that can be received by the broker server. #[repr(C)] #[derive(Clone)] #[allow(dead_code)] pub enum ServerCommand { MARKET_OPEN, MARKET_CLOSE, LIST_ACCOUNTS, DISCONNECT, PING, INIT_TICK_SUB, GET_OFFER_ROW, DELETE_ORDER, MODIFY_ORDER, } /// Contains all possible responses that can be received by the broker server. #[repr(C)] #[derive(Clone, Debug)] #[allow(dead_code)] pub enum ServerResponse { POSITION_OPENED, POSITION_CLOSED, TRADE_EXECUTED, TRADE_CLOSED, SESSION_TERMINATED, PONG, ERROR, TICK_SUB_SUCCESSFUL, OFFER_ROW, ORDER_MODIFIED, } /// A packet of information asynchronously received from the broker server. #[repr(C)] #[derive(Clone)] pub struct ServerMessage { pub response: ServerResponse, pub payload: *mut c_void, } /// A packet of information that can be sent to the broker server. #[repr(C)] #[derive(Clone)] pub struct ClientMessage { pub command: ServerCommand, pub payload: *mut c_void, } pub struct FXCMNative { pub settings_hash: HashMap<String, String>, pub server_environment: *mut c_void, pub raw_rx: Option<BoxStream<(u64, BrokerResult), ()>>, pub tickstream_obj: Mutex<Tickstream>, } // TODO: Move to Util #[derive(Debug)] #[repr(C)] #[allow(dead_code)] pub struct CTick { pub timestamp: uint64_t, pub bid: c_double, pub ask: c_double, } // TODO: Move to Util #[derive(Debug)] #[repr(C)] pub struct CSymbolTick { pub symbol: *const c_char, pub timestamp: uint64_t,
impl CSymbolTick { /// Converts a CSymbolTick into a Tick given the amount of decimal places precision. pub fn to_tick(&self, decimals: usize) -> Tick { let multiplier = 10usize.pow(decimals as u32) as f64; let bid_pips = self.bid * multiplier; let ask_pips = self.ask * multiplier; Tick { timestamp: self.timestamp, bid: bid_pips as usize, ask: ask_pips as usize, } } } /// Contains data necessary to initialize a tickstream #[repr(C)] pub struct TickstreamDef { pub env_ptr: *mut c_void, pub cb: Option<extern fn (tx_ptr: *mut c_void, cst: CSymbolTick)>, } /// Holds the currently subscribed symbols as well as a channel to send them through pub struct Tickstream { pub subbed_pairs: Vec<SubbedPair>, pub cs: CommandServer, } /// A pair that a user has subscribed to containing the symbol, an sender through which to /// send ticks, and the decimal precision of the exchange rate's float value. pub struct SubbedPair { pub symbol: *const c_char, pub sender: UnboundedSender<Tick>, pub decimals: usize, } /// Holds the state for the `handle_message` function pub struct HandlerState { pub sender: UnboundedSender<(u64, BrokerResult)>, pub cs: CommandServer, } /// A request to open or close a position at market price. #[repr(C)] #[allow(dead_code)] struct MarketRequest{ pub symbol: *const c_char, pub quantity: c_int, // when opening a long or closing a short, should be true // when opening a short or closing a long, should be false pub is_long: bool, pub uuid: *const c_char, } // something to hold our environment so we can convince Rust to send it between threads #[derive(Clone)] pub struct Spaceship(pub *mut c_void); unsafe impl Send for Spaceship{} unsafe impl Send for FXCMNative {} unsafe impl Send for ServerMessage {} unsafe impl Send for ClientMessage {}
pub bid: c_double, pub ask: c_double, }
random_line_split
mod.rs
//! Resource data implementations. //! //! This module will eventually contain implementations for the record data //! for all defined resource record types. //! //! The types are named identically to the [`Rtype`] variant they implement. //! They are grouped into submodules for the RFCs they are defined in. All //! types are also re-exported at the top level here. Ie., for the AAAA //! record type, you can simple `use domain::rdata::Aaaa` instead of //! `use domain::rdata::rfc3596::Aaaa` which nobody could possibly remember. //! There are, however, some helper data types defined here and there which //! are not re-exported to keep things somewhat tidy. //! //! See the [`Rtype`] enum for the complete set of record types and, //! consequently, those types that are still missing. //! //! [`Rtype`]:../iana/enum.Rtype.html pub mod rfc1035; pub mod rfc2782; pub mod rfc3596; #[macro_use] mod macros; mod generic; use ::bits::{CharStrBuf, DNameBuf}; // The master_types! macro (defined in self::macros) creates the // MasterRecordData enum produced when parsing master files (aka zone files). // // Include all record types that can occur in master files. Place the name of // the variant (identical to the type name) on the left side of the double // arrow and the name of the type on the right. If the type is generic, use // the owned version. // // The macro creates the re-export of the record data type. master_types!{ rfc1035::{ A => A, Cname => Cname<DNameBuf>, Hinfo => Hinfo<CharStrBuf>, Mb => Mb<DNameBuf>, Md => Md<DNameBuf>, Mf => Mf<DNameBuf>, Mg => Mg<DNameBuf>, Minfo => Minfo<DNameBuf>, Mr => Mr<DNameBuf>, Mx => Mx<DNameBuf>, Ns => Ns<DNameBuf>, Ptr => Ptr<DNameBuf>, Soa => Soa<DNameBuf>, Txt => Txt<Vec<u8>>, Wks => Wks<rfc1035::WksBitmapBuf>, } rfc2782::{ Srv => Srv<DNameBuf>, } rfc3596::{ Aaaa => Aaaa, } } // The pseudo_types! macro (defined in self::macros) creates the re-exports // for all the types not part of master_types! above. pseudo_types!{ rfc1035::{Null}; //rfc6891::{Opt}; } /// Formats record data from a message parser in master file format. /// /// This helper function formats the record data at the start of `parser` /// using the formatter `f`. It assumes that the record data is for a /// record of record type `rtype`. /// /// If the record type is known, the function tries to use the type’s /// proper master data format. Otherwise the generic format is used. pub fn fmt_rdata(rtype: ::iana::Rtype, parser: &mut ::bits::Parser, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match try!(fmt_master_data(rtype, parser, f)) { Some(res) => Ok(res), None => {
} } /// Parsed versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types that use parsed domain names and references to bytes slices where /// applicable. For convenience, it also includes re-exports for those types /// that are not in fact generic. /// /// Use the types from this module when working with wire format DNS messages. pub mod parsed { pub use super::rfc1035::parsed::*; pub use super::rfc3596::Aaaa; pub type Srv<'a> = super::rfc2782::Srv<::bits::ParsedDName<'a>>; } /// Owned versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types using owned data only. For convenience, it also includes re-exports /// for those types that are not generic. /// /// Use the types from this module if you are working with master file data /// or if you are constructing your own values. pub mod owned { pub use super::rfc1035::owned::*; pub use super::rfc3596::Aaaa; pub type Srv = super::rfc2782::Srv<::bits::DNameBuf>; }
let mut parser = parser.clone(); let len = parser.remaining(); let data = parser.parse_bytes(len).unwrap(); generic::fmt(data, f) }
conditional_block
mod.rs
//! Resource data implementations. //! //! This module will eventually contain implementations for the record data //! for all defined resource record types. //! //! The types are named identically to the [`Rtype`] variant they implement. //! They are grouped into submodules for the RFCs they are defined in. All //! types are also re-exported at the top level here. Ie., for the AAAA //! record type, you can simple `use domain::rdata::Aaaa` instead of //! `use domain::rdata::rfc3596::Aaaa` which nobody could possibly remember. //! There are, however, some helper data types defined here and there which //! are not re-exported to keep things somewhat tidy. //! //! See the [`Rtype`] enum for the complete set of record types and, //! consequently, those types that are still missing. //! //! [`Rtype`]:../iana/enum.Rtype.html pub mod rfc1035; pub mod rfc2782; pub mod rfc3596; #[macro_use] mod macros; mod generic; use ::bits::{CharStrBuf, DNameBuf}; // The master_types! macro (defined in self::macros) creates the // MasterRecordData enum produced when parsing master files (aka zone files). // // Include all record types that can occur in master files. Place the name of // the variant (identical to the type name) on the left side of the double // arrow and the name of the type on the right. If the type is generic, use // the owned version. // // The macro creates the re-export of the record data type. master_types!{ rfc1035::{ A => A, Cname => Cname<DNameBuf>, Hinfo => Hinfo<CharStrBuf>, Mb => Mb<DNameBuf>, Md => Md<DNameBuf>, Mf => Mf<DNameBuf>, Mg => Mg<DNameBuf>, Minfo => Minfo<DNameBuf>, Mr => Mr<DNameBuf>, Mx => Mx<DNameBuf>, Ns => Ns<DNameBuf>, Ptr => Ptr<DNameBuf>, Soa => Soa<DNameBuf>, Txt => Txt<Vec<u8>>, Wks => Wks<rfc1035::WksBitmapBuf>, } rfc2782::{ Srv => Srv<DNameBuf>, } rfc3596::{ Aaaa => Aaaa, } } // The pseudo_types! macro (defined in self::macros) creates the re-exports // for all the types not part of master_types! above. pseudo_types!{ rfc1035::{Null}; //rfc6891::{Opt}; } /// Formats record data from a message parser in master file format. /// /// This helper function formats the record data at the start of `parser` /// using the formatter `f`. It assumes that the record data is for a /// record of record type `rtype`. /// /// If the record type is known, the function tries to use the type’s /// proper master data format. Otherwise the generic format is used. pub fn fmt_rdata(rtype: ::iana::Rtype, parser: &mut ::bits::Parser, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
/// Parsed versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types that use parsed domain names and references to bytes slices where /// applicable. For convenience, it also includes re-exports for those types /// that are not in fact generic. /// /// Use the types from this module when working with wire format DNS messages. pub mod parsed { pub use super::rfc1035::parsed::*; pub use super::rfc3596::Aaaa; pub type Srv<'a> = super::rfc2782::Srv<::bits::ParsedDName<'a>>; } /// Owned versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types using owned data only. For convenience, it also includes re-exports /// for those types that are not generic. /// /// Use the types from this module if you are working with master file data /// or if you are constructing your own values. pub mod owned { pub use super::rfc1035::owned::*; pub use super::rfc3596::Aaaa; pub type Srv = super::rfc2782::Srv<::bits::DNameBuf>; }
match try!(fmt_master_data(rtype, parser, f)) { Some(res) => Ok(res), None => { let mut parser = parser.clone(); let len = parser.remaining(); let data = parser.parse_bytes(len).unwrap(); generic::fmt(data, f) } } }
identifier_body
mod.rs
//! Resource data implementations. //! //! This module will eventually contain implementations for the record data //! for all defined resource record types. //! //! The types are named identically to the [`Rtype`] variant they implement. //! They are grouped into submodules for the RFCs they are defined in. All //! types are also re-exported at the top level here. Ie., for the AAAA //! record type, you can simple `use domain::rdata::Aaaa` instead of //! `use domain::rdata::rfc3596::Aaaa` which nobody could possibly remember. //! There are, however, some helper data types defined here and there which //! are not re-exported to keep things somewhat tidy. //! //! See the [`Rtype`] enum for the complete set of record types and, //! consequently, those types that are still missing. //! //! [`Rtype`]:../iana/enum.Rtype.html pub mod rfc1035; pub mod rfc2782; pub mod rfc3596; #[macro_use] mod macros; mod generic; use ::bits::{CharStrBuf, DNameBuf}; // The master_types! macro (defined in self::macros) creates the // MasterRecordData enum produced when parsing master files (aka zone files). // // Include all record types that can occur in master files. Place the name of // the variant (identical to the type name) on the left side of the double // arrow and the name of the type on the right. If the type is generic, use // the owned version. // // The macro creates the re-export of the record data type. master_types!{ rfc1035::{ A => A, Cname => Cname<DNameBuf>, Hinfo => Hinfo<CharStrBuf>, Mb => Mb<DNameBuf>, Md => Md<DNameBuf>, Mf => Mf<DNameBuf>, Mg => Mg<DNameBuf>, Minfo => Minfo<DNameBuf>, Mr => Mr<DNameBuf>, Mx => Mx<DNameBuf>, Ns => Ns<DNameBuf>, Ptr => Ptr<DNameBuf>, Soa => Soa<DNameBuf>, Txt => Txt<Vec<u8>>, Wks => Wks<rfc1035::WksBitmapBuf>, } rfc2782::{ Srv => Srv<DNameBuf>, } rfc3596::{ Aaaa => Aaaa, } } // The pseudo_types! macro (defined in self::macros) creates the re-exports // for all the types not part of master_types! above. pseudo_types!{ rfc1035::{Null}; //rfc6891::{Opt}; } /// Formats record data from a message parser in master file format. /// /// This helper function formats the record data at the start of `parser` /// using the formatter `f`. It assumes that the record data is for a /// record of record type `rtype`. /// /// If the record type is known, the function tries to use the type’s /// proper master data format. Otherwise the generic format is used. pub fn fm
type: ::iana::Rtype, parser: &mut ::bits::Parser, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match try!(fmt_master_data(rtype, parser, f)) { Some(res) => Ok(res), None => { let mut parser = parser.clone(); let len = parser.remaining(); let data = parser.parse_bytes(len).unwrap(); generic::fmt(data, f) } } } /// Parsed versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types that use parsed domain names and references to bytes slices where /// applicable. For convenience, it also includes re-exports for those types /// that are not in fact generic. /// /// Use the types from this module when working with wire format DNS messages. pub mod parsed { pub use super::rfc1035::parsed::*; pub use super::rfc3596::Aaaa; pub type Srv<'a> = super::rfc2782::Srv<::bits::ParsedDName<'a>>; } /// Owned versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types using owned data only. For convenience, it also includes re-exports /// for those types that are not generic. /// /// Use the types from this module if you are working with master file data /// or if you are constructing your own values. pub mod owned { pub use super::rfc1035::owned::*; pub use super::rfc3596::Aaaa; pub type Srv = super::rfc2782::Srv<::bits::DNameBuf>; }
t_rdata(r
identifier_name
mod.rs
//! Resource data implementations. //! //! This module will eventually contain implementations for the record data //! for all defined resource record types. //! //! The types are named identically to the [`Rtype`] variant they implement. //! They are grouped into submodules for the RFCs they are defined in. All //! types are also re-exported at the top level here. Ie., for the AAAA //! record type, you can simple `use domain::rdata::Aaaa` instead of //! `use domain::rdata::rfc3596::Aaaa` which nobody could possibly remember. //! There are, however, some helper data types defined here and there which //! are not re-exported to keep things somewhat tidy. //! //! See the [`Rtype`] enum for the complete set of record types and, //! consequently, those types that are still missing. //! //! [`Rtype`]:../iana/enum.Rtype.html pub mod rfc1035; pub mod rfc2782; pub mod rfc3596; #[macro_use] mod macros; mod generic; use ::bits::{CharStrBuf, DNameBuf}; // The master_types! macro (defined in self::macros) creates the // MasterRecordData enum produced when parsing master files (aka zone files).
// arrow and the name of the type on the right. If the type is generic, use // the owned version. // // The macro creates the re-export of the record data type. master_types!{ rfc1035::{ A => A, Cname => Cname<DNameBuf>, Hinfo => Hinfo<CharStrBuf>, Mb => Mb<DNameBuf>, Md => Md<DNameBuf>, Mf => Mf<DNameBuf>, Mg => Mg<DNameBuf>, Minfo => Minfo<DNameBuf>, Mr => Mr<DNameBuf>, Mx => Mx<DNameBuf>, Ns => Ns<DNameBuf>, Ptr => Ptr<DNameBuf>, Soa => Soa<DNameBuf>, Txt => Txt<Vec<u8>>, Wks => Wks<rfc1035::WksBitmapBuf>, } rfc2782::{ Srv => Srv<DNameBuf>, } rfc3596::{ Aaaa => Aaaa, } } // The pseudo_types! macro (defined in self::macros) creates the re-exports // for all the types not part of master_types! above. pseudo_types!{ rfc1035::{Null}; //rfc6891::{Opt}; } /// Formats record data from a message parser in master file format. /// /// This helper function formats the record data at the start of `parser` /// using the formatter `f`. It assumes that the record data is for a /// record of record type `rtype`. /// /// If the record type is known, the function tries to use the type’s /// proper master data format. Otherwise the generic format is used. pub fn fmt_rdata(rtype: ::iana::Rtype, parser: &mut ::bits::Parser, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match try!(fmt_master_data(rtype, parser, f)) { Some(res) => Ok(res), None => { let mut parser = parser.clone(); let len = parser.remaining(); let data = parser.parse_bytes(len).unwrap(); generic::fmt(data, f) } } } /// Parsed versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types that use parsed domain names and references to bytes slices where /// applicable. For convenience, it also includes re-exports for those types /// that are not in fact generic. /// /// Use the types from this module when working with wire format DNS messages. pub mod parsed { pub use super::rfc1035::parsed::*; pub use super::rfc3596::Aaaa; pub type Srv<'a> = super::rfc2782::Srv<::bits::ParsedDName<'a>>; } /// Owned versions of all record data types. /// /// This module defines or re-exports type aliases for all record data /// types using owned data only. For convenience, it also includes re-exports /// for those types that are not generic. /// /// Use the types from this module if you are working with master file data /// or if you are constructing your own values. pub mod owned { pub use super::rfc1035::owned::*; pub use super::rfc3596::Aaaa; pub type Srv = super::rfc2782::Srv<::bits::DNameBuf>; }
// // Include all record types that can occur in master files. Place the name of // the variant (identical to the type name) on the left side of the double
random_line_split
lib.rs
#![feature(const_fn)] #![feature(drop_types_in_const)] #![feature(proc_macro)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate bootstrap_rs as bootstrap; extern crate fiber; use fiber::FiberId; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::mem; use std::sync::Mutex; use std::time::Duration; #[cfg(target_os="windows")] #[path="windows.rs"] pub mod platform; pub mod stats; thread_local! { static CONTEXT: RefCell<Context> = RefCell::new(Context::new()); } lazy_static! { static ref CONTEXT_MAP: Mutex<HashMap<FiberId, Context>> = Mutex::new(HashMap::with_capacity(1024)); static ref EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); } /// Swaps the currently tracked execution context with the specified context. pub fn switch_context(old: FiberId, new: FiberId) { with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter().rev() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "E", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); let mut context_map = CONTEXT_MAP.lock().expect("Unable to acquire lock on context map"); let new_context = context_map.remove(&new).unwrap_or(Context::new()); let old_context = with_context(move |context| { let mut new_context = new_context; mem::swap(context, &mut new_context); new_context }); context_map.insert(old, old_context); with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "B", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); } /// Writes the events history to a string. pub fn write_events_to_string() -> String { let events = EVENTS.lock().expect("Events mutex got poisoned"); serde_json::to_string(&*events).unwrap() } pub struct Stopwatch { name: &'static str, } impl Stopwatch { pub fn new(name: &'static str) -> Stopwatch { push_event(Event { name: name, cat: String::new(), ph: "B", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); with_context(|stack| { stack.push(StopwatchData { name: name }); }); Stopwatch { name: name, } } pub fn with_budget(name: &'static str, _budget: Duration) -> Stopwatch { // TODO: We should actually do something with the budget, right? Stopwatch::new(name) } } impl Drop for Stopwatch { fn drop(&mut self) { with_context(|stack| { let stopwatch = stack.pop().expect("No stopwatch popped, stack is corrupted"); assert_eq!(self.name, stopwatch.name, "Stack got corrupted I guess"); }); push_event(Event { name: self.name, cat: String::new(), ph: "E", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); } } #[derive(Debug, Serialize)] struct
{ /// Human-readable name for the event. name: &'static str, /// Event category. cat: String, /// Event phase (i.e. the event type). ph: &'static str, /// Timestamp in microseconds. ts: i64, /// Process ID for the event. pid: usize, /// Thread ID for the event. tid: usize, } fn push_event(event: Event) { let mut events = EVENTS.lock().expect("Events mutex got poisoned"); events.push(event); } #[derive(Debug, Clone, Copy)] struct StopwatchData { name: &'static str, } type Context = Vec<StopwatchData>; fn with_context<F, T>(func: F) -> T where F: FnOnce(&mut Context) -> T { CONTEXT.with(move |context_cell| { let mut context = context_cell.borrow_mut(); func(&mut *context) }) } pub struct PrettyDuration(pub Duration); impl Display for PrettyDuration { fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { let mins = self.0.as_secs() / 60; let secs = self.0.as_secs() % 60; let millis = self.0.subsec_nanos() as u64 / 1_000_000; let micros = (self.0.subsec_nanos() / 1_000) % 1_000; if mins > 0 { write!(formatter, "{}m {}s {}.{}ms", mins, secs, millis, micros) } else if secs > 0 { write!(formatter, "{}s {}.{}ms", secs, millis, micros) } else { write!(formatter, "{}.{}ms", millis, micros) } } }
Event
identifier_name
lib.rs
#![feature(const_fn)] #![feature(drop_types_in_const)] #![feature(proc_macro)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate bootstrap_rs as bootstrap; extern crate fiber; use fiber::FiberId; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::mem; use std::sync::Mutex; use std::time::Duration; #[cfg(target_os="windows")] #[path="windows.rs"] pub mod platform; pub mod stats; thread_local! { static CONTEXT: RefCell<Context> = RefCell::new(Context::new()); } lazy_static! { static ref CONTEXT_MAP: Mutex<HashMap<FiberId, Context>> = Mutex::new(HashMap::with_capacity(1024)); static ref EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); } /// Swaps the currently tracked execution context with the specified context. pub fn switch_context(old: FiberId, new: FiberId) { with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter().rev() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "E", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); let mut context_map = CONTEXT_MAP.lock().expect("Unable to acquire lock on context map"); let new_context = context_map.remove(&new).unwrap_or(Context::new()); let old_context = with_context(move |context| { let mut new_context = new_context; mem::swap(context, &mut new_context); new_context }); context_map.insert(old, old_context); with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "B", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); } /// Writes the events history to a string. pub fn write_events_to_string() -> String { let events = EVENTS.lock().expect("Events mutex got poisoned"); serde_json::to_string(&*events).unwrap() } pub struct Stopwatch { name: &'static str, } impl Stopwatch { pub fn new(name: &'static str) -> Stopwatch
pub fn with_budget(name: &'static str, _budget: Duration) -> Stopwatch { // TODO: We should actually do something with the budget, right? Stopwatch::new(name) } } impl Drop for Stopwatch { fn drop(&mut self) { with_context(|stack| { let stopwatch = stack.pop().expect("No stopwatch popped, stack is corrupted"); assert_eq!(self.name, stopwatch.name, "Stack got corrupted I guess"); }); push_event(Event { name: self.name, cat: String::new(), ph: "E", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); } } #[derive(Debug, Serialize)] struct Event { /// Human-readable name for the event. name: &'static str, /// Event category. cat: String, /// Event phase (i.e. the event type). ph: &'static str, /// Timestamp in microseconds. ts: i64, /// Process ID for the event. pid: usize, /// Thread ID for the event. tid: usize, } fn push_event(event: Event) { let mut events = EVENTS.lock().expect("Events mutex got poisoned"); events.push(event); } #[derive(Debug, Clone, Copy)] struct StopwatchData { name: &'static str, } type Context = Vec<StopwatchData>; fn with_context<F, T>(func: F) -> T where F: FnOnce(&mut Context) -> T { CONTEXT.with(move |context_cell| { let mut context = context_cell.borrow_mut(); func(&mut *context) }) } pub struct PrettyDuration(pub Duration); impl Display for PrettyDuration { fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { let mins = self.0.as_secs() / 60; let secs = self.0.as_secs() % 60; let millis = self.0.subsec_nanos() as u64 / 1_000_000; let micros = (self.0.subsec_nanos() / 1_000) % 1_000; if mins > 0 { write!(formatter, "{}m {}s {}.{}ms", mins, secs, millis, micros) } else if secs > 0 { write!(formatter, "{}s {}.{}ms", secs, millis, micros) } else { write!(formatter, "{}.{}ms", millis, micros) } } }
{ push_event(Event { name: name, cat: String::new(), ph: "B", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); with_context(|stack| { stack.push(StopwatchData { name: name }); }); Stopwatch { name: name, } }
identifier_body
lib.rs
#![feature(const_fn)] #![feature(drop_types_in_const)] #![feature(proc_macro)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate bootstrap_rs as bootstrap; extern crate fiber; use fiber::FiberId; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::mem; use std::sync::Mutex; use std::time::Duration; #[cfg(target_os="windows")] #[path="windows.rs"] pub mod platform; pub mod stats; thread_local! { static CONTEXT: RefCell<Context> = RefCell::new(Context::new()); } lazy_static! { static ref CONTEXT_MAP: Mutex<HashMap<FiberId, Context>> = Mutex::new(HashMap::with_capacity(1024)); static ref EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); } /// Swaps the currently tracked execution context with the specified context. pub fn switch_context(old: FiberId, new: FiberId) { with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter().rev() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "E", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); let mut context_map = CONTEXT_MAP.lock().expect("Unable to acquire lock on context map"); let new_context = context_map.remove(&new).unwrap_or(Context::new()); let old_context = with_context(move |context| { let mut new_context = new_context; mem::swap(context, &mut new_context); new_context }); context_map.insert(old, old_context); with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "B", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); } /// Writes the events history to a string. pub fn write_events_to_string() -> String { let events = EVENTS.lock().expect("Events mutex got poisoned"); serde_json::to_string(&*events).unwrap() } pub struct Stopwatch { name: &'static str, } impl Stopwatch { pub fn new(name: &'static str) -> Stopwatch { push_event(Event { name: name, cat: String::new(), ph: "B", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); with_context(|stack| { stack.push(StopwatchData { name: name }); }); Stopwatch { name: name, } } pub fn with_budget(name: &'static str, _budget: Duration) -> Stopwatch { // TODO: We should actually do something with the budget, right? Stopwatch::new(name) } } impl Drop for Stopwatch { fn drop(&mut self) { with_context(|stack| { let stopwatch = stack.pop().expect("No stopwatch popped, stack is corrupted"); assert_eq!(self.name, stopwatch.name, "Stack got corrupted I guess"); }); push_event(Event { name: self.name, cat: String::new(), ph: "E", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); } } #[derive(Debug, Serialize)] struct Event { /// Human-readable name for the event. name: &'static str, /// Event category. cat: String, /// Event phase (i.e. the event type). ph: &'static str, /// Timestamp in microseconds. ts: i64, /// Process ID for the event. pid: usize, /// Thread ID for the event. tid: usize, } fn push_event(event: Event) { let mut events = EVENTS.lock().expect("Events mutex got poisoned"); events.push(event); } #[derive(Debug, Clone, Copy)] struct StopwatchData { name: &'static str, } type Context = Vec<StopwatchData>; fn with_context<F, T>(func: F) -> T where F: FnOnce(&mut Context) -> T { CONTEXT.with(move |context_cell| { let mut context = context_cell.borrow_mut(); func(&mut *context) }) } pub struct PrettyDuration(pub Duration); impl Display for PrettyDuration { fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { let mins = self.0.as_secs() / 60; let secs = self.0.as_secs() % 60; let millis = self.0.subsec_nanos() as u64 / 1_000_000; let micros = (self.0.subsec_nanos() / 1_000) % 1_000;
write!(formatter, "{}m {}s {}.{}ms", mins, secs, millis, micros) } else if secs > 0 { write!(formatter, "{}s {}.{}ms", secs, millis, micros) } else { write!(formatter, "{}.{}ms", millis, micros) } } }
if mins > 0 {
random_line_split
lib.rs
#![feature(const_fn)] #![feature(drop_types_in_const)] #![feature(proc_macro)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate bootstrap_rs as bootstrap; extern crate fiber; use fiber::FiberId; use std::cell::RefCell; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::mem; use std::sync::Mutex; use std::time::Duration; #[cfg(target_os="windows")] #[path="windows.rs"] pub mod platform; pub mod stats; thread_local! { static CONTEXT: RefCell<Context> = RefCell::new(Context::new()); } lazy_static! { static ref CONTEXT_MAP: Mutex<HashMap<FiberId, Context>> = Mutex::new(HashMap::with_capacity(1024)); static ref EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); } /// Swaps the currently tracked execution context with the specified context. pub fn switch_context(old: FiberId, new: FiberId) { with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter().rev() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "E", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); let mut context_map = CONTEXT_MAP.lock().expect("Unable to acquire lock on context map"); let new_context = context_map.remove(&new).unwrap_or(Context::new()); let old_context = with_context(move |context| { let mut new_context = new_context; mem::swap(context, &mut new_context); new_context }); context_map.insert(old, old_context); with_context(|stack| { let timestamp = platform::timestamp(); // Push an end event for each of the time slices. for stopwatch in stack.iter() { push_event(Event { name: stopwatch.name, cat: String::new(), ph: "B", ts: timestamp, tid: platform::thread_id(), pid: 0, }); } }); } /// Writes the events history to a string. pub fn write_events_to_string() -> String { let events = EVENTS.lock().expect("Events mutex got poisoned"); serde_json::to_string(&*events).unwrap() } pub struct Stopwatch { name: &'static str, } impl Stopwatch { pub fn new(name: &'static str) -> Stopwatch { push_event(Event { name: name, cat: String::new(), ph: "B", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); with_context(|stack| { stack.push(StopwatchData { name: name }); }); Stopwatch { name: name, } } pub fn with_budget(name: &'static str, _budget: Duration) -> Stopwatch { // TODO: We should actually do something with the budget, right? Stopwatch::new(name) } } impl Drop for Stopwatch { fn drop(&mut self) { with_context(|stack| { let stopwatch = stack.pop().expect("No stopwatch popped, stack is corrupted"); assert_eq!(self.name, stopwatch.name, "Stack got corrupted I guess"); }); push_event(Event { name: self.name, cat: String::new(), ph: "E", ts: platform::timestamp(), tid: platform::thread_id(), pid: 0, // TODO: Do we care about tracking process ID? }); } } #[derive(Debug, Serialize)] struct Event { /// Human-readable name for the event. name: &'static str, /// Event category. cat: String, /// Event phase (i.e. the event type). ph: &'static str, /// Timestamp in microseconds. ts: i64, /// Process ID for the event. pid: usize, /// Thread ID for the event. tid: usize, } fn push_event(event: Event) { let mut events = EVENTS.lock().expect("Events mutex got poisoned"); events.push(event); } #[derive(Debug, Clone, Copy)] struct StopwatchData { name: &'static str, } type Context = Vec<StopwatchData>; fn with_context<F, T>(func: F) -> T where F: FnOnce(&mut Context) -> T { CONTEXT.with(move |context_cell| { let mut context = context_cell.borrow_mut(); func(&mut *context) }) } pub struct PrettyDuration(pub Duration); impl Display for PrettyDuration { fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { let mins = self.0.as_secs() / 60; let secs = self.0.as_secs() % 60; let millis = self.0.subsec_nanos() as u64 / 1_000_000; let micros = (self.0.subsec_nanos() / 1_000) % 1_000; if mins > 0 { write!(formatter, "{}m {}s {}.{}ms", mins, secs, millis, micros) } else if secs > 0
else { write!(formatter, "{}.{}ms", millis, micros) } } }
{ write!(formatter, "{}s {}.{}ms", secs, millis, micros) }
conditional_block
main.rs
// Copyright 2015 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; use gfx::traits::FactoryExt; use gfx::Device;
vertex Vertex { pos: [f32; 2] = "a_Pos", color: [f32; 3] = "a_Color", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), out: gfx::RenderTarget<ColorFormat> = "Target0", } } const TRIANGLE: [Vertex; 3] = [ Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] }, Vertex { pos: [ 0.5, -0.5 ], color: [0.0, 1.0, 0.0] }, Vertex { pos: [ 0.0, 0.5 ], color: [0.0, 0.0, 1.0] } ]; const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0]; pub fn main() { let builder = glutin::WindowBuilder::new() .with_title("Triangle example".to_string()) .with_dimensions(1024, 768) .with_vsync(); let (window, mut device, mut factory, main_color, _main_depth) = gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder); let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into(); let pso = factory.create_pipeline_simple( include_bytes!("shader/triangle_150.glslv"), include_bytes!("shader/triangle_150.glslf"), pipe::new() ).unwrap(); let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&TRIANGLE, ()); let data = pipe::Data { vbuf: vertex_buffer, out: main_color }; 'main: loop { // loop over events for event in window.poll_events() { match event { glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) | glutin::Event::Closed => break'main, _ => {}, } } // draw a frame encoder.clear(&data.out, CLEAR_COLOR); encoder.draw(&slice, &pso, &data); encoder.flush(&mut device); window.swap_buffers().unwrap(); device.cleanup(); } }
pub type ColorFormat = gfx::format::Rgba8; pub type DepthFormat = gfx::format::DepthStencil; gfx_defines!{
random_line_split
main.rs
// Copyright 2015 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; use gfx::traits::FactoryExt; use gfx::Device; pub type ColorFormat = gfx::format::Rgba8; pub type DepthFormat = gfx::format::DepthStencil; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", color: [f32; 3] = "a_Color", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), out: gfx::RenderTarget<ColorFormat> = "Target0", } } const TRIANGLE: [Vertex; 3] = [ Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] }, Vertex { pos: [ 0.5, -0.5 ], color: [0.0, 1.0, 0.0] }, Vertex { pos: [ 0.0, 0.5 ], color: [0.0, 0.0, 1.0] } ]; const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0]; pub fn
() { let builder = glutin::WindowBuilder::new() .with_title("Triangle example".to_string()) .with_dimensions(1024, 768) .with_vsync(); let (window, mut device, mut factory, main_color, _main_depth) = gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder); let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into(); let pso = factory.create_pipeline_simple( include_bytes!("shader/triangle_150.glslv"), include_bytes!("shader/triangle_150.glslf"), pipe::new() ).unwrap(); let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&TRIANGLE, ()); let data = pipe::Data { vbuf: vertex_buffer, out: main_color }; 'main: loop { // loop over events for event in window.poll_events() { match event { glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) | glutin::Event::Closed => break'main, _ => {}, } } // draw a frame encoder.clear(&data.out, CLEAR_COLOR); encoder.draw(&slice, &pso, &data); encoder.flush(&mut device); window.swap_buffers().unwrap(); device.cleanup(); } }
main
identifier_name
main.rs
// Copyright 2015 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; use gfx::traits::FactoryExt; use gfx::Device; pub type ColorFormat = gfx::format::Rgba8; pub type DepthFormat = gfx::format::DepthStencil; gfx_defines!{ vertex Vertex { pos: [f32; 2] = "a_Pos", color: [f32; 3] = "a_Color", } pipeline pipe { vbuf: gfx::VertexBuffer<Vertex> = (), out: gfx::RenderTarget<ColorFormat> = "Target0", } } const TRIANGLE: [Vertex; 3] = [ Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] }, Vertex { pos: [ 0.5, -0.5 ], color: [0.0, 1.0, 0.0] }, Vertex { pos: [ 0.0, 0.5 ], color: [0.0, 0.0, 1.0] } ]; const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0]; pub fn main()
// loop over events for event in window.poll_events() { match event { glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) | glutin::Event::Closed => break'main, _ => {}, } } // draw a frame encoder.clear(&data.out, CLEAR_COLOR); encoder.draw(&slice, &pso, &data); encoder.flush(&mut device); window.swap_buffers().unwrap(); device.cleanup(); } }
{ let builder = glutin::WindowBuilder::new() .with_title("Triangle example".to_string()) .with_dimensions(1024, 768) .with_vsync(); let (window, mut device, mut factory, main_color, _main_depth) = gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder); let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into(); let pso = factory.create_pipeline_simple( include_bytes!("shader/triangle_150.glslv"), include_bytes!("shader/triangle_150.glslf"), pipe::new() ).unwrap(); let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&TRIANGLE, ()); let data = pipe::Data { vbuf: vertex_buffer, out: main_color }; 'main: loop {
identifier_body
gamma.rs
use err::ErrMsg; use RGSLRng; #[derive(Debug, Clone)] pub struct Gamma { a: f64, b: f64, } impl Gamma { pub fn new(a: f64, b: f64) -> Result<Gamma, ()> { if a <= 0.0 || b <= 0.0 { return Err(()); } Ok(Gamma { a, b }) } #[inline] pub fn pdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_pdf; gamma_pdf(x, self.a, self.b) } } use super::{Sample, CDF}; impl Sample for Gamma { #[inline] fn sample(&self, rng: &mut RGSLRng) -> f64 { use rgsl::randist::gamma::gamma; gamma(rng.get_gen(), self.a, self.b) } } impl CDF for Gamma { #[inline] fn cdf(&self, x: f64) -> f64
#[inline] fn inverse_cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_Pinv; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_Pinv(x, self.a, self.b) } }
{ use rgsl::randist::gamma::gamma_P; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_P(x, self.a, self.b) }
identifier_body
gamma.rs
use err::ErrMsg; use RGSLRng; #[derive(Debug, Clone)] pub struct
{ a: f64, b: f64, } impl Gamma { pub fn new(a: f64, b: f64) -> Result<Gamma, ()> { if a <= 0.0 || b <= 0.0 { return Err(()); } Ok(Gamma { a, b }) } #[inline] pub fn pdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_pdf; gamma_pdf(x, self.a, self.b) } } use super::{Sample, CDF}; impl Sample for Gamma { #[inline] fn sample(&self, rng: &mut RGSLRng) -> f64 { use rgsl::randist::gamma::gamma; gamma(rng.get_gen(), self.a, self.b) } } impl CDF for Gamma { #[inline] fn cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_P; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_P(x, self.a, self.b) } #[inline] fn inverse_cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_Pinv; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_Pinv(x, self.a, self.b) } }
Gamma
identifier_name
gamma.rs
use err::ErrMsg; use RGSLRng; #[derive(Debug, Clone)] pub struct Gamma { a: f64, b: f64, } impl Gamma { pub fn new(a: f64, b: f64) -> Result<Gamma, ()> { if a <= 0.0 || b <= 0.0 { return Err(()); } Ok(Gamma { a, b }) } #[inline] pub fn pdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_pdf; gamma_pdf(x, self.a, self.b)
use super::{Sample, CDF}; impl Sample for Gamma { #[inline] fn sample(&self, rng: &mut RGSLRng) -> f64 { use rgsl::randist::gamma::gamma; gamma(rng.get_gen(), self.a, self.b) } } impl CDF for Gamma { #[inline] fn cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_P; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_P(x, self.a, self.b) } #[inline] fn inverse_cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_Pinv; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_Pinv(x, self.a, self.b) } }
} }
random_line_split
gamma.rs
use err::ErrMsg; use RGSLRng; #[derive(Debug, Clone)] pub struct Gamma { a: f64, b: f64, } impl Gamma { pub fn new(a: f64, b: f64) -> Result<Gamma, ()> { if a <= 0.0 || b <= 0.0 { return Err(()); } Ok(Gamma { a, b }) } #[inline] pub fn pdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_pdf; gamma_pdf(x, self.a, self.b) } } use super::{Sample, CDF}; impl Sample for Gamma { #[inline] fn sample(&self, rng: &mut RGSLRng) -> f64 { use rgsl::randist::gamma::gamma; gamma(rng.get_gen(), self.a, self.b) } } impl CDF for Gamma { #[inline] fn cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_P; if x.is_sign_negative() { panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); } gamma_P(x, self.a, self.b) } #[inline] fn inverse_cdf(&self, x: f64) -> f64 { use rgsl::randist::gamma::gamma_Pinv; if x.is_sign_negative()
gamma_Pinv(x, self.a, self.b) } }
{ panic!(ErrMsg::PositiveReal.panic_msg_with_arg(&self)); }
conditional_block
regex.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use crate::reflection; use crate::utils; use crate::Predicate; /// An error that occurred during parsing or compiling a regular expression. pub type RegexError = regex::Error; /// Predicate that uses regex matching /// /// This is created by the `predicate::str::is_match`. #[derive(Debug, Clone)] pub struct RegexPredicate { re: regex::Regex, } impl RegexPredicate { /// Require a specific count of matches. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("T[a-z]*").unwrap().count(3); /// assert_eq!(true, predicate_fn.eval("One Two Three Two One")); /// assert_eq!(false, predicate_fn.eval("One Two Three")); /// ``` pub fn count(self, count: usize) -> RegexMatchesPredicate { RegexMatchesPredicate { re: self.re, count } } } impl Predicate<str> for RegexPredicate { fn eval(&self, variable: &str) -> bool { self.re.is_match(variable) } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) .map(|case| case.add_product(reflection::Product::new("var", variable.to_owned()))) } } impl reflection::PredicateReflection for RegexPredicate {} impl fmt::Display for RegexPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Predicate that checks for repeated patterns. /// /// This is created by `predicates::str::is_match(...).count`. #[derive(Debug, Clone)] pub struct RegexMatchesPredicate { re: regex::Regex, count: usize, } impl Predicate<str> for RegexMatchesPredicate { fn eval(&self, variable: &str) -> bool { self.re.find_iter(variable).count() == self.count } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { let actual_count = self.re.find_iter(variable).count(); let result = self.count == actual_count; if result == expected { Some( reflection::Case::new(Some(self), result) .add_product(reflection::Product::new("var", variable.to_owned())) .add_product(reflection::Product::new("actual count", actual_count)), ) } else
} } impl reflection::PredicateReflection for RegexMatchesPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("count", &self.count)]; Box::new(params.into_iter()) } } impl fmt::Display for RegexMatchesPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Creates a new `Predicate` that uses a regular expression to match the string. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("^Hello.*$").unwrap(); /// assert_eq!(true, predicate_fn.eval("Hello World")); /// assert_eq!(false, predicate_fn.eval("Food World")); /// ``` pub fn is_match<S>(pattern: S) -> Result<RegexPredicate, RegexError> where S: AsRef<str>, { regex::Regex::new(pattern.as_ref()).map(|re| RegexPredicate { re }) }
{ None }
conditional_block
regex.rs
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use crate::reflection; use crate::utils; use crate::Predicate; /// An error that occurred during parsing or compiling a regular expression. pub type RegexError = regex::Error; /// Predicate that uses regex matching /// /// This is created by the `predicate::str::is_match`. #[derive(Debug, Clone)] pub struct RegexPredicate { re: regex::Regex, } impl RegexPredicate { /// Require a specific count of matches. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("T[a-z]*").unwrap().count(3); /// assert_eq!(true, predicate_fn.eval("One Two Three Two One")); /// assert_eq!(false, predicate_fn.eval("One Two Three")); /// ``` pub fn count(self, count: usize) -> RegexMatchesPredicate { RegexMatchesPredicate { re: self.re, count } } } impl Predicate<str> for RegexPredicate { fn eval(&self, variable: &str) -> bool { self.re.is_match(variable) } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { utils::default_find_case(self, expected, variable) .map(|case| case.add_product(reflection::Product::new("var", variable.to_owned()))) } } impl reflection::PredicateReflection for RegexPredicate {} impl fmt::Display for RegexPredicate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Predicate that checks for repeated patterns. /// /// This is created by `predicates::str::is_match(...).count`. #[derive(Debug, Clone)] pub struct RegexMatchesPredicate { re: regex::Regex, count: usize, } impl Predicate<str> for RegexMatchesPredicate { fn eval(&self, variable: &str) -> bool { self.re.find_iter(variable).count() == self.count } fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> { let actual_count = self.re.find_iter(variable).count(); let result = self.count == actual_count; if result == expected { Some( reflection::Case::new(Some(self), result) .add_product(reflection::Product::new("var", variable.to_owned())) .add_product(reflection::Product::new("actual count", actual_count)), ) } else { None } } } impl reflection::PredicateReflection for RegexMatchesPredicate { fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> { let params = vec![reflection::Parameter::new("count", &self.count)]; Box::new(params.into_iter()) } } impl fmt::Display for RegexMatchesPredicate { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let palette = crate::Palette::current(); write!( f, "{}.{}({})", palette.var.paint("var"), palette.description.paint("is_match"), palette.expected.paint(&self.re), ) } } /// Creates a new `Predicate` that uses a regular expression to match the string. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::str::is_match("^Hello.*$").unwrap(); /// assert_eq!(true, predicate_fn.eval("Hello World")); /// assert_eq!(false, predicate_fn.eval("Food World")); /// ``` pub fn is_match<S>(pattern: S) -> Result<RegexPredicate, RegexError> where S: AsRef<str>, { regex::Regex::new(pattern.as_ref()).map(|re| RegexPredicate { re }) }
fmt
identifier_name