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
monad.rs
// Copyright 2012-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. trait vec_monad<A> { fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.extend(f(elt).into_iter()); } r } } trait option_monad<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String>
pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
{ x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) ) }
identifier_body
monad.rs
// Copyright 2012-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. trait vec_monad<A> { fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ;
fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.extend(f(elt).into_iter()); } r } } trait option_monad<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) ) } pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
} impl<A> vec_monad<A> for Vec<A> {
random_line_split
monad.rs
// Copyright 2012-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. trait vec_monad<A> { fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ; } impl<A> vec_monad<A> for Vec<A> { fn bind<B, F>(&self, mut f: F) -> Vec<B> where F: FnMut(&A) -> Vec<B> { let mut r = Vec::new(); for elt in self.iter() { r.extend(f(elt).into_iter()); } r } } trait option_monad<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B, F>(&self, f: F) -> Option<B> where F: FnOnce(&A) -> Option<B> { match *self { Some(ref a) => { f(a) } None =>
} } } fn transform(x: Option<int>) -> Option<String> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) ) } pub fn main() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), "hi!".to_string(), "hi!?".to_string())); }
{ None }
conditional_block
gecko_selector_impl.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::ToCss; use element_state::ElementState; use selector_impl::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable}; use selector_impl::PseudoElementCascadeType; use selectors::parser::{AttrSelector, ParserContext, SelectorImpl}; use std::fmt; use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GeckoSelectorImpl; /// NOTE: The boolean field represents whether this element is an anonymous box. /// /// This is just for convenience, instead of recomputing it. Also, note that /// Atom is always a static atom, so if space is a concern, we can use the /// raw pointer and use the lower bit to represent it without space overhead. /// /// FIXME(emilio): we know all these atoms are static. Patches are starting to /// pile up, but a further potential optimisation is generating bindings without /// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no /// longer depends on it), and using the raw *mut nsIAtom (properly asserting /// we're a static atom). /// /// This should allow us to avoid random FFI overhead when cloning/dropping /// pseudos. /// /// Also, we can further optimize PartialEq and hash comparing/hashing only the /// atoms. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct PseudoElement(Atom, bool); impl PseudoElement { #[inline] pub fn as_atom(&self) -> &Atom { &self.0 } #[inline] fn is_anon_box(&self) -> bool { self.1 } #[inline] pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self { if cfg!(debug_assertions) { // Do the check on debug regardless. match Self::from_atom(&*atom, true) { Some(pseudo) => { assert_eq!(pseudo.is_anon_box(), is_anon_box); return pseudo; } None => panic!("Unknown pseudo: {:?}", atom), } } PseudoElement(atom, is_anon_box) } #[inline] fn from_atom(atom: &WeakAtom, in_ua: bool) -> Option<Self> { macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ if atom == &*$atom { return Some(PseudoElement($atom, $is_anon_box)); } }} } include!("generated/gecko_pseudo_element_helper.rs"); None } #[inline] fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> { use std::ascii::AsciiExt; macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ if!$is_anon_box || in_ua_stylesheet { if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) { return Some(PseudoElement($atom, $is_anon_box)) } } }} } include!("generated/gecko_pseudo_element_helper.rs"); None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { // FIXME: why does the atom contain one colon? Pseudo-element has two debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) && !self.0.as_slice().starts_with(&[b':' as u16, b':' as u16])); try!(dest.write_char(':')); write!(dest, "{}", self.0) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum NonTSPseudoClass { AnyLink, Link, Visited, Active, Focus, Hover, Enabled, Disabled, Checked, Indeterminate, ReadWrite, ReadOnly, } impl ToCss for NonTSPseudoClass { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { use self::NonTSPseudoClass::*; dest.write_str(match *self { AnyLink => ":any-link", Link => ":link", Visited => ":visited", Active => ":active", Focus => ":focus", Hover => ":hover", Enabled => ":enabled", Disabled => ":disabled", Checked => ":checked", Indeterminate => ":indeterminate", ReadWrite => ":read-write", ReadOnly => ":read-only", }) } } impl NonTSPseudoClass { pub fn state_flag(&self) -> ElementState { use element_state::*; use self::NonTSPseudoClass::*; match *self { Active => IN_ACTIVE_STATE, Focus => IN_FOCUS_STATE, Hover => IN_HOVER_STATE, Enabled => IN_ENABLED_STATE, Disabled => IN_DISABLED_STATE, Checked => IN_CHECKED_STATE, Indeterminate => IN_INDETERMINATE_STATE, ReadOnly | ReadWrite => IN_READ_WRITE_STATE, AnyLink | Link | Visited => ElementState::empty(), } } } impl SelectorImpl for GeckoSelectorImpl { type AttrValue = Atom; type Identifier = Atom; type ClassName = Atom; type LocalName = Atom; type NamespacePrefix = Atom; type NamespaceUrl = Namespace; type BorrowedNamespaceUrl = WeakNamespace; type BorrowedLocalName = WeakAtom; type PseudoElement = PseudoElement; type NonTSPseudoClass = NonTSPseudoClass; fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool { attr_exists_selector_is_shareable(attr_selector) } fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>, value: &Self::AttrValue) -> bool { attr_equals_selector_is_shareable(attr_selector, value) } fn parse_non_ts_pseudo_class(_context: &ParserContext<Self>, name: &str) -> Result<NonTSPseudoClass, ()> { use self::NonTSPseudoClass::*; let pseudo_class = match_ignore_ascii_case! { name, "any-link" => AnyLink, "link" => Link, "visited" => Visited, "active" => Active, "focus" => Focus, "hover" => Hover, "enabled" => Enabled, "disabled" => Disabled, "checked" => Checked, "indeterminate" => Indeterminate, "read-write" => ReadWrite, "read-only" => ReadOnly, _ => return Err(()) }; Ok(pseudo_class) } fn parse_pseudo_element(context: &ParserContext<Self>, name: &str) -> Result<PseudoElement, ()> { match PseudoElement::from_slice(name, context.in_user_agent_stylesheet) { Some(pseudo) => Ok(pseudo), None => Err(()), } } } impl GeckoSelectorImpl { #[inline] pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType { if Self::pseudo_is_before_or_after(pseudo) { return PseudoElementCascadeType::Eager } if pseudo.is_anon_box() { return PseudoElementCascadeType::Precomputed } PseudoElementCascadeType::Lazy } #[inline] pub fn each_pseudo_element<F>(mut fun: F) where F: FnMut(PseudoElement) { macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ fun(PseudoElement($atom, $is_anon_box)); }} } include!("generated/gecko_pseudo_element_helper.rs") } #[inline] pub fn
(pseudo: &PseudoElement) -> bool { *pseudo.as_atom() == atom!(":before") || *pseudo.as_atom() == atom!(":after") } #[inline] pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState { pc.state_flag() } }
pseudo_is_before_or_after
identifier_name
gecko_selector_impl.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::ToCss; use element_state::ElementState; use selector_impl::{attr_equals_selector_is_shareable, attr_exists_selector_is_shareable}; use selector_impl::PseudoElementCascadeType; use selectors::parser::{AttrSelector, ParserContext, SelectorImpl}; use std::fmt; use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GeckoSelectorImpl; /// NOTE: The boolean field represents whether this element is an anonymous box. /// /// This is just for convenience, instead of recomputing it. Also, note that /// Atom is always a static atom, so if space is a concern, we can use the /// raw pointer and use the lower bit to represent it without space overhead. /// /// FIXME(emilio): we know all these atoms are static. Patches are starting to /// pile up, but a further potential optimisation is generating bindings without /// `-no-gen-bitfield-methods` (that was removed to compile on stable, but it no /// longer depends on it), and using the raw *mut nsIAtom (properly asserting /// we're a static atom). /// /// This should allow us to avoid random FFI overhead when cloning/dropping /// pseudos. /// /// Also, we can further optimize PartialEq and hash comparing/hashing only the /// atoms. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct PseudoElement(Atom, bool); impl PseudoElement { #[inline] pub fn as_atom(&self) -> &Atom { &self.0 } #[inline] fn is_anon_box(&self) -> bool { self.1 } #[inline] pub fn from_atom_unchecked(atom: Atom, is_anon_box: bool) -> Self { if cfg!(debug_assertions) { // Do the check on debug regardless. match Self::from_atom(&*atom, true) { Some(pseudo) => { assert_eq!(pseudo.is_anon_box(), is_anon_box); return pseudo; } None => panic!("Unknown pseudo: {:?}", atom), } } PseudoElement(atom, is_anon_box) } #[inline] fn from_atom(atom: &WeakAtom, in_ua: bool) -> Option<Self> { macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ if atom == &*$atom { return Some(PseudoElement($atom, $is_anon_box)); } }} } include!("generated/gecko_pseudo_element_helper.rs"); None } #[inline] fn from_slice(s: &str, in_ua_stylesheet: bool) -> Option<Self> { use std::ascii::AsciiExt; macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ if!$is_anon_box || in_ua_stylesheet { if s.eq_ignore_ascii_case(&$pseudo_str_with_colon[1..]) { return Some(PseudoElement($atom, $is_anon_box)) } } }} } include!("generated/gecko_pseudo_element_helper.rs"); None } } impl ToCss for PseudoElement { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { // FIXME: why does the atom contain one colon? Pseudo-element has two debug_assert!(self.0.as_slice().starts_with(&[b':' as u16]) && !self.0.as_slice().starts_with(&[b':' as u16, b':' as u16])); try!(dest.write_char(':')); write!(dest, "{}", self.0) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum NonTSPseudoClass { AnyLink, Link, Visited, Active, Focus, Hover, Enabled, Disabled, Checked, Indeterminate, ReadWrite, ReadOnly, } impl ToCss for NonTSPseudoClass { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { use self::NonTSPseudoClass::*; dest.write_str(match *self { AnyLink => ":any-link", Link => ":link", Visited => ":visited", Active => ":active", Focus => ":focus", Hover => ":hover", Enabled => ":enabled", Disabled => ":disabled", Checked => ":checked", Indeterminate => ":indeterminate", ReadWrite => ":read-write", ReadOnly => ":read-only", }) } } impl NonTSPseudoClass { pub fn state_flag(&self) -> ElementState { use element_state::*; use self::NonTSPseudoClass::*; match *self { Active => IN_ACTIVE_STATE, Focus => IN_FOCUS_STATE, Hover => IN_HOVER_STATE, Enabled => IN_ENABLED_STATE, Disabled => IN_DISABLED_STATE, Checked => IN_CHECKED_STATE, Indeterminate => IN_INDETERMINATE_STATE, ReadOnly | ReadWrite => IN_READ_WRITE_STATE, AnyLink | Link | Visited => ElementState::empty(), } } } impl SelectorImpl for GeckoSelectorImpl { type AttrValue = Atom; type Identifier = Atom; type ClassName = Atom; type LocalName = Atom; type NamespacePrefix = Atom; type NamespaceUrl = Namespace; type BorrowedNamespaceUrl = WeakNamespace; type BorrowedLocalName = WeakAtom; type PseudoElement = PseudoElement; type NonTSPseudoClass = NonTSPseudoClass; fn attr_exists_selector_is_shareable(attr_selector: &AttrSelector<Self>) -> bool { attr_exists_selector_is_shareable(attr_selector) } fn attr_equals_selector_is_shareable(attr_selector: &AttrSelector<Self>, value: &Self::AttrValue) -> bool { attr_equals_selector_is_shareable(attr_selector, value) } fn parse_non_ts_pseudo_class(_context: &ParserContext<Self>, name: &str) -> Result<NonTSPseudoClass, ()> { use self::NonTSPseudoClass::*; let pseudo_class = match_ignore_ascii_case! { name, "any-link" => AnyLink, "link" => Link, "visited" => Visited, "active" => Active, "focus" => Focus, "hover" => Hover, "enabled" => Enabled, "disabled" => Disabled, "checked" => Checked, "indeterminate" => Indeterminate, "read-write" => ReadWrite, "read-only" => ReadOnly, _ => return Err(()) };
fn parse_pseudo_element(context: &ParserContext<Self>, name: &str) -> Result<PseudoElement, ()> { match PseudoElement::from_slice(name, context.in_user_agent_stylesheet) { Some(pseudo) => Ok(pseudo), None => Err(()), } } } impl GeckoSelectorImpl { #[inline] pub fn pseudo_element_cascade_type(pseudo: &PseudoElement) -> PseudoElementCascadeType { if Self::pseudo_is_before_or_after(pseudo) { return PseudoElementCascadeType::Eager } if pseudo.is_anon_box() { return PseudoElementCascadeType::Precomputed } PseudoElementCascadeType::Lazy } #[inline] pub fn each_pseudo_element<F>(mut fun: F) where F: FnMut(PseudoElement) { macro_rules! pseudo_element { ($pseudo_str_with_colon:expr, $atom:expr, $is_anon_box:expr) => {{ fun(PseudoElement($atom, $is_anon_box)); }} } include!("generated/gecko_pseudo_element_helper.rs") } #[inline] pub fn pseudo_is_before_or_after(pseudo: &PseudoElement) -> bool { *pseudo.as_atom() == atom!(":before") || *pseudo.as_atom() == atom!(":after") } #[inline] pub fn pseudo_class_state_flag(pc: &NonTSPseudoClass) -> ElementState { pc.state_flag() } }
Ok(pseudo_class) }
random_line_split
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! On-demand chain requests over LES. This is a major building block for RPCs. //! The request service is implemented using Futures. Higher level request handlers //! will take the raw data received here and extract meaningful results from it. use std::collections::HashMap; use std::marker::PhantomData; use std::sync::Arc; use ethcore::executed::{Executed, ExecutionError}; use futures::{Async, Poll, Future}; use futures::sync::oneshot::{self, Sender, Receiver, Canceled}; use network::PeerId; use parking_lot::{RwLock, Mutex}; use net::{ self, Handler, PeerStatus, Status, Capabilities, Announcement, EventContext, BasicContext, ReqId, }; use cache::Cache; use request::{self as basic_request, Request as NetworkRequest}; use self::request::CheckedRequest; pub use self::request::{Request, Response, HeaderRef}; #[cfg(test)] mod tests; pub mod request; /// The result of execution pub type ExecutionResult = Result<Executed, ExecutionError>; // relevant peer info. struct Peer { status: Status, capabilities: Capabilities, } impl Peer { // whether this peer can fulfill the necessary capabilities for the given // request. fn can_fulfill(&self, request: &Capabilities) -> bool { let local_caps = &self.capabilities; let can_serve_since = |req, local| { match (req, local) { (Some(request_block), Some(serve_since)) => request_block >= serve_since, (Some(_), None) => false, (None, _) => true, } }; local_caps.serve_headers >= request.serve_headers && can_serve_since(request.serve_chain_since, local_caps.serve_chain_since) && can_serve_since(request.serve_state_since, local_caps.serve_state_since) } } // Attempted request info and sender to put received value. struct Pending { requests: basic_request::Batch<CheckedRequest>, net_requests: basic_request::Batch<NetworkRequest>, required_capabilities: Capabilities, responses: Vec<Response>, sender: oneshot::Sender<Vec<Response>>, } impl Pending { // answer as many of the given requests from the supplied cache as possible. // TODO: support re-shuffling. fn answer_from_cache(&mut self, cache: &Mutex<Cache>) { while!self.requests.is_complete() { let idx = self.requests.num_answered(); match self.requests[idx].respond_local(cache) { Some(response) => { self.requests.supply_response_unchecked(&response); self.update_header_refs(idx, &response); self.responses.push(response); } None => break, } } } // update header refs if the given response contains a header future requests require for // verification. // `idx` is the index of the request the response corresponds to. fn update_header_refs(&mut self, idx: usize, response: &Response) { match *response { Response::HeaderByHash(ref hdr) => { // fill the header for all requests waiting on this one. // TODO: could be faster if we stored a map usize => Vec<usize> // but typical use just has one header request that others // depend on. for r in self.requests.iter_mut().skip(idx + 1) { if r.needs_header().map_or(false, |(i, _)| i == idx) { r.provide_header(hdr.clone()) } } } _ => {}, // no other responses produce headers. } } // supply a response. fn supply_response(&mut self, cache: &Mutex<Cache>, response: &basic_request::Response) -> Result<(), basic_request::ResponseError<self::request::Error>> { match self.requests.supply_response(&cache, response) { Ok(response) => { let idx = self.responses.len(); self.update_header_refs(idx, &response); self.responses.push(response); Ok(()) } Err(e) => Err(e), } } // if the requests are complete, send the result and consume self. fn try_complete(self) -> Option<Self> { if self.requests.is_complete() { let _ = self.sender.send(self.responses); None } else { Some(self) } } fn fill_unanswered(&mut self) { self.requests.fill_unanswered(); } // update the cached network requests. fn update_net_requests(&mut self) { use request::IncompleteRequest; let mut builder = basic_request::Builder::default(); let num_answered = self.requests.num_answered(); let mut mapping = move |idx| idx - num_answered; for request in self.requests.iter().skip(num_answered) { let mut net_req = request.clone().into_net_request(); // all back-references with request index less than `num_answered` have // been filled by now. all remaining requests point to nothing earlier // than the next unanswered request. net_req.adjust_refs(&mut mapping); builder.push(net_req) .expect("all back-references to answered requests have been filled; qed"); } // update pending fields. let capabilities = guess_capabilities(&self.requests[num_answered..]); self.net_requests = builder.build(); self.required_capabilities = capabilities; } } // helper to guess capabilities required for a given batch of network requests. fn guess_capabilities(requests: &[CheckedRequest]) -> Capabilities { let mut caps = Capabilities { serve_headers: false, serve_chain_since: None, serve_state_since: None, tx_relay: false, }; let update_since = |current: &mut Option<u64>, new| *current = match *current { Some(x) => Some(::std::cmp::min(x, new)), None => Some(new), }; for request in requests { match *request { // TODO: might be worth returning a required block number for this also. CheckedRequest::HeaderProof(_, _) => caps.serve_headers = true, CheckedRequest::HeaderByHash(_, _) => caps.serve_headers = true, CheckedRequest::TransactionIndex(_, _) => {} // hashes yield no info. CheckedRequest::Signal(_, _) => caps.serve_headers = true, CheckedRequest::Body(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Receipts(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Account(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, CheckedRequest::Code(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, CheckedRequest::Execution(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, } } caps } /// A future extracting the concrete output type of the generic adapter /// from a vector of responses. pub struct OnResponses<T: request::RequestAdapter> { receiver: Receiver<Vec<Response>>, _marker: PhantomData<T>, } impl<T: request::RequestAdapter> Future for OnResponses<T> { type Item = T::Out; type Error = Canceled; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.receiver.poll().map(|async| async.map(T::extract_from)) } } /// On demand request service. See module docs for more details. /// Accumulates info about all peers' capabilities and dispatches /// requests to them accordingly. // lock in declaration order. pub struct OnDemand { pending: RwLock<Vec<Pending>>, peers: RwLock<HashMap<PeerId, Peer>>, in_transit: RwLock<HashMap<ReqId, Pending>>, cache: Arc<Mutex<Cache>>, no_immediate_dispatch: bool, } impl OnDemand { /// Create a new `OnDemand` service with the given cache. pub fn new(cache: Arc<Mutex<Cache>>) -> Self { OnDemand { pending: RwLock::new(Vec::new()), peers: RwLock::new(HashMap::new()), in_transit: RwLock::new(HashMap::new()), cache: cache, no_immediate_dispatch: false, } } // make a test version: this doesn't dispatch pending requests // until you trigger it manually. #[cfg(test)] fn
(cache: Arc<Mutex<Cache>>) -> Self { let mut me = OnDemand::new(cache); me.no_immediate_dispatch = true; me } /// Submit a vector of requests to be processed together. /// /// Fails if back-references are not coherent. /// The returned vector of responses will correspond to the requests exactly. pub fn request_raw(&self, ctx: &BasicContext, requests: Vec<Request>) -> Result<Receiver<Vec<Response>>, basic_request::NoSuchOutput> { let (sender, receiver) = oneshot::channel(); if requests.is_empty() { assert!(sender.send(Vec::new()).is_ok(), "receiver still in scope; qed"); return Ok(receiver); } let mut builder = basic_request::Builder::default(); let responses = Vec::with_capacity(requests.len()); let mut header_producers = HashMap::new(); for (i, request) in requests.into_iter().enumerate() { let request = CheckedRequest::from(request); // ensure that all requests needing headers will get them. if let Some((idx, field)) = request.needs_header() { // a request chain with a header back-reference is valid only if it both // points to a request that returns a header and has the same back-reference // for the block hash. match header_producers.get(&idx) { Some(ref f) if &field == *f => {} _ => return Err(basic_request::NoSuchOutput), } } if let CheckedRequest::HeaderByHash(ref req, _) = request { header_producers.insert(i, req.0.clone()); } builder.push(request)?; } let requests = builder.build(); let net_requests = requests.clone().map_requests(|req| req.into_net_request()); let capabilities = guess_capabilities(requests.requests()); self.submit_pending(ctx, Pending { requests: requests, net_requests: net_requests, required_capabilities: capabilities, responses: responses, sender: sender, }); Ok(receiver) } /// Submit a strongly-typed batch of requests. /// /// Fails if back-reference are not coherent. pub fn request<T>(&self, ctx: &BasicContext, requests: T) -> Result<OnResponses<T>, basic_request::NoSuchOutput> where T: request::RequestAdapter { self.request_raw(ctx, requests.make_requests()).map(|recv| OnResponses { receiver: recv, _marker: PhantomData, }) } // maybe dispatch pending requests. // sometimes fn attempt_dispatch(&self, ctx: &BasicContext) { if!self.no_immediate_dispatch { self.dispatch_pending(ctx) } } // dispatch pending requests, and discard those for which the corresponding // receiver has been dropped. fn dispatch_pending(&self, ctx: &BasicContext) { // wrapper future for calling `poll_cancel` on our `Senders` to preserve // the invariant that it's always within a task. struct CheckHangup<'a, T: 'a>(&'a mut Sender<T>); impl<'a, T: 'a> Future for CheckHangup<'a, T> { type Item = bool; type Error = (); fn poll(&mut self) -> Poll<bool, ()> { Ok(Async::Ready(match self.0.poll_cancel() { Ok(Async::NotReady) => false, // hasn't hung up. _ => true, // has hung up. })) } } // check whether a sender's hung up (using `wait` to preserve the task invariant) // returns true if has hung up, false otherwise. fn check_hangup<T>(send: &mut Sender<T>) -> bool { CheckHangup(send).wait().expect("CheckHangup always returns ok; qed") } if self.pending.read().is_empty() { return } let mut pending = self.pending.write(); debug!(target: "on_demand", "Attempting to dispatch {} pending requests", pending.len()); // iterate over all pending requests, and check them for hang-up. // then, try and find a peer who can serve it. let peers = self.peers.read(); *pending = ::std::mem::replace(&mut *pending, Vec::new()).into_iter() .filter_map(|mut pending| match check_hangup(&mut pending.sender) { false => Some(pending), true => None, }) .filter_map(|pending| { for (peer_id, peer) in peers.iter() { //.shuffle? // TODO: see which requests can be answered by the cache? if!peer.can_fulfill(&pending.required_capabilities) { continue } match ctx.request_from(*peer_id, pending.net_requests.clone()) { Ok(req_id) => { trace!(target: "on_demand", "Dispatched request {} to peer {}", req_id, peer_id); self.in_transit.write().insert(req_id, pending); return None } Err(net::Error::NoCredits) | Err(net::Error::NotServer) => {} Err(e) => debug!(target: "on_demand", "Error dispatching request to peer: {}", e), } } // TODO: maximum number of failures _when we have peers_. Some(pending) }) .collect(); // `pending` now contains all requests we couldn't dispatch. debug!(target: "on_demand", "Was unable to dispatch {} requests.", pending.len()); } // submit a pending request set. attempts to answer from cache before // going to the network. if complete, sends response and consumes the struct. fn submit_pending(&self, ctx: &BasicContext, mut pending: Pending) { // answer as many requests from cache as we can, and schedule for dispatch // if incomplete. pending.answer_from_cache(&*self.cache); if let Some(mut pending) = pending.try_complete() { pending.update_net_requests(); self.pending.write().push(pending); self.attempt_dispatch(ctx); } } } impl Handler for OnDemand { fn on_connect( &self, ctx: &EventContext, status: &Status, capabilities: &Capabilities ) -> PeerStatus { self.peers.write().insert( ctx.peer(), Peer { status: status.clone(), capabilities: capabilities.clone() } ); self.attempt_dispatch(ctx.as_basic()); PeerStatus::Kept } fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { self.peers.write().remove(&ctx.peer()); let ctx = ctx.as_basic(); { let mut pending = self.pending.write(); for unfulfilled in unfulfilled { if let Some(unfulfilled) = self.in_transit.write().remove(unfulfilled) { trace!(target: "on_demand", "Attempting to reassign dropped request"); pending.push(unfulfilled); } } } self.attempt_dispatch(ctx); } fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) { { let mut peers = self.peers.write(); if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) { peer.status.update_from(&announcement); peer.capabilities.update_from(&announcement); } } self.attempt_dispatch(ctx.as_basic()); } fn on_responses(&self, ctx: &EventContext, req_id: ReqId, responses: &[basic_request::Response]) { let mut pending = match self.in_transit.write().remove(&req_id) { Some(req) => req, None => return, }; // for each incoming response // 1. ensure verification data filled. // 2. pending.requests.supply_response // 3. if extracted on-demand response, keep it for later. for response in responses { if let Err(e) = pending.supply_response(&*self.cache, response) { let peer = ctx.peer(); debug!(target: "on_demand", "Peer {} gave bad response: {:?}", peer, e); ctx.disable_peer(peer); break; } } pending.fill_unanswered(); self.submit_pending(ctx.as_basic(), pending); } fn tick(&self, ctx: &BasicContext) { self.attempt_dispatch(ctx) } }
new_test
identifier_name
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! On-demand chain requests over LES. This is a major building block for RPCs. //! The request service is implemented using Futures. Higher level request handlers //! will take the raw data received here and extract meaningful results from it. use std::collections::HashMap; use std::marker::PhantomData; use std::sync::Arc; use ethcore::executed::{Executed, ExecutionError}; use futures::{Async, Poll, Future}; use futures::sync::oneshot::{self, Sender, Receiver, Canceled}; use network::PeerId; use parking_lot::{RwLock, Mutex}; use net::{ self, Handler, PeerStatus, Status, Capabilities, Announcement, EventContext, BasicContext, ReqId, }; use cache::Cache; use request::{self as basic_request, Request as NetworkRequest}; use self::request::CheckedRequest; pub use self::request::{Request, Response, HeaderRef}; #[cfg(test)] mod tests; pub mod request; /// The result of execution pub type ExecutionResult = Result<Executed, ExecutionError>; // relevant peer info. struct Peer { status: Status, capabilities: Capabilities, } impl Peer { // whether this peer can fulfill the necessary capabilities for the given // request. fn can_fulfill(&self, request: &Capabilities) -> bool { let local_caps = &self.capabilities; let can_serve_since = |req, local| { match (req, local) { (Some(request_block), Some(serve_since)) => request_block >= serve_since, (Some(_), None) => false, (None, _) => true, } }; local_caps.serve_headers >= request.serve_headers && can_serve_since(request.serve_chain_since, local_caps.serve_chain_since) && can_serve_since(request.serve_state_since, local_caps.serve_state_since) } } // Attempted request info and sender to put received value. struct Pending { requests: basic_request::Batch<CheckedRequest>, net_requests: basic_request::Batch<NetworkRequest>, required_capabilities: Capabilities, responses: Vec<Response>, sender: oneshot::Sender<Vec<Response>>, } impl Pending { // answer as many of the given requests from the supplied cache as possible. // TODO: support re-shuffling. fn answer_from_cache(&mut self, cache: &Mutex<Cache>) { while!self.requests.is_complete() { let idx = self.requests.num_answered(); match self.requests[idx].respond_local(cache) { Some(response) => { self.requests.supply_response_unchecked(&response); self.update_header_refs(idx, &response); self.responses.push(response); } None => break, } } } // update header refs if the given response contains a header future requests require for // verification. // `idx` is the index of the request the response corresponds to. fn update_header_refs(&mut self, idx: usize, response: &Response) { match *response { Response::HeaderByHash(ref hdr) => { // fill the header for all requests waiting on this one. // TODO: could be faster if we stored a map usize => Vec<usize> // but typical use just has one header request that others // depend on. for r in self.requests.iter_mut().skip(idx + 1) { if r.needs_header().map_or(false, |(i, _)| i == idx) { r.provide_header(hdr.clone()) } } } _ => {}, // no other responses produce headers. } } // supply a response. fn supply_response(&mut self, cache: &Mutex<Cache>, response: &basic_request::Response) -> Result<(), basic_request::ResponseError<self::request::Error>> { match self.requests.supply_response(&cache, response) { Ok(response) => { let idx = self.responses.len(); self.update_header_refs(idx, &response); self.responses.push(response); Ok(()) } Err(e) => Err(e), } } // if the requests are complete, send the result and consume self. fn try_complete(self) -> Option<Self> { if self.requests.is_complete() { let _ = self.sender.send(self.responses); None } else { Some(self) } } fn fill_unanswered(&mut self) { self.requests.fill_unanswered(); } // update the cached network requests. fn update_net_requests(&mut self) { use request::IncompleteRequest; let mut builder = basic_request::Builder::default(); let num_answered = self.requests.num_answered(); let mut mapping = move |idx| idx - num_answered; for request in self.requests.iter().skip(num_answered) { let mut net_req = request.clone().into_net_request(); // all back-references with request index less than `num_answered` have // been filled by now. all remaining requests point to nothing earlier // than the next unanswered request. net_req.adjust_refs(&mut mapping); builder.push(net_req) .expect("all back-references to answered requests have been filled; qed"); } // update pending fields. let capabilities = guess_capabilities(&self.requests[num_answered..]); self.net_requests = builder.build(); self.required_capabilities = capabilities; } } // helper to guess capabilities required for a given batch of network requests. fn guess_capabilities(requests: &[CheckedRequest]) -> Capabilities { let mut caps = Capabilities { serve_headers: false, serve_chain_since: None, serve_state_since: None, tx_relay: false, }; let update_since = |current: &mut Option<u64>, new| *current = match *current { Some(x) => Some(::std::cmp::min(x, new)), None => Some(new), }; for request in requests { match *request { // TODO: might be worth returning a required block number for this also. CheckedRequest::HeaderProof(_, _) => caps.serve_headers = true, CheckedRequest::HeaderByHash(_, _) => caps.serve_headers = true, CheckedRequest::TransactionIndex(_, _) => {} // hashes yield no info. CheckedRequest::Signal(_, _) => caps.serve_headers = true, CheckedRequest::Body(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Receipts(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Account(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, CheckedRequest::Code(ref req, _) => if let Ok(ref hdr) = req.header.as_ref()
, CheckedRequest::Execution(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, } } caps } /// A future extracting the concrete output type of the generic adapter /// from a vector of responses. pub struct OnResponses<T: request::RequestAdapter> { receiver: Receiver<Vec<Response>>, _marker: PhantomData<T>, } impl<T: request::RequestAdapter> Future for OnResponses<T> { type Item = T::Out; type Error = Canceled; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.receiver.poll().map(|async| async.map(T::extract_from)) } } /// On demand request service. See module docs for more details. /// Accumulates info about all peers' capabilities and dispatches /// requests to them accordingly. // lock in declaration order. pub struct OnDemand { pending: RwLock<Vec<Pending>>, peers: RwLock<HashMap<PeerId, Peer>>, in_transit: RwLock<HashMap<ReqId, Pending>>, cache: Arc<Mutex<Cache>>, no_immediate_dispatch: bool, } impl OnDemand { /// Create a new `OnDemand` service with the given cache. pub fn new(cache: Arc<Mutex<Cache>>) -> Self { OnDemand { pending: RwLock::new(Vec::new()), peers: RwLock::new(HashMap::new()), in_transit: RwLock::new(HashMap::new()), cache: cache, no_immediate_dispatch: false, } } // make a test version: this doesn't dispatch pending requests // until you trigger it manually. #[cfg(test)] fn new_test(cache: Arc<Mutex<Cache>>) -> Self { let mut me = OnDemand::new(cache); me.no_immediate_dispatch = true; me } /// Submit a vector of requests to be processed together. /// /// Fails if back-references are not coherent. /// The returned vector of responses will correspond to the requests exactly. pub fn request_raw(&self, ctx: &BasicContext, requests: Vec<Request>) -> Result<Receiver<Vec<Response>>, basic_request::NoSuchOutput> { let (sender, receiver) = oneshot::channel(); if requests.is_empty() { assert!(sender.send(Vec::new()).is_ok(), "receiver still in scope; qed"); return Ok(receiver); } let mut builder = basic_request::Builder::default(); let responses = Vec::with_capacity(requests.len()); let mut header_producers = HashMap::new(); for (i, request) in requests.into_iter().enumerate() { let request = CheckedRequest::from(request); // ensure that all requests needing headers will get them. if let Some((idx, field)) = request.needs_header() { // a request chain with a header back-reference is valid only if it both // points to a request that returns a header and has the same back-reference // for the block hash. match header_producers.get(&idx) { Some(ref f) if &field == *f => {} _ => return Err(basic_request::NoSuchOutput), } } if let CheckedRequest::HeaderByHash(ref req, _) = request { header_producers.insert(i, req.0.clone()); } builder.push(request)?; } let requests = builder.build(); let net_requests = requests.clone().map_requests(|req| req.into_net_request()); let capabilities = guess_capabilities(requests.requests()); self.submit_pending(ctx, Pending { requests: requests, net_requests: net_requests, required_capabilities: capabilities, responses: responses, sender: sender, }); Ok(receiver) } /// Submit a strongly-typed batch of requests. /// /// Fails if back-reference are not coherent. pub fn request<T>(&self, ctx: &BasicContext, requests: T) -> Result<OnResponses<T>, basic_request::NoSuchOutput> where T: request::RequestAdapter { self.request_raw(ctx, requests.make_requests()).map(|recv| OnResponses { receiver: recv, _marker: PhantomData, }) } // maybe dispatch pending requests. // sometimes fn attempt_dispatch(&self, ctx: &BasicContext) { if!self.no_immediate_dispatch { self.dispatch_pending(ctx) } } // dispatch pending requests, and discard those for which the corresponding // receiver has been dropped. fn dispatch_pending(&self, ctx: &BasicContext) { // wrapper future for calling `poll_cancel` on our `Senders` to preserve // the invariant that it's always within a task. struct CheckHangup<'a, T: 'a>(&'a mut Sender<T>); impl<'a, T: 'a> Future for CheckHangup<'a, T> { type Item = bool; type Error = (); fn poll(&mut self) -> Poll<bool, ()> { Ok(Async::Ready(match self.0.poll_cancel() { Ok(Async::NotReady) => false, // hasn't hung up. _ => true, // has hung up. })) } } // check whether a sender's hung up (using `wait` to preserve the task invariant) // returns true if has hung up, false otherwise. fn check_hangup<T>(send: &mut Sender<T>) -> bool { CheckHangup(send).wait().expect("CheckHangup always returns ok; qed") } if self.pending.read().is_empty() { return } let mut pending = self.pending.write(); debug!(target: "on_demand", "Attempting to dispatch {} pending requests", pending.len()); // iterate over all pending requests, and check them for hang-up. // then, try and find a peer who can serve it. let peers = self.peers.read(); *pending = ::std::mem::replace(&mut *pending, Vec::new()).into_iter() .filter_map(|mut pending| match check_hangup(&mut pending.sender) { false => Some(pending), true => None, }) .filter_map(|pending| { for (peer_id, peer) in peers.iter() { //.shuffle? // TODO: see which requests can be answered by the cache? if!peer.can_fulfill(&pending.required_capabilities) { continue } match ctx.request_from(*peer_id, pending.net_requests.clone()) { Ok(req_id) => { trace!(target: "on_demand", "Dispatched request {} to peer {}", req_id, peer_id); self.in_transit.write().insert(req_id, pending); return None } Err(net::Error::NoCredits) | Err(net::Error::NotServer) => {} Err(e) => debug!(target: "on_demand", "Error dispatching request to peer: {}", e), } } // TODO: maximum number of failures _when we have peers_. Some(pending) }) .collect(); // `pending` now contains all requests we couldn't dispatch. debug!(target: "on_demand", "Was unable to dispatch {} requests.", pending.len()); } // submit a pending request set. attempts to answer from cache before // going to the network. if complete, sends response and consumes the struct. fn submit_pending(&self, ctx: &BasicContext, mut pending: Pending) { // answer as many requests from cache as we can, and schedule for dispatch // if incomplete. pending.answer_from_cache(&*self.cache); if let Some(mut pending) = pending.try_complete() { pending.update_net_requests(); self.pending.write().push(pending); self.attempt_dispatch(ctx); } } } impl Handler for OnDemand { fn on_connect( &self, ctx: &EventContext, status: &Status, capabilities: &Capabilities ) -> PeerStatus { self.peers.write().insert( ctx.peer(), Peer { status: status.clone(), capabilities: capabilities.clone() } ); self.attempt_dispatch(ctx.as_basic()); PeerStatus::Kept } fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { self.peers.write().remove(&ctx.peer()); let ctx = ctx.as_basic(); { let mut pending = self.pending.write(); for unfulfilled in unfulfilled { if let Some(unfulfilled) = self.in_transit.write().remove(unfulfilled) { trace!(target: "on_demand", "Attempting to reassign dropped request"); pending.push(unfulfilled); } } } self.attempt_dispatch(ctx); } fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) { { let mut peers = self.peers.write(); if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) { peer.status.update_from(&announcement); peer.capabilities.update_from(&announcement); } } self.attempt_dispatch(ctx.as_basic()); } fn on_responses(&self, ctx: &EventContext, req_id: ReqId, responses: &[basic_request::Response]) { let mut pending = match self.in_transit.write().remove(&req_id) { Some(req) => req, None => return, }; // for each incoming response // 1. ensure verification data filled. // 2. pending.requests.supply_response // 3. if extracted on-demand response, keep it for later. for response in responses { if let Err(e) = pending.supply_response(&*self.cache, response) { let peer = ctx.peer(); debug!(target: "on_demand", "Peer {} gave bad response: {:?}", peer, e); ctx.disable_peer(peer); break; } } pending.fill_unanswered(); self.submit_pending(ctx.as_basic(), pending); } fn tick(&self, ctx: &BasicContext) { self.attempt_dispatch(ctx) } }
{ update_since(&mut caps.serve_state_since, hdr.number()); }
conditional_block
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! On-demand chain requests over LES. This is a major building block for RPCs. //! The request service is implemented using Futures. Higher level request handlers //! will take the raw data received here and extract meaningful results from it. use std::collections::HashMap; use std::marker::PhantomData; use std::sync::Arc; use ethcore::executed::{Executed, ExecutionError}; use futures::{Async, Poll, Future};
use net::{ self, Handler, PeerStatus, Status, Capabilities, Announcement, EventContext, BasicContext, ReqId, }; use cache::Cache; use request::{self as basic_request, Request as NetworkRequest}; use self::request::CheckedRequest; pub use self::request::{Request, Response, HeaderRef}; #[cfg(test)] mod tests; pub mod request; /// The result of execution pub type ExecutionResult = Result<Executed, ExecutionError>; // relevant peer info. struct Peer { status: Status, capabilities: Capabilities, } impl Peer { // whether this peer can fulfill the necessary capabilities for the given // request. fn can_fulfill(&self, request: &Capabilities) -> bool { let local_caps = &self.capabilities; let can_serve_since = |req, local| { match (req, local) { (Some(request_block), Some(serve_since)) => request_block >= serve_since, (Some(_), None) => false, (None, _) => true, } }; local_caps.serve_headers >= request.serve_headers && can_serve_since(request.serve_chain_since, local_caps.serve_chain_since) && can_serve_since(request.serve_state_since, local_caps.serve_state_since) } } // Attempted request info and sender to put received value. struct Pending { requests: basic_request::Batch<CheckedRequest>, net_requests: basic_request::Batch<NetworkRequest>, required_capabilities: Capabilities, responses: Vec<Response>, sender: oneshot::Sender<Vec<Response>>, } impl Pending { // answer as many of the given requests from the supplied cache as possible. // TODO: support re-shuffling. fn answer_from_cache(&mut self, cache: &Mutex<Cache>) { while!self.requests.is_complete() { let idx = self.requests.num_answered(); match self.requests[idx].respond_local(cache) { Some(response) => { self.requests.supply_response_unchecked(&response); self.update_header_refs(idx, &response); self.responses.push(response); } None => break, } } } // update header refs if the given response contains a header future requests require for // verification. // `idx` is the index of the request the response corresponds to. fn update_header_refs(&mut self, idx: usize, response: &Response) { match *response { Response::HeaderByHash(ref hdr) => { // fill the header for all requests waiting on this one. // TODO: could be faster if we stored a map usize => Vec<usize> // but typical use just has one header request that others // depend on. for r in self.requests.iter_mut().skip(idx + 1) { if r.needs_header().map_or(false, |(i, _)| i == idx) { r.provide_header(hdr.clone()) } } } _ => {}, // no other responses produce headers. } } // supply a response. fn supply_response(&mut self, cache: &Mutex<Cache>, response: &basic_request::Response) -> Result<(), basic_request::ResponseError<self::request::Error>> { match self.requests.supply_response(&cache, response) { Ok(response) => { let idx = self.responses.len(); self.update_header_refs(idx, &response); self.responses.push(response); Ok(()) } Err(e) => Err(e), } } // if the requests are complete, send the result and consume self. fn try_complete(self) -> Option<Self> { if self.requests.is_complete() { let _ = self.sender.send(self.responses); None } else { Some(self) } } fn fill_unanswered(&mut self) { self.requests.fill_unanswered(); } // update the cached network requests. fn update_net_requests(&mut self) { use request::IncompleteRequest; let mut builder = basic_request::Builder::default(); let num_answered = self.requests.num_answered(); let mut mapping = move |idx| idx - num_answered; for request in self.requests.iter().skip(num_answered) { let mut net_req = request.clone().into_net_request(); // all back-references with request index less than `num_answered` have // been filled by now. all remaining requests point to nothing earlier // than the next unanswered request. net_req.adjust_refs(&mut mapping); builder.push(net_req) .expect("all back-references to answered requests have been filled; qed"); } // update pending fields. let capabilities = guess_capabilities(&self.requests[num_answered..]); self.net_requests = builder.build(); self.required_capabilities = capabilities; } } // helper to guess capabilities required for a given batch of network requests. fn guess_capabilities(requests: &[CheckedRequest]) -> Capabilities { let mut caps = Capabilities { serve_headers: false, serve_chain_since: None, serve_state_since: None, tx_relay: false, }; let update_since = |current: &mut Option<u64>, new| *current = match *current { Some(x) => Some(::std::cmp::min(x, new)), None => Some(new), }; for request in requests { match *request { // TODO: might be worth returning a required block number for this also. CheckedRequest::HeaderProof(_, _) => caps.serve_headers = true, CheckedRequest::HeaderByHash(_, _) => caps.serve_headers = true, CheckedRequest::TransactionIndex(_, _) => {} // hashes yield no info. CheckedRequest::Signal(_, _) => caps.serve_headers = true, CheckedRequest::Body(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Receipts(ref req, _) => if let Ok(ref hdr) = req.0.as_ref() { update_since(&mut caps.serve_chain_since, hdr.number()); }, CheckedRequest::Account(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, CheckedRequest::Code(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, CheckedRequest::Execution(ref req, _) => if let Ok(ref hdr) = req.header.as_ref() { update_since(&mut caps.serve_state_since, hdr.number()); }, } } caps } /// A future extracting the concrete output type of the generic adapter /// from a vector of responses. pub struct OnResponses<T: request::RequestAdapter> { receiver: Receiver<Vec<Response>>, _marker: PhantomData<T>, } impl<T: request::RequestAdapter> Future for OnResponses<T> { type Item = T::Out; type Error = Canceled; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.receiver.poll().map(|async| async.map(T::extract_from)) } } /// On demand request service. See module docs for more details. /// Accumulates info about all peers' capabilities and dispatches /// requests to them accordingly. // lock in declaration order. pub struct OnDemand { pending: RwLock<Vec<Pending>>, peers: RwLock<HashMap<PeerId, Peer>>, in_transit: RwLock<HashMap<ReqId, Pending>>, cache: Arc<Mutex<Cache>>, no_immediate_dispatch: bool, } impl OnDemand { /// Create a new `OnDemand` service with the given cache. pub fn new(cache: Arc<Mutex<Cache>>) -> Self { OnDemand { pending: RwLock::new(Vec::new()), peers: RwLock::new(HashMap::new()), in_transit: RwLock::new(HashMap::new()), cache: cache, no_immediate_dispatch: false, } } // make a test version: this doesn't dispatch pending requests // until you trigger it manually. #[cfg(test)] fn new_test(cache: Arc<Mutex<Cache>>) -> Self { let mut me = OnDemand::new(cache); me.no_immediate_dispatch = true; me } /// Submit a vector of requests to be processed together. /// /// Fails if back-references are not coherent. /// The returned vector of responses will correspond to the requests exactly. pub fn request_raw(&self, ctx: &BasicContext, requests: Vec<Request>) -> Result<Receiver<Vec<Response>>, basic_request::NoSuchOutput> { let (sender, receiver) = oneshot::channel(); if requests.is_empty() { assert!(sender.send(Vec::new()).is_ok(), "receiver still in scope; qed"); return Ok(receiver); } let mut builder = basic_request::Builder::default(); let responses = Vec::with_capacity(requests.len()); let mut header_producers = HashMap::new(); for (i, request) in requests.into_iter().enumerate() { let request = CheckedRequest::from(request); // ensure that all requests needing headers will get them. if let Some((idx, field)) = request.needs_header() { // a request chain with a header back-reference is valid only if it both // points to a request that returns a header and has the same back-reference // for the block hash. match header_producers.get(&idx) { Some(ref f) if &field == *f => {} _ => return Err(basic_request::NoSuchOutput), } } if let CheckedRequest::HeaderByHash(ref req, _) = request { header_producers.insert(i, req.0.clone()); } builder.push(request)?; } let requests = builder.build(); let net_requests = requests.clone().map_requests(|req| req.into_net_request()); let capabilities = guess_capabilities(requests.requests()); self.submit_pending(ctx, Pending { requests: requests, net_requests: net_requests, required_capabilities: capabilities, responses: responses, sender: sender, }); Ok(receiver) } /// Submit a strongly-typed batch of requests. /// /// Fails if back-reference are not coherent. pub fn request<T>(&self, ctx: &BasicContext, requests: T) -> Result<OnResponses<T>, basic_request::NoSuchOutput> where T: request::RequestAdapter { self.request_raw(ctx, requests.make_requests()).map(|recv| OnResponses { receiver: recv, _marker: PhantomData, }) } // maybe dispatch pending requests. // sometimes fn attempt_dispatch(&self, ctx: &BasicContext) { if!self.no_immediate_dispatch { self.dispatch_pending(ctx) } } // dispatch pending requests, and discard those for which the corresponding // receiver has been dropped. fn dispatch_pending(&self, ctx: &BasicContext) { // wrapper future for calling `poll_cancel` on our `Senders` to preserve // the invariant that it's always within a task. struct CheckHangup<'a, T: 'a>(&'a mut Sender<T>); impl<'a, T: 'a> Future for CheckHangup<'a, T> { type Item = bool; type Error = (); fn poll(&mut self) -> Poll<bool, ()> { Ok(Async::Ready(match self.0.poll_cancel() { Ok(Async::NotReady) => false, // hasn't hung up. _ => true, // has hung up. })) } } // check whether a sender's hung up (using `wait` to preserve the task invariant) // returns true if has hung up, false otherwise. fn check_hangup<T>(send: &mut Sender<T>) -> bool { CheckHangup(send).wait().expect("CheckHangup always returns ok; qed") } if self.pending.read().is_empty() { return } let mut pending = self.pending.write(); debug!(target: "on_demand", "Attempting to dispatch {} pending requests", pending.len()); // iterate over all pending requests, and check them for hang-up. // then, try and find a peer who can serve it. let peers = self.peers.read(); *pending = ::std::mem::replace(&mut *pending, Vec::new()).into_iter() .filter_map(|mut pending| match check_hangup(&mut pending.sender) { false => Some(pending), true => None, }) .filter_map(|pending| { for (peer_id, peer) in peers.iter() { //.shuffle? // TODO: see which requests can be answered by the cache? if!peer.can_fulfill(&pending.required_capabilities) { continue } match ctx.request_from(*peer_id, pending.net_requests.clone()) { Ok(req_id) => { trace!(target: "on_demand", "Dispatched request {} to peer {}", req_id, peer_id); self.in_transit.write().insert(req_id, pending); return None } Err(net::Error::NoCredits) | Err(net::Error::NotServer) => {} Err(e) => debug!(target: "on_demand", "Error dispatching request to peer: {}", e), } } // TODO: maximum number of failures _when we have peers_. Some(pending) }) .collect(); // `pending` now contains all requests we couldn't dispatch. debug!(target: "on_demand", "Was unable to dispatch {} requests.", pending.len()); } // submit a pending request set. attempts to answer from cache before // going to the network. if complete, sends response and consumes the struct. fn submit_pending(&self, ctx: &BasicContext, mut pending: Pending) { // answer as many requests from cache as we can, and schedule for dispatch // if incomplete. pending.answer_from_cache(&*self.cache); if let Some(mut pending) = pending.try_complete() { pending.update_net_requests(); self.pending.write().push(pending); self.attempt_dispatch(ctx); } } } impl Handler for OnDemand { fn on_connect( &self, ctx: &EventContext, status: &Status, capabilities: &Capabilities ) -> PeerStatus { self.peers.write().insert( ctx.peer(), Peer { status: status.clone(), capabilities: capabilities.clone() } ); self.attempt_dispatch(ctx.as_basic()); PeerStatus::Kept } fn on_disconnect(&self, ctx: &EventContext, unfulfilled: &[ReqId]) { self.peers.write().remove(&ctx.peer()); let ctx = ctx.as_basic(); { let mut pending = self.pending.write(); for unfulfilled in unfulfilled { if let Some(unfulfilled) = self.in_transit.write().remove(unfulfilled) { trace!(target: "on_demand", "Attempting to reassign dropped request"); pending.push(unfulfilled); } } } self.attempt_dispatch(ctx); } fn on_announcement(&self, ctx: &EventContext, announcement: &Announcement) { { let mut peers = self.peers.write(); if let Some(ref mut peer) = peers.get_mut(&ctx.peer()) { peer.status.update_from(&announcement); peer.capabilities.update_from(&announcement); } } self.attempt_dispatch(ctx.as_basic()); } fn on_responses(&self, ctx: &EventContext, req_id: ReqId, responses: &[basic_request::Response]) { let mut pending = match self.in_transit.write().remove(&req_id) { Some(req) => req, None => return, }; // for each incoming response // 1. ensure verification data filled. // 2. pending.requests.supply_response // 3. if extracted on-demand response, keep it for later. for response in responses { if let Err(e) = pending.supply_response(&*self.cache, response) { let peer = ctx.peer(); debug!(target: "on_demand", "Peer {} gave bad response: {:?}", peer, e); ctx.disable_peer(peer); break; } } pending.fill_unanswered(); self.submit_pending(ctx.as_basic(), pending); } fn tick(&self, ctx: &BasicContext) { self.attempt_dispatch(ctx) } }
use futures::sync::oneshot::{self, Sender, Receiver, Canceled}; use network::PeerId; use parking_lot::{RwLock, Mutex};
random_line_split
extdeps.rs
// Copyright 2018 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. //! Check for external package sources. Allow only vendorable packages. use std::fs; use std::path::Path; /// List of whitelisted sources for packages const WHITELISTED_SOURCES: &[&str] = &[ "\"registry+https://github.com/rust-lang/crates.io-index\"", ]; /// check for external package sources pub fn check(path: &Path, bad: &mut bool)
println!("invalid source: {}", source); *bad = true; } } }
{ // Cargo.lock of rust (tidy runs inside src/) let path = path.join("../Cargo.lock"); // open and read the whole file let cargo_lock = t!(fs::read_to_string(&path)); // process each line for line in cargo_lock.lines() { // consider only source entries if ! line.starts_with("source = ") { continue; } // extract source value let source = line.splitn(2, '=').nth(1).unwrap().trim(); // ensure source is whitelisted if !WHITELISTED_SOURCES.contains(&&*source) {
identifier_body
extdeps.rs
// Copyright 2018 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. //! Check for external package sources. Allow only vendorable packages. use std::fs; use std::path::Path; /// List of whitelisted sources for packages const WHITELISTED_SOURCES: &[&str] = &[ "\"registry+https://github.com/rust-lang/crates.io-index\"", ]; /// check for external package sources pub fn
(path: &Path, bad: &mut bool) { // Cargo.lock of rust (tidy runs inside src/) let path = path.join("../Cargo.lock"); // open and read the whole file let cargo_lock = t!(fs::read_to_string(&path)); // process each line for line in cargo_lock.lines() { // consider only source entries if! line.starts_with("source = ") { continue; } // extract source value let source = line.splitn(2, '=').nth(1).unwrap().trim(); // ensure source is whitelisted if!WHITELISTED_SOURCES.contains(&&*source) { println!("invalid source: {}", source); *bad = true; } } }
check
identifier_name
extdeps.rs
// Copyright 2018 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. //! Check for external package sources. Allow only vendorable packages. use std::fs; use std::path::Path; /// List of whitelisted sources for packages const WHITELISTED_SOURCES: &[&str] = &[ "\"registry+https://github.com/rust-lang/crates.io-index\"", ]; /// check for external package sources pub fn check(path: &Path, bad: &mut bool) { // Cargo.lock of rust (tidy runs inside src/) let path = path.join("../Cargo.lock"); // open and read the whole file let cargo_lock = t!(fs::read_to_string(&path)); // process each line for line in cargo_lock.lines() { // consider only source entries if! line.starts_with("source = ") { continue; } // extract source value let source = line.splitn(2, '=').nth(1).unwrap().trim(); // ensure source is whitelisted if!WHITELISTED_SOURCES.contains(&&*source) { println!("invalid source: {}", source); *bad = true; }
}
}
random_line_split
extdeps.rs
// Copyright 2018 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. //! Check for external package sources. Allow only vendorable packages. use std::fs; use std::path::Path; /// List of whitelisted sources for packages const WHITELISTED_SOURCES: &[&str] = &[ "\"registry+https://github.com/rust-lang/crates.io-index\"", ]; /// check for external package sources pub fn check(path: &Path, bad: &mut bool) { // Cargo.lock of rust (tidy runs inside src/) let path = path.join("../Cargo.lock"); // open and read the whole file let cargo_lock = t!(fs::read_to_string(&path)); // process each line for line in cargo_lock.lines() { // consider only source entries if! line.starts_with("source = ") { continue; } // extract source value let source = line.splitn(2, '=').nth(1).unwrap().trim(); // ensure source is whitelisted if!WHITELISTED_SOURCES.contains(&&*source)
} }
{ println!("invalid source: {}", source); *bad = true; }
conditional_block
jack_utils.rs
use jack_sys as j; use std::ffi; /// Collects strings from an array of c-strings into a Rust vector of strings /// and frees the memory pointed to by `ptr`. The end of the array is marked by /// the value of the c-string being the null pointer. `ptr` may be `null`, in /// which case nothing (deallocating) is done and an empty vector is returned. pub unsafe fn
(ptr: *const *const libc::c_char) -> Vec<String> { if ptr.is_null() { return Vec::new(); }; let len = { let mut len = 0; while!(*ptr.offset(len)).is_null() { len += 1; } len }; let mut strs = Vec::with_capacity(len as usize); for i in 0..len { let cstr_ptr = *ptr.offset(i); let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().into_owned(); strs.push(s); } j::jack_free(ptr as *mut ::libc::c_void); strs }
collect_strs
identifier_name
jack_utils.rs
use jack_sys as j; use std::ffi; /// Collects strings from an array of c-strings into a Rust vector of strings /// and frees the memory pointed to by `ptr`. The end of the array is marked by /// the value of the c-string being the null pointer. `ptr` may be `null`, in /// which case nothing (deallocating) is done and an empty vector is returned. pub unsafe fn collect_strs(ptr: *const *const libc::c_char) -> Vec<String>
{ if ptr.is_null() { return Vec::new(); }; let len = { let mut len = 0; while !(*ptr.offset(len)).is_null() { len += 1; } len }; let mut strs = Vec::with_capacity(len as usize); for i in 0..len { let cstr_ptr = *ptr.offset(i); let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().into_owned(); strs.push(s); } j::jack_free(ptr as *mut ::libc::c_void); strs }
identifier_body
jack_utils.rs
use jack_sys as j; use std::ffi; /// Collects strings from an array of c-strings into a Rust vector of strings /// and frees the memory pointed to by `ptr`. The end of the array is marked by /// the value of the c-string being the null pointer. `ptr` may be `null`, in /// which case nothing (deallocating) is done and an empty vector is returned. pub unsafe fn collect_strs(ptr: *const *const libc::c_char) -> Vec<String> { if ptr.is_null()
; let len = { let mut len = 0; while!(*ptr.offset(len)).is_null() { len += 1; } len }; let mut strs = Vec::with_capacity(len as usize); for i in 0..len { let cstr_ptr = *ptr.offset(i); let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().into_owned(); strs.push(s); } j::jack_free(ptr as *mut ::libc::c_void); strs }
{ return Vec::new(); }
conditional_block
jack_utils.rs
use jack_sys as j; use std::ffi; /// Collects strings from an array of c-strings into a Rust vector of strings /// and frees the memory pointed to by `ptr`. The end of the array is marked by /// the value of the c-string being the null pointer. `ptr` may be `null`, in /// which case nothing (deallocating) is done and an empty vector is returned. pub unsafe fn collect_strs(ptr: *const *const libc::c_char) -> Vec<String> { if ptr.is_null() { return Vec::new(); }; let len = { let mut len = 0; while!(*ptr.offset(len)).is_null() { len += 1; } len }; let mut strs = Vec::with_capacity(len as usize); for i in 0..len {
j::jack_free(ptr as *mut ::libc::c_void); strs }
let cstr_ptr = *ptr.offset(i); let s = ffi::CStr::from_ptr(cstr_ptr).to_string_lossy().into_owned(); strs.push(s); }
random_line_split
leader.rs
use chrono::{DateTime, FixedOffset, ParseError, Local}; use self::super::{read_toml_file, write_toml_file}; use self::super::super::Error; use std::iter::FromIterator; use std::cmp::Ordering; use std::path::Path; /// A leaderboard entry. /// /// # Examples /// /// Reading a leaderboard, adding an entry to it, then writing it back. /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// let mut leaders = Leader::read(&tf).unwrap(); /// assert!(leaders.is_empty()); /// leaders.push(Leader::now("nabijaczleweli".to_string(), 105)); /// assert_eq!(Leader::write(leaders, &tf), Ok(())); /// ``` /// /// This could alternatively be done with `Leader::append()`. #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Leader { /// Name the user entered when prompted. pub name: String, /// Time the score was achieved. pub time: DateTime<FixedOffset>, /// User's score. pub score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct LeaderForSerialisation { name: String, time: String, score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct Leaders { leader: Vec<LeaderForSerialisation>, } impl Leader { /// Create a new leaderboard entry with `time` set to now. /// /// # Examples /// /// ``` /// # use poke_a_mango::ops::Leader; /// let ldr = Leader::now("nabijaczleweli".to_string(), 36); /// assert_eq!(ldr.name, "nabijaczleweli"); /// assert_eq!(ldr.score, 36); /// ``` pub fn now(name: String, score: u64) -> Leader { let now = Local::now(); Leader { name: name, time: now.with_timezone(now.offset()), score: score, } } /// Read leaderboard from the specified file. /// /// If the specified file doesn't exist an empty leaderboard is returned. /// /// # Examples /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-read-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// assert_eq!(Leader::read(&tf), Ok(vec![])); /// ``` pub fn read(p: &Path) -> Result<Vec<Leader>, Error> { if p.exists()
else { Ok(vec![]) } } /// Save leaderboard to the specified file. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-write-0"); /// create_dir_all(&tf).unwrap(); /// /// Leader::write(vec![Leader::now("nabijaczleweli".to_string(), 105), /// Leader::now("skorezore".to_string(), 51)], /// &tf.join("leaderboard.toml")) /// .unwrap(); /// # } /// ``` pub fn write(queued_leaders: Vec<Leader>, p: &Path) -> Result<(), Error> { write_toml_file(&Leaders { leader: queued_leaders.into_iter().map(LeaderForSerialisation::from).collect() }, p, "leaderboard") } /// Append the specified leader to the leaderboard file at the specified path. /// /// This is equivalent to reading it, appending the leader, properly sorting and writing it back. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-append-0"); /// create_dir_all(&tf).unwrap(); /// /// assert_eq!(Leader::append(Leader::now("nabijaczleweli".to_string(), 105), &tf.join("leaderboard.toml")), Ok(())); /// # } /// ``` pub fn append(ldr: Leader, p: &Path) -> Result<(), Error> { let mut leaderboard = try!(Leader::read(p)); leaderboard.push(ldr); leaderboard.sort(); leaderboard.reverse(); try!(Leader::write(leaderboard, p)); Ok(()) } } impl Ord for Leader { fn cmp(&self, other: &Self) -> Ordering { self.score.cmp(&other.score) } } impl PartialOrd for Leader { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.score.partial_cmp(&other.score) } } impl From<Leader> for LeaderForSerialisation { fn from(qt: Leader) -> LeaderForSerialisation { LeaderForSerialisation { name: qt.name, time: qt.time.to_rfc3339(), score: qt.score, } } } impl Into<Result<Leader, ParseError>> for LeaderForSerialisation { fn into(self) -> Result<Leader, ParseError> { Ok(Leader { name: self.name, time: try!(DateTime::parse_from_rfc3339(&self.time)), score: self.score, }) } }
{ let queued_leaders: Leaders = try!(read_toml_file(p, "leaderboard")); Ok(Result::from_iter(queued_leaders.leader.into_iter().map(|qts| qts.into()).collect::<Vec<_>>()).unwrap()) }
conditional_block
leader.rs
use chrono::{DateTime, FixedOffset, ParseError, Local}; use self::super::{read_toml_file, write_toml_file}; use self::super::super::Error; use std::iter::FromIterator; use std::cmp::Ordering; use std::path::Path; /// A leaderboard entry. /// /// # Examples /// /// Reading a leaderboard, adding an entry to it, then writing it back. /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// let mut leaders = Leader::read(&tf).unwrap(); /// assert!(leaders.is_empty()); /// leaders.push(Leader::now("nabijaczleweli".to_string(), 105)); /// assert_eq!(Leader::write(leaders, &tf), Ok(())); /// ``` /// /// This could alternatively be done with `Leader::append()`. #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Leader { /// Name the user entered when prompted. pub name: String, /// Time the score was achieved. pub time: DateTime<FixedOffset>, /// User's score. pub score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct LeaderForSerialisation { name: String, time: String, score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct
{ leader: Vec<LeaderForSerialisation>, } impl Leader { /// Create a new leaderboard entry with `time` set to now. /// /// # Examples /// /// ``` /// # use poke_a_mango::ops::Leader; /// let ldr = Leader::now("nabijaczleweli".to_string(), 36); /// assert_eq!(ldr.name, "nabijaczleweli"); /// assert_eq!(ldr.score, 36); /// ``` pub fn now(name: String, score: u64) -> Leader { let now = Local::now(); Leader { name: name, time: now.with_timezone(now.offset()), score: score, } } /// Read leaderboard from the specified file. /// /// If the specified file doesn't exist an empty leaderboard is returned. /// /// # Examples /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-read-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// assert_eq!(Leader::read(&tf), Ok(vec![])); /// ``` pub fn read(p: &Path) -> Result<Vec<Leader>, Error> { if p.exists() { let queued_leaders: Leaders = try!(read_toml_file(p, "leaderboard")); Ok(Result::from_iter(queued_leaders.leader.into_iter().map(|qts| qts.into()).collect::<Vec<_>>()).unwrap()) } else { Ok(vec![]) } } /// Save leaderboard to the specified file. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-write-0"); /// create_dir_all(&tf).unwrap(); /// /// Leader::write(vec![Leader::now("nabijaczleweli".to_string(), 105), /// Leader::now("skorezore".to_string(), 51)], /// &tf.join("leaderboard.toml")) /// .unwrap(); /// # } /// ``` pub fn write(queued_leaders: Vec<Leader>, p: &Path) -> Result<(), Error> { write_toml_file(&Leaders { leader: queued_leaders.into_iter().map(LeaderForSerialisation::from).collect() }, p, "leaderboard") } /// Append the specified leader to the leaderboard file at the specified path. /// /// This is equivalent to reading it, appending the leader, properly sorting and writing it back. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-append-0"); /// create_dir_all(&tf).unwrap(); /// /// assert_eq!(Leader::append(Leader::now("nabijaczleweli".to_string(), 105), &tf.join("leaderboard.toml")), Ok(())); /// # } /// ``` pub fn append(ldr: Leader, p: &Path) -> Result<(), Error> { let mut leaderboard = try!(Leader::read(p)); leaderboard.push(ldr); leaderboard.sort(); leaderboard.reverse(); try!(Leader::write(leaderboard, p)); Ok(()) } } impl Ord for Leader { fn cmp(&self, other: &Self) -> Ordering { self.score.cmp(&other.score) } } impl PartialOrd for Leader { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.score.partial_cmp(&other.score) } } impl From<Leader> for LeaderForSerialisation { fn from(qt: Leader) -> LeaderForSerialisation { LeaderForSerialisation { name: qt.name, time: qt.time.to_rfc3339(), score: qt.score, } } } impl Into<Result<Leader, ParseError>> for LeaderForSerialisation { fn into(self) -> Result<Leader, ParseError> { Ok(Leader { name: self.name, time: try!(DateTime::parse_from_rfc3339(&self.time)), score: self.score, }) } }
Leaders
identifier_name
leader.rs
use chrono::{DateTime, FixedOffset, ParseError, Local}; use self::super::{read_toml_file, write_toml_file}; use self::super::super::Error; use std::iter::FromIterator; use std::cmp::Ordering; use std::path::Path; /// A leaderboard entry. /// /// # Examples /// /// Reading a leaderboard, adding an entry to it, then writing it back. /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// let mut leaders = Leader::read(&tf).unwrap(); /// assert!(leaders.is_empty()); /// leaders.push(Leader::now("nabijaczleweli".to_string(), 105)); /// assert_eq!(Leader::write(leaders, &tf), Ok(())); /// ``` /// /// This could alternatively be done with `Leader::append()`. #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Leader { /// Name the user entered when prompted. pub name: String, /// Time the score was achieved. pub time: DateTime<FixedOffset>, /// User's score. pub score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct LeaderForSerialisation { name: String, time: String, score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct Leaders { leader: Vec<LeaderForSerialisation>, } impl Leader { /// Create a new leaderboard entry with `time` set to now. /// /// # Examples /// /// ``` /// # use poke_a_mango::ops::Leader; /// let ldr = Leader::now("nabijaczleweli".to_string(), 36); /// assert_eq!(ldr.name, "nabijaczleweli"); /// assert_eq!(ldr.score, 36); /// ``` pub fn now(name: String, score: u64) -> Leader { let now = Local::now(); Leader { name: name, time: now.with_timezone(now.offset()), score: score, } } /// Read leaderboard from the specified file. /// /// If the specified file doesn't exist an empty leaderboard is returned. /// /// # Examples /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-read-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// assert_eq!(Leader::read(&tf), Ok(vec![])); /// ``` pub fn read(p: &Path) -> Result<Vec<Leader>, Error> { if p.exists() { let queued_leaders: Leaders = try!(read_toml_file(p, "leaderboard")); Ok(Result::from_iter(queued_leaders.leader.into_iter().map(|qts| qts.into()).collect::<Vec<_>>()).unwrap()) } else { Ok(vec![]) } } /// Save leaderboard to the specified file. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-write-0"); /// create_dir_all(&tf).unwrap(); /// /// Leader::write(vec![Leader::now("nabijaczleweli".to_string(), 105), /// Leader::now("skorezore".to_string(), 51)], /// &tf.join("leaderboard.toml")) /// .unwrap(); /// # } /// ``` pub fn write(queued_leaders: Vec<Leader>, p: &Path) -> Result<(), Error> { write_toml_file(&Leaders { leader: queued_leaders.into_iter().map(LeaderForSerialisation::from).collect() }, p, "leaderboard") } /// Append the specified leader to the leaderboard file at the specified path. /// /// This is equivalent to reading it, appending the leader, properly sorting and writing it back. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-append-0"); /// create_dir_all(&tf).unwrap(); /// /// assert_eq!(Leader::append(Leader::now("nabijaczleweli".to_string(), 105), &tf.join("leaderboard.toml")), Ok(())); /// # } /// ``` pub fn append(ldr: Leader, p: &Path) -> Result<(), Error> { let mut leaderboard = try!(Leader::read(p)); leaderboard.push(ldr); leaderboard.sort(); leaderboard.reverse(); try!(Leader::write(leaderboard, p)); Ok(()) } } impl Ord for Leader { fn cmp(&self, other: &Self) -> Ordering { self.score.cmp(&other.score) } } impl PartialOrd for Leader { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.score.partial_cmp(&other.score) } } impl From<Leader> for LeaderForSerialisation { fn from(qt: Leader) -> LeaderForSerialisation { LeaderForSerialisation { name: qt.name, time: qt.time.to_rfc3339(), score: qt.score, } } } impl Into<Result<Leader, ParseError>> for LeaderForSerialisation { fn into(self) -> Result<Leader, ParseError>
}
{ Ok(Leader { name: self.name, time: try!(DateTime::parse_from_rfc3339(&self.time)), score: self.score, }) }
identifier_body
leader.rs
use chrono::{DateTime, FixedOffset, ParseError, Local}; use self::super::{read_toml_file, write_toml_file}; use self::super::super::Error; use std::iter::FromIterator; use std::cmp::Ordering; use std::path::Path; /// A leaderboard entry. /// /// # Examples /// /// Reading a leaderboard, adding an entry to it, then writing it back. /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// let mut leaders = Leader::read(&tf).unwrap(); /// assert!(leaders.is_empty()); /// leaders.push(Leader::now("nabijaczleweli".to_string(), 105)); /// assert_eq!(Leader::write(leaders, &tf), Ok(())); /// ``` /// /// This could alternatively be done with `Leader::append()`. #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct Leader { /// Name the user entered when prompted. pub name: String, /// Time the score was achieved. pub time: DateTime<FixedOffset>, /// User's score. pub score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct LeaderForSerialisation { name: String, time: String, score: u64, } #[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] struct Leaders { leader: Vec<LeaderForSerialisation>, } impl Leader {
/// Create a new leaderboard entry with `time` set to now. /// /// # Examples /// /// ``` /// # use poke_a_mango::ops::Leader; /// let ldr = Leader::now("nabijaczleweli".to_string(), 36); /// assert_eq!(ldr.name, "nabijaczleweli"); /// assert_eq!(ldr.score, 36); /// ``` pub fn now(name: String, score: u64) -> Leader { let now = Local::now(); Leader { name: name, time: now.with_timezone(now.offset()), score: score, } } /// Read leaderboard from the specified file. /// /// If the specified file doesn't exist an empty leaderboard is returned. /// /// # Examples /// /// ``` /// # use std::fs::{File, create_dir_all}; /// # use poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-read-0"); /// create_dir_all(&tf).unwrap(); /// /// let tf = tf.join("leaderboard.toml"); /// File::create(&tf).unwrap(); /// /// assert_eq!(Leader::read(&tf), Ok(vec![])); /// ``` pub fn read(p: &Path) -> Result<Vec<Leader>, Error> { if p.exists() { let queued_leaders: Leaders = try!(read_toml_file(p, "leaderboard")); Ok(Result::from_iter(queued_leaders.leader.into_iter().map(|qts| qts.into()).collect::<Vec<_>>()).unwrap()) } else { Ok(vec![]) } } /// Save leaderboard to the specified file. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-write-0"); /// create_dir_all(&tf).unwrap(); /// /// Leader::write(vec![Leader::now("nabijaczleweli".to_string(), 105), /// Leader::now("skorezore".to_string(), 51)], /// &tf.join("leaderboard.toml")) /// .unwrap(); /// # } /// ``` pub fn write(queued_leaders: Vec<Leader>, p: &Path) -> Result<(), Error> { write_toml_file(&Leaders { leader: queued_leaders.into_iter().map(LeaderForSerialisation::from).collect() }, p, "leaderboard") } /// Append the specified leader to the leaderboard file at the specified path. /// /// This is equivalent to reading it, appending the leader, properly sorting and writing it back. /// /// # Examples /// /// ``` /// # extern crate poke_a_mango; /// # extern crate chrono; /// # use std::fs::{File, create_dir_all}; /// # use self::chrono::{Duration, Local}; /// # use self::poke_a_mango::ops::Leader; /// # use std::env::temp_dir; /// # fn main() { /// let tf = temp_dir().join("poke-a-mango-doctest").join("ops-Leader-append-0"); /// create_dir_all(&tf).unwrap(); /// /// assert_eq!(Leader::append(Leader::now("nabijaczleweli".to_string(), 105), &tf.join("leaderboard.toml")), Ok(())); /// # } /// ``` pub fn append(ldr: Leader, p: &Path) -> Result<(), Error> { let mut leaderboard = try!(Leader::read(p)); leaderboard.push(ldr); leaderboard.sort(); leaderboard.reverse(); try!(Leader::write(leaderboard, p)); Ok(()) } } impl Ord for Leader { fn cmp(&self, other: &Self) -> Ordering { self.score.cmp(&other.score) } } impl PartialOrd for Leader { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.score.partial_cmp(&other.score) } } impl From<Leader> for LeaderForSerialisation { fn from(qt: Leader) -> LeaderForSerialisation { LeaderForSerialisation { name: qt.name, time: qt.time.to_rfc3339(), score: qt.score, } } } impl Into<Result<Leader, ParseError>> for LeaderForSerialisation { fn into(self) -> Result<Leader, ParseError> { Ok(Leader { name: self.name, time: try!(DateTime::parse_from_rfc3339(&self.time)), score: self.score, }) } }
random_line_split
multi.rs
use wlroots_sys::{ wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove, wlr_multi_is_empty }; use crate::backend::UnsafeRenderSetupFunction; /// When multiple backends are running or when the compositor writer doesn't /// care and just used the auto create option in the `CompositorBuilder`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct Multi { pub(crate) backend: *mut wlr_backend } impl Multi { /// Auto create a backend based on the environment. pub unsafe fn auto_create( display: *mut wl_display, render_setup_func: Option<UnsafeRenderSetupFunction> ) -> Self { let backend = wlr_backend_autocreate(display, render_setup_func); if backend.is_null() { panic!("Could not auto construct backend"); } Multi { backend } } /// Adds the given backend to the multi backend. /// /// # Safety /// /// This should be done before the new backend is started. pub unsafe fn add_backend(&self, new_backend: *mut wlr_backend) -> bool { wlr_multi_backend_add(self.backend, new_backend) } /// Removes the backend. /// /// # Safety /// /// Doesn't check if that backend is valid. pub unsafe fn remove_backend(&self, backend: *mut wlr_backend)
pub fn is_empty(&self) -> bool { unsafe { wlr_multi_is_empty(self.backend) } } }
{ wlr_multi_backend_remove(self.backend, backend) }
identifier_body
multi.rs
use wlroots_sys::{ wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove, wlr_multi_is_empty }; use crate::backend::UnsafeRenderSetupFunction; /// When multiple backends are running or when the compositor writer doesn't /// care and just used the auto create option in the `CompositorBuilder`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct Multi { pub(crate) backend: *mut wlr_backend } impl Multi { /// Auto create a backend based on the environment. pub unsafe fn auto_create( display: *mut wl_display, render_setup_func: Option<UnsafeRenderSetupFunction> ) -> Self { let backend = wlr_backend_autocreate(display, render_setup_func); if backend.is_null()
Multi { backend } } /// Adds the given backend to the multi backend. /// /// # Safety /// /// This should be done before the new backend is started. pub unsafe fn add_backend(&self, new_backend: *mut wlr_backend) -> bool { wlr_multi_backend_add(self.backend, new_backend) } /// Removes the backend. /// /// # Safety /// /// Doesn't check if that backend is valid. pub unsafe fn remove_backend(&self, backend: *mut wlr_backend) { wlr_multi_backend_remove(self.backend, backend) } pub fn is_empty(&self) -> bool { unsafe { wlr_multi_is_empty(self.backend) } } }
{ panic!("Could not auto construct backend"); }
conditional_block
multi.rs
use wlroots_sys::{ wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove, wlr_multi_is_empty }; use crate::backend::UnsafeRenderSetupFunction; /// When multiple backends are running or when the compositor writer doesn't /// care and just used the auto create option in the `CompositorBuilder`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct Multi { pub(crate) backend: *mut wlr_backend } impl Multi { /// Auto create a backend based on the environment. pub unsafe fn auto_create( display: *mut wl_display, render_setup_func: Option<UnsafeRenderSetupFunction> ) -> Self { let backend = wlr_backend_autocreate(display, render_setup_func); if backend.is_null() { panic!("Could not auto construct backend"); } Multi { backend } } /// Adds the given backend to the multi backend. /// /// # Safety /// /// This should be done before the new backend is started. pub unsafe fn
(&self, new_backend: *mut wlr_backend) -> bool { wlr_multi_backend_add(self.backend, new_backend) } /// Removes the backend. /// /// # Safety /// /// Doesn't check if that backend is valid. pub unsafe fn remove_backend(&self, backend: *mut wlr_backend) { wlr_multi_backend_remove(self.backend, backend) } pub fn is_empty(&self) -> bool { unsafe { wlr_multi_is_empty(self.backend) } } }
add_backend
identifier_name
multi.rs
use wlroots_sys::{ wl_display, wlr_backend, wlr_backend_autocreate, wlr_multi_backend_add, wlr_multi_backend_remove, wlr_multi_is_empty }; use crate::backend::UnsafeRenderSetupFunction; /// When multiple backends are running or when the compositor writer doesn't /// care and just used the auto create option in the `CompositorBuilder`. #[derive(Debug, Hash, Eq, PartialEq)] pub struct Multi { pub(crate) backend: *mut wlr_backend }
display: *mut wl_display, render_setup_func: Option<UnsafeRenderSetupFunction> ) -> Self { let backend = wlr_backend_autocreate(display, render_setup_func); if backend.is_null() { panic!("Could not auto construct backend"); } Multi { backend } } /// Adds the given backend to the multi backend. /// /// # Safety /// /// This should be done before the new backend is started. pub unsafe fn add_backend(&self, new_backend: *mut wlr_backend) -> bool { wlr_multi_backend_add(self.backend, new_backend) } /// Removes the backend. /// /// # Safety /// /// Doesn't check if that backend is valid. pub unsafe fn remove_backend(&self, backend: *mut wlr_backend) { wlr_multi_backend_remove(self.backend, backend) } pub fn is_empty(&self) -> bool { unsafe { wlr_multi_is_empty(self.backend) } } }
impl Multi { /// Auto create a backend based on the environment. pub unsafe fn auto_create(
random_line_split
classify.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. /* Predicates on exprs and stmts that the pretty-printer and parser use */ use ast; // does this expression require a semicolon to be treated // as a statement? The negation of this: 'can this expression // be used as a statement without a semicolon' -- is used // as an early-bail-out in the parser so that, for instance, // 'if true {...} else {...} // |x| 5 ' // isn't parsed as (if true {...} else {...} | x) | 5 pub fn
(e: @ast::expr) -> bool { match e.node { ast::expr_if(*) | ast::expr_match(*) | ast::expr_block(_) | ast::expr_while(*) | ast::expr_loop(*) | ast::expr_call(_, _, ast::DoSugar) | ast::expr_call(_, _, ast::ForSugar) | ast::expr_method_call(_, _, _, _, _, ast::DoSugar) | ast::expr_method_call(_, _, _, _, _, ast::ForSugar) => false, _ => true } } pub fn expr_is_simple_block(e: @ast::expr) -> bool { match e.node { ast::expr_block( ast::blk { rules: ast::default_blk, _ } ) => true, _ => false } } // this statement requires a semicolon after it. // note that in one case (stmt_semi), we've already // seen the semicolon, and thus don't need another. pub fn stmt_ends_with_semi(stmt: &ast::stmt) -> bool { return match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_local(_) => true, ast::decl_item(_) => false } } ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) } ast::stmt_semi(*) => { false } ast::stmt_mac(*) => { false } } }
expr_requires_semi_to_be_stmt
identifier_name
classify.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. /* Predicates on exprs and stmts that the pretty-printer and parser use */ use ast; // does this expression require a semicolon to be treated // as a statement? The negation of this: 'can this expression // be used as a statement without a semicolon' -- is used // as an early-bail-out in the parser so that, for instance, // 'if true {...} else {...} // |x| 5 ' // isn't parsed as (if true {...} else {...} | x) | 5 pub fn expr_requires_semi_to_be_stmt(e: @ast::expr) -> bool { match e.node { ast::expr_if(*) | ast::expr_match(*) | ast::expr_block(_) | ast::expr_while(*) | ast::expr_loop(*) | ast::expr_call(_, _, ast::DoSugar) | ast::expr_call(_, _, ast::ForSugar) | ast::expr_method_call(_, _, _, _, _, ast::DoSugar) | ast::expr_method_call(_, _, _, _, _, ast::ForSugar) => false, _ => true } } pub fn expr_is_simple_block(e: @ast::expr) -> bool { match e.node { ast::expr_block( ast::blk { rules: ast::default_blk, _ } ) => true, _ => false } } // this statement requires a semicolon after it. // note that in one case (stmt_semi), we've already // seen the semicolon, and thus don't need another. pub fn stmt_ends_with_semi(stmt: &ast::stmt) -> bool
{ return match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_local(_) => true, ast::decl_item(_) => false } } ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) } ast::stmt_semi(*) => { false } ast::stmt_mac(*) => { false } } }
identifier_body
classify.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. /* Predicates on exprs and stmts that the pretty-printer and parser use */ use ast; // does this expression require a semicolon to be treated // as a statement? The negation of this: 'can this expression // be used as a statement without a semicolon' -- is used // as an early-bail-out in the parser so that, for instance, // 'if true {...} else {...} // |x| 5 ' // isn't parsed as (if true {...} else {...} | x) | 5 pub fn expr_requires_semi_to_be_stmt(e: @ast::expr) -> bool { match e.node { ast::expr_if(*) | ast::expr_match(*) | ast::expr_block(_) | ast::expr_while(*) | ast::expr_loop(*) | ast::expr_call(_, _, ast::DoSugar) | ast::expr_call(_, _, ast::ForSugar) | ast::expr_method_call(_, _, _, _, _, ast::DoSugar) | ast::expr_method_call(_, _, _, _, _, ast::ForSugar) => false, _ => true } } pub fn expr_is_simple_block(e: @ast::expr) -> bool { match e.node { ast::expr_block( ast::blk { rules: ast::default_blk, _ } ) => true, _ => false } } // this statement requires a semicolon after it.
return match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_local(_) => true, ast::decl_item(_) => false } } ast::stmt_expr(e, _) => { expr_requires_semi_to_be_stmt(e) } ast::stmt_semi(*) => { false } ast::stmt_mac(*) => { false } } }
// note that in one case (stmt_semi), we've already // seen the semicolon, and thus don't need another. pub fn stmt_ends_with_semi(stmt: &ast::stmt) -> bool {
random_line_split
llrepr.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. use middle::trans::context::CrateContext; use middle::trans::type_::Type; use llvm::ValueRef; pub trait LlvmRepr { fn llrepr(&self, ccx: &CrateContext) -> String; } impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] { fn llrepr(&self, ccx: &CrateContext) -> String { let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect(); format!("[{}]", reprs.connect(",")) } } impl LlvmRepr for Type { fn
(&self, ccx: &CrateContext) -> String { ccx.tn.type_to_string(*self) } } impl LlvmRepr for ValueRef { fn llrepr(&self, ccx: &CrateContext) -> String { ccx.tn.val_to_string(*self) } }
llrepr
identifier_name
llrepr.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. use middle::trans::context::CrateContext; use middle::trans::type_::Type; use llvm::ValueRef; pub trait LlvmRepr { fn llrepr(&self, ccx: &CrateContext) -> String; } impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] { fn llrepr(&self, ccx: &CrateContext) -> String { let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect(); format!("[{}]", reprs.connect(",")) } } impl LlvmRepr for Type { fn llrepr(&self, ccx: &CrateContext) -> String
} impl LlvmRepr for ValueRef { fn llrepr(&self, ccx: &CrateContext) -> String { ccx.tn.val_to_string(*self) } }
{ ccx.tn.type_to_string(*self) }
identifier_body
llrepr.rs
// // 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 middle::trans::context::CrateContext; use middle::trans::type_::Type; use llvm::ValueRef; pub trait LlvmRepr { fn llrepr(&self, ccx: &CrateContext) -> String; } impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] { fn llrepr(&self, ccx: &CrateContext) -> String { let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect(); format!("[{}]", reprs.connect(",")) } } impl LlvmRepr for Type { fn llrepr(&self, ccx: &CrateContext) -> String { ccx.tn.type_to_string(*self) } } impl LlvmRepr for ValueRef { fn llrepr(&self, ccx: &CrateContext) -> String { ccx.tn.val_to_string(*self) } }
// 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.
random_line_split
mod.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines physical storage schema for a transaction index via which the version of a //! transaction sent by `account_address` with `sequence_number` can be found. With the version one //! can resort to `TransactionSchema` for the transaction content. //! //! ```text //! |<-------key------->|<-value->| //! | address | seq_num | txn_ver | //! ``` use crate::schema::{ensure_slice_len_eq, TRANSACTION_BY_ACCOUNT_CF_NAME}; use anyhow::Result; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_types::{account_address::AccountAddress, transaction::Version}; use schemadb::{ define_schema, schema::{KeyCodec, ValueCodec}, }; use std::{convert::TryFrom, mem::size_of}; define_schema!( TransactionByAccountSchema, Key, Version, TRANSACTION_BY_ACCOUNT_CF_NAME ); type SeqNum = u64; type Key = (AccountAddress, SeqNum); impl KeyCodec<TransactionByAccountSchema> for Key { fn encode_key(&self) -> Result<Vec<u8>> { let (ref account_address, seq_num) = *self; let mut encoded = account_address.to_vec(); encoded.write_u64::<BigEndian>(seq_num)?; Ok(encoded) } fn
(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; let address = AccountAddress::try_from(&data[..AccountAddress::LENGTH])?; let seq_num = (&data[AccountAddress::LENGTH..]).read_u64::<BigEndian>()?; Ok((address, seq_num)) } } impl ValueCodec<TransactionByAccountSchema> for Version { fn encode_value(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) } fn decode_value(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; Ok((&data[..]).read_u64::<BigEndian>()?) } } #[cfg(test)] mod test;
decode_key
identifier_name
mod.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines physical storage schema for a transaction index via which the version of a //! transaction sent by `account_address` with `sequence_number` can be found. With the version one //! can resort to `TransactionSchema` for the transaction content. //! //! ```text //! |<-------key------->|<-value->| //! | address | seq_num | txn_ver | //! ``` use crate::schema::{ensure_slice_len_eq, TRANSACTION_BY_ACCOUNT_CF_NAME}; use anyhow::Result; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_types::{account_address::AccountAddress, transaction::Version}; use schemadb::{ define_schema, schema::{KeyCodec, ValueCodec}, }; use std::{convert::TryFrom, mem::size_of};
); type SeqNum = u64; type Key = (AccountAddress, SeqNum); impl KeyCodec<TransactionByAccountSchema> for Key { fn encode_key(&self) -> Result<Vec<u8>> { let (ref account_address, seq_num) = *self; let mut encoded = account_address.to_vec(); encoded.write_u64::<BigEndian>(seq_num)?; Ok(encoded) } fn decode_key(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; let address = AccountAddress::try_from(&data[..AccountAddress::LENGTH])?; let seq_num = (&data[AccountAddress::LENGTH..]).read_u64::<BigEndian>()?; Ok((address, seq_num)) } } impl ValueCodec<TransactionByAccountSchema> for Version { fn encode_value(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) } fn decode_value(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; Ok((&data[..]).read_u64::<BigEndian>()?) } } #[cfg(test)] mod test;
define_schema!( TransactionByAccountSchema, Key, Version, TRANSACTION_BY_ACCOUNT_CF_NAME
random_line_split
mod.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines physical storage schema for a transaction index via which the version of a //! transaction sent by `account_address` with `sequence_number` can be found. With the version one //! can resort to `TransactionSchema` for the transaction content. //! //! ```text //! |<-------key------->|<-value->| //! | address | seq_num | txn_ver | //! ``` use crate::schema::{ensure_slice_len_eq, TRANSACTION_BY_ACCOUNT_CF_NAME}; use anyhow::Result; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_types::{account_address::AccountAddress, transaction::Version}; use schemadb::{ define_schema, schema::{KeyCodec, ValueCodec}, }; use std::{convert::TryFrom, mem::size_of}; define_schema!( TransactionByAccountSchema, Key, Version, TRANSACTION_BY_ACCOUNT_CF_NAME ); type SeqNum = u64; type Key = (AccountAddress, SeqNum); impl KeyCodec<TransactionByAccountSchema> for Key { fn encode_key(&self) -> Result<Vec<u8>>
fn decode_key(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; let address = AccountAddress::try_from(&data[..AccountAddress::LENGTH])?; let seq_num = (&data[AccountAddress::LENGTH..]).read_u64::<BigEndian>()?; Ok((address, seq_num)) } } impl ValueCodec<TransactionByAccountSchema> for Version { fn encode_value(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) } fn decode_value(data: &[u8]) -> Result<Self> { ensure_slice_len_eq(data, size_of::<Self>())?; Ok((&data[..]).read_u64::<BigEndian>()?) } } #[cfg(test)] mod test;
{ let (ref account_address, seq_num) = *self; let mut encoded = account_address.to_vec(); encoded.write_u64::<BigEndian>(seq_num)?; Ok(encoded) }
identifier_body
crc32.rs
// Sadly, all of the crc crates in Rust appear to be insufficient for high // performance algorithms. In fact, the implementation here is insufficient! // The best implementation uses the CRC32 instruction from SSE 4.2, but using // specialty instructions on stable Rust is an absolute nightmare at the // moment. The only way I can think to do it is to write some Assembly in a // separate source file and run an Assembler from build.rs. But we'd need to be // careful to only do this on platforms that support the CRC32 instruction, // which means we'd need to query CPUID. There are a couple Rust crates for // that, but of course, they only work on unstable Rust so we'd need to hand // roll that too. // // As a stopgap, we implement the fastest (slicing-by-16) algorithm described // here: http://create.stephan-brumme.com/crc32/ // (Actually, slicing-by-16 doesn't seem to be measurably faster than // slicing-by-8 on my i7-6900K, so use slicing-by-8.) // // For Snappy, we only care about CRC32C (32 bit, Castagnoli). // // ---AG // We have a bunch of different implementations of crc32 below that seem // somewhat useful to leave around for easy benchmarking. #![allow(dead_code)] use byteorder::{ByteOrder, LittleEndian as LE}; const CASTAGNOLI_POLY: u32 = 0x82f63b78; lazy_static! { static ref TABLE: [u32; 256] = make_table(CASTAGNOLI_POLY); static ref TABLE16: [[u32; 256]; 16] = { let mut tab = [[0; 256]; 16]; tab[0] = make_table(CASTAGNOLI_POLY); for i in 0..256 { let mut crc = tab[0][i]; for j in 1..16 { crc = (crc >> 8) ^ tab[0][crc as u8 as usize]; tab[j][i] = crc; } } tab }; } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. pub fn crc32c(buf: &[u8]) -> u32
/// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice16(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab16 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 16 { crc ^= LE::read_u32(&buf[0..4]); crc = tab16[0][buf[15] as usize] ^ tab16[1][buf[14] as usize] ^ tab16[2][buf[13] as usize] ^ tab16[3][buf[12] as usize] ^ tab16[4][buf[11] as usize] ^ tab16[5][buf[10] as usize] ^ tab16[6][buf[9] as usize] ^ tab16[7][buf[8] as usize] ^ tab16[8][buf[7] as usize] ^ tab16[9][buf[6] as usize] ^ tab16[10][buf[5] as usize] ^ tab16[11][buf[4] as usize] ^ tab16[12][(crc >> 24) as u8 as usize] ^ tab16[13][(crc >> 16) as u8 as usize] ^ tab16[14][(crc >> 8) as u8 as usize] ^ tab16[15][(crc) as u8 as usize]; buf = &buf[16..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice8(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab8 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 8 { crc ^= LE::read_u32(&buf[0..4]); crc = tab8[0][buf[7] as usize] ^ tab8[1][buf[6] as usize] ^ tab8[2][buf[5] as usize] ^ tab8[3][buf[4] as usize] ^ tab8[4][(crc >> 24) as u8 as usize] ^ tab8[5][(crc >> 16) as u8 as usize] ^ tab8[6][(crc >> 8) as u8 as usize] ^ tab8[7][(crc) as u8 as usize]; buf = &buf[8..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice4(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab4 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 4 { crc ^= LE::read_u32(&buf[0..4]); crc = tab4[0][(crc >> 24) as u8 as usize] ^ tab4[1][(crc >> 16) as u8 as usize] ^ tab4[2][(crc >> 8) as u8 as usize] ^ tab4[3][(crc) as u8 as usize]; buf = &buf[4..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_multiple(buf: &[u8]) -> u32 { let tab = &*TABLE; let mut crc: u32 =!0; for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_bitwise(buf: &[u8]) -> u32 { let mut crc: u32 =!0; for &b in buf { crc ^= b as u32; for _ in 0..8 { crc = (crc >> 1) ^ ((crc & 1) * CASTAGNOLI_POLY); } } !crc } fn make_table(poly: u32) -> [u32; 256] { let mut tab = [0; 256]; for i in 0u32..256u32 { let mut crc = i; for _ in 0..8 { if crc & 1 == 1 { crc = (crc >> 1) ^ poly; } else { crc >>= 1; } } tab[i as usize] = crc; } tab }
{ // I can't measure any difference between slice8 and slice16. crc32c_slice8(buf) }
identifier_body
crc32.rs
// Sadly, all of the crc crates in Rust appear to be insufficient for high // performance algorithms. In fact, the implementation here is insufficient! // The best implementation uses the CRC32 instruction from SSE 4.2, but using // specialty instructions on stable Rust is an absolute nightmare at the // moment. The only way I can think to do it is to write some Assembly in a // separate source file and run an Assembler from build.rs. But we'd need to be // careful to only do this on platforms that support the CRC32 instruction, // which means we'd need to query CPUID. There are a couple Rust crates for // that, but of course, they only work on unstable Rust so we'd need to hand // roll that too. // // As a stopgap, we implement the fastest (slicing-by-16) algorithm described // here: http://create.stephan-brumme.com/crc32/ // (Actually, slicing-by-16 doesn't seem to be measurably faster than // slicing-by-8 on my i7-6900K, so use slicing-by-8.) // // For Snappy, we only care about CRC32C (32 bit, Castagnoli). // // ---AG // We have a bunch of different implementations of crc32 below that seem // somewhat useful to leave around for easy benchmarking. #![allow(dead_code)] use byteorder::{ByteOrder, LittleEndian as LE}; const CASTAGNOLI_POLY: u32 = 0x82f63b78; lazy_static! { static ref TABLE: [u32; 256] = make_table(CASTAGNOLI_POLY); static ref TABLE16: [[u32; 256]; 16] = { let mut tab = [[0; 256]; 16]; tab[0] = make_table(CASTAGNOLI_POLY);
let mut crc = tab[0][i]; for j in 1..16 { crc = (crc >> 8) ^ tab[0][crc as u8 as usize]; tab[j][i] = crc; } } tab }; } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. pub fn crc32c(buf: &[u8]) -> u32 { // I can't measure any difference between slice8 and slice16. crc32c_slice8(buf) } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice16(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab16 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 16 { crc ^= LE::read_u32(&buf[0..4]); crc = tab16[0][buf[15] as usize] ^ tab16[1][buf[14] as usize] ^ tab16[2][buf[13] as usize] ^ tab16[3][buf[12] as usize] ^ tab16[4][buf[11] as usize] ^ tab16[5][buf[10] as usize] ^ tab16[6][buf[9] as usize] ^ tab16[7][buf[8] as usize] ^ tab16[8][buf[7] as usize] ^ tab16[9][buf[6] as usize] ^ tab16[10][buf[5] as usize] ^ tab16[11][buf[4] as usize] ^ tab16[12][(crc >> 24) as u8 as usize] ^ tab16[13][(crc >> 16) as u8 as usize] ^ tab16[14][(crc >> 8) as u8 as usize] ^ tab16[15][(crc) as u8 as usize]; buf = &buf[16..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice8(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab8 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 8 { crc ^= LE::read_u32(&buf[0..4]); crc = tab8[0][buf[7] as usize] ^ tab8[1][buf[6] as usize] ^ tab8[2][buf[5] as usize] ^ tab8[3][buf[4] as usize] ^ tab8[4][(crc >> 24) as u8 as usize] ^ tab8[5][(crc >> 16) as u8 as usize] ^ tab8[6][(crc >> 8) as u8 as usize] ^ tab8[7][(crc) as u8 as usize]; buf = &buf[8..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice4(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab4 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 4 { crc ^= LE::read_u32(&buf[0..4]); crc = tab4[0][(crc >> 24) as u8 as usize] ^ tab4[1][(crc >> 16) as u8 as usize] ^ tab4[2][(crc >> 8) as u8 as usize] ^ tab4[3][(crc) as u8 as usize]; buf = &buf[4..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_multiple(buf: &[u8]) -> u32 { let tab = &*TABLE; let mut crc: u32 =!0; for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_bitwise(buf: &[u8]) -> u32 { let mut crc: u32 =!0; for &b in buf { crc ^= b as u32; for _ in 0..8 { crc = (crc >> 1) ^ ((crc & 1) * CASTAGNOLI_POLY); } } !crc } fn make_table(poly: u32) -> [u32; 256] { let mut tab = [0; 256]; for i in 0u32..256u32 { let mut crc = i; for _ in 0..8 { if crc & 1 == 1 { crc = (crc >> 1) ^ poly; } else { crc >>= 1; } } tab[i as usize] = crc; } tab }
for i in 0..256 {
random_line_split
crc32.rs
// Sadly, all of the crc crates in Rust appear to be insufficient for high // performance algorithms. In fact, the implementation here is insufficient! // The best implementation uses the CRC32 instruction from SSE 4.2, but using // specialty instructions on stable Rust is an absolute nightmare at the // moment. The only way I can think to do it is to write some Assembly in a // separate source file and run an Assembler from build.rs. But we'd need to be // careful to only do this on platforms that support the CRC32 instruction, // which means we'd need to query CPUID. There are a couple Rust crates for // that, but of course, they only work on unstable Rust so we'd need to hand // roll that too. // // As a stopgap, we implement the fastest (slicing-by-16) algorithm described // here: http://create.stephan-brumme.com/crc32/ // (Actually, slicing-by-16 doesn't seem to be measurably faster than // slicing-by-8 on my i7-6900K, so use slicing-by-8.) // // For Snappy, we only care about CRC32C (32 bit, Castagnoli). // // ---AG // We have a bunch of different implementations of crc32 below that seem // somewhat useful to leave around for easy benchmarking. #![allow(dead_code)] use byteorder::{ByteOrder, LittleEndian as LE}; const CASTAGNOLI_POLY: u32 = 0x82f63b78; lazy_static! { static ref TABLE: [u32; 256] = make_table(CASTAGNOLI_POLY); static ref TABLE16: [[u32; 256]; 16] = { let mut tab = [[0; 256]; 16]; tab[0] = make_table(CASTAGNOLI_POLY); for i in 0..256 { let mut crc = tab[0][i]; for j in 1..16 { crc = (crc >> 8) ^ tab[0][crc as u8 as usize]; tab[j][i] = crc; } } tab }; } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. pub fn crc32c(buf: &[u8]) -> u32 { // I can't measure any difference between slice8 and slice16. crc32c_slice8(buf) } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice16(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab16 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 16 { crc ^= LE::read_u32(&buf[0..4]); crc = tab16[0][buf[15] as usize] ^ tab16[1][buf[14] as usize] ^ tab16[2][buf[13] as usize] ^ tab16[3][buf[12] as usize] ^ tab16[4][buf[11] as usize] ^ tab16[5][buf[10] as usize] ^ tab16[6][buf[9] as usize] ^ tab16[7][buf[8] as usize] ^ tab16[8][buf[7] as usize] ^ tab16[9][buf[6] as usize] ^ tab16[10][buf[5] as usize] ^ tab16[11][buf[4] as usize] ^ tab16[12][(crc >> 24) as u8 as usize] ^ tab16[13][(crc >> 16) as u8 as usize] ^ tab16[14][(crc >> 8) as u8 as usize] ^ tab16[15][(crc) as u8 as usize]; buf = &buf[16..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice8(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab8 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 8 { crc ^= LE::read_u32(&buf[0..4]); crc = tab8[0][buf[7] as usize] ^ tab8[1][buf[6] as usize] ^ tab8[2][buf[5] as usize] ^ tab8[3][buf[4] as usize] ^ tab8[4][(crc >> 24) as u8 as usize] ^ tab8[5][(crc >> 16) as u8 as usize] ^ tab8[6][(crc >> 8) as u8 as usize] ^ tab8[7][(crc) as u8 as usize]; buf = &buf[8..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice4(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab4 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 4 { crc ^= LE::read_u32(&buf[0..4]); crc = tab4[0][(crc >> 24) as u8 as usize] ^ tab4[1][(crc >> 16) as u8 as usize] ^ tab4[2][(crc >> 8) as u8 as usize] ^ tab4[3][(crc) as u8 as usize]; buf = &buf[4..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn
(buf: &[u8]) -> u32 { let tab = &*TABLE; let mut crc: u32 =!0; for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_bitwise(buf: &[u8]) -> u32 { let mut crc: u32 =!0; for &b in buf { crc ^= b as u32; for _ in 0..8 { crc = (crc >> 1) ^ ((crc & 1) * CASTAGNOLI_POLY); } } !crc } fn make_table(poly: u32) -> [u32; 256] { let mut tab = [0; 256]; for i in 0u32..256u32 { let mut crc = i; for _ in 0..8 { if crc & 1 == 1 { crc = (crc >> 1) ^ poly; } else { crc >>= 1; } } tab[i as usize] = crc; } tab }
crc32c_multiple
identifier_name
crc32.rs
// Sadly, all of the crc crates in Rust appear to be insufficient for high // performance algorithms. In fact, the implementation here is insufficient! // The best implementation uses the CRC32 instruction from SSE 4.2, but using // specialty instructions on stable Rust is an absolute nightmare at the // moment. The only way I can think to do it is to write some Assembly in a // separate source file and run an Assembler from build.rs. But we'd need to be // careful to only do this on platforms that support the CRC32 instruction, // which means we'd need to query CPUID. There are a couple Rust crates for // that, but of course, they only work on unstable Rust so we'd need to hand // roll that too. // // As a stopgap, we implement the fastest (slicing-by-16) algorithm described // here: http://create.stephan-brumme.com/crc32/ // (Actually, slicing-by-16 doesn't seem to be measurably faster than // slicing-by-8 on my i7-6900K, so use slicing-by-8.) // // For Snappy, we only care about CRC32C (32 bit, Castagnoli). // // ---AG // We have a bunch of different implementations of crc32 below that seem // somewhat useful to leave around for easy benchmarking. #![allow(dead_code)] use byteorder::{ByteOrder, LittleEndian as LE}; const CASTAGNOLI_POLY: u32 = 0x82f63b78; lazy_static! { static ref TABLE: [u32; 256] = make_table(CASTAGNOLI_POLY); static ref TABLE16: [[u32; 256]; 16] = { let mut tab = [[0; 256]; 16]; tab[0] = make_table(CASTAGNOLI_POLY); for i in 0..256 { let mut crc = tab[0][i]; for j in 1..16 { crc = (crc >> 8) ^ tab[0][crc as u8 as usize]; tab[j][i] = crc; } } tab }; } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. pub fn crc32c(buf: &[u8]) -> u32 { // I can't measure any difference between slice8 and slice16. crc32c_slice8(buf) } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice16(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab16 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 16 { crc ^= LE::read_u32(&buf[0..4]); crc = tab16[0][buf[15] as usize] ^ tab16[1][buf[14] as usize] ^ tab16[2][buf[13] as usize] ^ tab16[3][buf[12] as usize] ^ tab16[4][buf[11] as usize] ^ tab16[5][buf[10] as usize] ^ tab16[6][buf[9] as usize] ^ tab16[7][buf[8] as usize] ^ tab16[8][buf[7] as usize] ^ tab16[9][buf[6] as usize] ^ tab16[10][buf[5] as usize] ^ tab16[11][buf[4] as usize] ^ tab16[12][(crc >> 24) as u8 as usize] ^ tab16[13][(crc >> 16) as u8 as usize] ^ tab16[14][(crc >> 8) as u8 as usize] ^ tab16[15][(crc) as u8 as usize]; buf = &buf[16..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice8(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab8 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 8 { crc ^= LE::read_u32(&buf[0..4]); crc = tab8[0][buf[7] as usize] ^ tab8[1][buf[6] as usize] ^ tab8[2][buf[5] as usize] ^ tab8[3][buf[4] as usize] ^ tab8[4][(crc >> 24) as u8 as usize] ^ tab8[5][(crc >> 16) as u8 as usize] ^ tab8[6][(crc >> 8) as u8 as usize] ^ tab8[7][(crc) as u8 as usize]; buf = &buf[8..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_slice4(mut buf: &[u8]) -> u32 { let tab = &*TABLE; let tab4 = &*TABLE16; let mut crc: u32 =!0; while buf.len() >= 4 { crc ^= LE::read_u32(&buf[0..4]); crc = tab4[0][(crc >> 24) as u8 as usize] ^ tab4[1][(crc >> 16) as u8 as usize] ^ tab4[2][(crc >> 8) as u8 as usize] ^ tab4[3][(crc) as u8 as usize]; buf = &buf[4..]; } for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_multiple(buf: &[u8]) -> u32 { let tab = &*TABLE; let mut crc: u32 =!0; for &b in buf { crc = tab[((crc as u8) ^ b) as usize] ^ (crc >> 8); } !crc } /// Returns the CRC32 checksum of `buf` using the Castagnoli polynomial. fn crc32c_bitwise(buf: &[u8]) -> u32 { let mut crc: u32 =!0; for &b in buf { crc ^= b as u32; for _ in 0..8 { crc = (crc >> 1) ^ ((crc & 1) * CASTAGNOLI_POLY); } } !crc } fn make_table(poly: u32) -> [u32; 256] { let mut tab = [0; 256]; for i in 0u32..256u32 { let mut crc = i; for _ in 0..8 { if crc & 1 == 1 { crc = (crc >> 1) ^ poly; } else
} tab[i as usize] = crc; } tab }
{ crc >>= 1; }
conditional_block
hmac_prf_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for HMAC keys for PRF. use crate::subtle; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, HashType}; /// Maximal version of HMAC PRF keys. pub const HMAC_PRF_KEY_VERSION: u32 = 0; /// Type URL of HMAC PRF keys that Tink supports. pub const HMAC_PRF_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.HmacPrfKey"; /// Generates new HMAC keys and produces new instances of HMAC. #[derive(Default)] pub(crate) struct HmacPrfKeyManager; impl tink_core::registry::KeyManager for HmacPrfKeyManager { /// Construct an HMAC instance for the given serialized [`HmacPrfKey`](tink_proto::HmacPrfKey). fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("HmacPrfKeyManager: invalid key".into()); } let key = tink_proto::HmacPrfKey::decode(serialized_key) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key"))?; let (_params, hash) = validate_key(&key).map_err(|e| wrap_err("HmacPrfKeyManager", e))?; match subtle::HmacPrf::new(hash, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Prf(Box::new(p))), Err(e) => Err(wrap_err("HmacPrfManager: cannot create new primitive", e)), } } /// Generates a new [`HmacPrfKey`](tink_proto::HmacPrfKey) according to specification in the /// given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("HmacPrfKeyManager: invalid key format".into()); } let key_format = tink_proto::HmacPrfKeyFormat::decode(serialized_key_format) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key format"))?; validate_key_format(&key_format) .map_err(|e| wrap_err("HmacPrfKeyManager: invalid key format", e))?; let key_value = tink_core::subtle::random::get_random_bytes(key_format.key_size as usize); let mut sk = Vec::new(); tink_proto::HmacPrfKey { version: HMAC_PRF_KEY_VERSION, params: key_format.params, key_value, } .encode(&mut sk) .map_err(|e| wrap_err("HmacPrfKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { HMAC_PRF_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::Symmetric } } /// Validate the given [`HmacPrfKey`](tink_proto::HmacPrfKey). It only validates the version of the /// key because other parameters will be validated in primitive construction. fn validate_key( key: &tink_proto::HmacPrfKey, ) -> Result<(tink_proto::HmacPrfParams, HashType), TinkError> { tink_core::keyset::validate_key_version(key.version, HMAC_PRF_KEY_VERSION) .map_err(|e| wrap_err("invalid version", e))?; let key_size = key.key_value.len(); let params = match key.params.as_ref() { None => return Err("no key params".into()), Some(p) => p, }; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, key_size)?; Ok((params.clone(), hash))
/// Validates the given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn validate_key_format(format: &tink_proto::HmacPrfKeyFormat) -> Result<(), TinkError> { let params = format .params .as_ref() .ok_or_else(|| TinkError::new("no params"))?; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, format.key_size as usize) }
}
random_line_split
hmac_prf_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for HMAC keys for PRF. use crate::subtle; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, HashType}; /// Maximal version of HMAC PRF keys. pub const HMAC_PRF_KEY_VERSION: u32 = 0; /// Type URL of HMAC PRF keys that Tink supports. pub const HMAC_PRF_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.HmacPrfKey"; /// Generates new HMAC keys and produces new instances of HMAC. #[derive(Default)] pub(crate) struct HmacPrfKeyManager; impl tink_core::registry::KeyManager for HmacPrfKeyManager { /// Construct an HMAC instance for the given serialized [`HmacPrfKey`](tink_proto::HmacPrfKey). fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("HmacPrfKeyManager: invalid key".into()); } let key = tink_proto::HmacPrfKey::decode(serialized_key) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key"))?; let (_params, hash) = validate_key(&key).map_err(|e| wrap_err("HmacPrfKeyManager", e))?; match subtle::HmacPrf::new(hash, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Prf(Box::new(p))), Err(e) => Err(wrap_err("HmacPrfManager: cannot create new primitive", e)), } } /// Generates a new [`HmacPrfKey`](tink_proto::HmacPrfKey) according to specification in the /// given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("HmacPrfKeyManager: invalid key format".into()); } let key_format = tink_proto::HmacPrfKeyFormat::decode(serialized_key_format) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key format"))?; validate_key_format(&key_format) .map_err(|e| wrap_err("HmacPrfKeyManager: invalid key format", e))?; let key_value = tink_core::subtle::random::get_random_bytes(key_format.key_size as usize); let mut sk = Vec::new(); tink_proto::HmacPrfKey { version: HMAC_PRF_KEY_VERSION, params: key_format.params, key_value, } .encode(&mut sk) .map_err(|e| wrap_err("HmacPrfKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { HMAC_PRF_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType
} /// Validate the given [`HmacPrfKey`](tink_proto::HmacPrfKey). It only validates the version of the /// key because other parameters will be validated in primitive construction. fn validate_key( key: &tink_proto::HmacPrfKey, ) -> Result<(tink_proto::HmacPrfParams, HashType), TinkError> { tink_core::keyset::validate_key_version(key.version, HMAC_PRF_KEY_VERSION) .map_err(|e| wrap_err("invalid version", e))?; let key_size = key.key_value.len(); let params = match key.params.as_ref() { None => return Err("no key params".into()), Some(p) => p, }; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, key_size)?; Ok((params.clone(), hash)) } /// Validates the given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn validate_key_format(format: &tink_proto::HmacPrfKeyFormat) -> Result<(), TinkError> { let params = format .params .as_ref() .ok_or_else(|| TinkError::new("no params"))?; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, format.key_size as usize) }
{ tink_proto::key_data::KeyMaterialType::Symmetric }
identifier_body
hmac_prf_key_manager.rs
// Copyright 2020 The Tink-Rust Authors // // 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. // //////////////////////////////////////////////////////////////////////////////// //! Key manager for HMAC keys for PRF. use crate::subtle; use tink_core::{utils::wrap_err, TinkError}; use tink_proto::{prost::Message, HashType}; /// Maximal version of HMAC PRF keys. pub const HMAC_PRF_KEY_VERSION: u32 = 0; /// Type URL of HMAC PRF keys that Tink supports. pub const HMAC_PRF_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.HmacPrfKey"; /// Generates new HMAC keys and produces new instances of HMAC. #[derive(Default)] pub(crate) struct HmacPrfKeyManager; impl tink_core::registry::KeyManager for HmacPrfKeyManager { /// Construct an HMAC instance for the given serialized [`HmacPrfKey`](tink_proto::HmacPrfKey). fn
(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> { if serialized_key.is_empty() { return Err("HmacPrfKeyManager: invalid key".into()); } let key = tink_proto::HmacPrfKey::decode(serialized_key) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key"))?; let (_params, hash) = validate_key(&key).map_err(|e| wrap_err("HmacPrfKeyManager", e))?; match subtle::HmacPrf::new(hash, &key.key_value) { Ok(p) => Ok(tink_core::Primitive::Prf(Box::new(p))), Err(e) => Err(wrap_err("HmacPrfManager: cannot create new primitive", e)), } } /// Generates a new [`HmacPrfKey`](tink_proto::HmacPrfKey) according to specification in the /// given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> { if serialized_key_format.is_empty() { return Err("HmacPrfKeyManager: invalid key format".into()); } let key_format = tink_proto::HmacPrfKeyFormat::decode(serialized_key_format) .map_err(|_| TinkError::new("HmacPrfKeyManager: invalid key format"))?; validate_key_format(&key_format) .map_err(|e| wrap_err("HmacPrfKeyManager: invalid key format", e))?; let key_value = tink_core::subtle::random::get_random_bytes(key_format.key_size as usize); let mut sk = Vec::new(); tink_proto::HmacPrfKey { version: HMAC_PRF_KEY_VERSION, params: key_format.params, key_value, } .encode(&mut sk) .map_err(|e| wrap_err("HmacPrfKeyManager: failed to encode new key", e))?; Ok(sk) } fn type_url(&self) -> &'static str { HMAC_PRF_TYPE_URL } fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType { tink_proto::key_data::KeyMaterialType::Symmetric } } /// Validate the given [`HmacPrfKey`](tink_proto::HmacPrfKey). It only validates the version of the /// key because other parameters will be validated in primitive construction. fn validate_key( key: &tink_proto::HmacPrfKey, ) -> Result<(tink_proto::HmacPrfParams, HashType), TinkError> { tink_core::keyset::validate_key_version(key.version, HMAC_PRF_KEY_VERSION) .map_err(|e| wrap_err("invalid version", e))?; let key_size = key.key_value.len(); let params = match key.params.as_ref() { None => return Err("no key params".into()), Some(p) => p, }; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, key_size)?; Ok((params.clone(), hash)) } /// Validates the given [`HmacPrfKeyFormat`](tink_proto::HmacPrfKeyFormat). fn validate_key_format(format: &tink_proto::HmacPrfKeyFormat) -> Result<(), TinkError> { let params = format .params .as_ref() .ok_or_else(|| TinkError::new("no params"))?; let hash = HashType::from_i32(params.hash).unwrap_or(HashType::UnknownHash); subtle::validate_hmac_prf_params(hash, format.key_size as usize) }
primitive
identifier_name
cp437.rs
//! Convert a string in IBM codepage 437 to UTF-8 /// Trait to convert IBM codepage 437 to the target type pub trait FromCp437 { /// Target type type Target; /// Function that does the conversion from cp437. /// Generally allocations will be avoided if all data falls into the ASCII range. #[allow(clippy::wrong_self_convention)] fn from_cp437(self) -> Self::Target; } impl<'a> FromCp437 for &'a [u8] { type Target = ::std::borrow::Cow<'a, str>; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { ::std::str::from_utf8(self).unwrap().into() } else { self.iter().map(|c| to_char(*c)).collect::<String>().into() } } } impl FromCp437 for Vec<u8> { type Target = String; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { String::from_utf8(self).unwrap() } else { self.into_iter().map(to_char).collect() } } } fn to_char(input: u8) -> char { let output = match input { 0x00..=0x7f => input as u32, 0x80 => 0x00c7, 0x81 => 0x00fc, 0x82 => 0x00e9, 0x83 => 0x00e2, 0x84 => 0x00e4, 0x85 => 0x00e0, 0x86 => 0x00e5, 0x87 => 0x00e7, 0x88 => 0x00ea, 0x89 => 0x00eb, 0x8a => 0x00e8, 0x8b => 0x00ef, 0x8c => 0x00ee, 0x8d => 0x00ec, 0x8e => 0x00c4, 0x8f => 0x00c5, 0x90 => 0x00c9, 0x91 => 0x00e6, 0x92 => 0x00c6, 0x93 => 0x00f4, 0x94 => 0x00f6, 0x95 => 0x00f2, 0x96 => 0x00fb, 0x97 => 0x00f9, 0x98 => 0x00ff, 0x99 => 0x00d6, 0x9a => 0x00dc, 0x9b => 0x00a2, 0x9c => 0x00a3, 0x9d => 0x00a5, 0x9e => 0x20a7, 0x9f => 0x0192, 0xa0 => 0x00e1, 0xa1 => 0x00ed, 0xa2 => 0x00f3, 0xa3 => 0x00fa, 0xa4 => 0x00f1, 0xa5 => 0x00d1, 0xa6 => 0x00aa, 0xa7 => 0x00ba, 0xa8 => 0x00bf, 0xa9 => 0x2310, 0xaa => 0x00ac, 0xab => 0x00bd, 0xac => 0x00bc, 0xad => 0x00a1, 0xae => 0x00ab, 0xaf => 0x00bb, 0xb0 => 0x2591, 0xb1 => 0x2592, 0xb2 => 0x2593, 0xb3 => 0x2502, 0xb4 => 0x2524, 0xb5 => 0x2561, 0xb6 => 0x2562, 0xb7 => 0x2556, 0xb8 => 0x2555, 0xb9 => 0x2563, 0xba => 0x2551, 0xbb => 0x2557, 0xbc => 0x255d, 0xbd => 0x255c, 0xbe => 0x255b, 0xbf => 0x2510, 0xc0 => 0x2514, 0xc1 => 0x2534, 0xc2 => 0x252c, 0xc3 => 0x251c, 0xc4 => 0x2500, 0xc5 => 0x253c, 0xc6 => 0x255e, 0xc7 => 0x255f, 0xc8 => 0x255a, 0xc9 => 0x2554, 0xca => 0x2569, 0xcb => 0x2566, 0xcc => 0x2560, 0xcd => 0x2550, 0xce => 0x256c, 0xcf => 0x2567, 0xd0 => 0x2568, 0xd1 => 0x2564, 0xd2 => 0x2565, 0xd3 => 0x2559, 0xd4 => 0x2558, 0xd5 => 0x2552, 0xd6 => 0x2553, 0xd7 => 0x256b, 0xd8 => 0x256a, 0xd9 => 0x2518, 0xda => 0x250c, 0xdb => 0x2588, 0xdc => 0x2584, 0xdd => 0x258c, 0xde => 0x2590, 0xdf => 0x2580, 0xe0 => 0x03b1, 0xe1 => 0x00df, 0xe2 => 0x0393, 0xe3 => 0x03c0, 0xe4 => 0x03a3, 0xe5 => 0x03c3, 0xe6 => 0x00b5, 0xe7 => 0x03c4, 0xe8 => 0x03a6, 0xe9 => 0x0398, 0xea => 0x03a9, 0xeb => 0x03b4, 0xec => 0x221e, 0xed => 0x03c6, 0xee => 0x03b5, 0xef => 0x2229, 0xf0 => 0x2261, 0xf1 => 0x00b1, 0xf2 => 0x2265, 0xf3 => 0x2264, 0xf4 => 0x2320, 0xf5 => 0x2321, 0xf6 => 0x00f7, 0xf7 => 0x2248, 0xf8 => 0x00b0, 0xf9 => 0x2219, 0xfa => 0x00b7, 0xfb => 0x221a, 0xfc => 0x207f, 0xfd => 0x00b2, 0xfe => 0x25a0, 0xff => 0x00a0, }; ::std::char::from_u32(output).unwrap() } #[cfg(test)] mod test { #[test] fn to_char_valid() { for i in 0x00_u32..0x100 { super::to_char(i as u8); } } #[test] fn ascii()
#[test] fn example_slice() { use super::FromCp437; let data = b"Cura\x87ao"; assert!(::std::str::from_utf8(data).is_err()); assert_eq!(data.from_cp437(), "Curaçao"); } #[test] fn example_vec() { use super::FromCp437; let data = vec![0xCC, 0xCD, 0xCD, 0xB9]; assert!(String::from_utf8(data.clone()).is_err()); assert_eq!(&data.from_cp437(), "╠══╣"); } }
{ for i in 0x00..0x80 { assert_eq!(super::to_char(i), i as char); } }
identifier_body
cp437.rs
//! Convert a string in IBM codepage 437 to UTF-8 /// Trait to convert IBM codepage 437 to the target type pub trait FromCp437 { /// Target type type Target; /// Function that does the conversion from cp437. /// Generally allocations will be avoided if all data falls into the ASCII range. #[allow(clippy::wrong_self_convention)] fn from_cp437(self) -> Self::Target; } impl<'a> FromCp437 for &'a [u8] { type Target = ::std::borrow::Cow<'a, str>; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { ::std::str::from_utf8(self).unwrap().into() } else { self.iter().map(|c| to_char(*c)).collect::<String>().into() } } } impl FromCp437 for Vec<u8> { type Target = String; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { String::from_utf8(self).unwrap() } else { self.into_iter().map(to_char).collect() } } } fn to_char(input: u8) -> char { let output = match input { 0x00..=0x7f => input as u32, 0x80 => 0x00c7, 0x81 => 0x00fc, 0x82 => 0x00e9, 0x83 => 0x00e2, 0x84 => 0x00e4, 0x85 => 0x00e0, 0x86 => 0x00e5, 0x87 => 0x00e7, 0x88 => 0x00ea, 0x89 => 0x00eb, 0x8a => 0x00e8, 0x8b => 0x00ef, 0x8c => 0x00ee, 0x8d => 0x00ec, 0x8e => 0x00c4, 0x8f => 0x00c5, 0x90 => 0x00c9, 0x91 => 0x00e6, 0x92 => 0x00c6, 0x93 => 0x00f4, 0x94 => 0x00f6, 0x95 => 0x00f2, 0x96 => 0x00fb, 0x97 => 0x00f9, 0x98 => 0x00ff, 0x99 => 0x00d6, 0x9a => 0x00dc, 0x9b => 0x00a2, 0x9c => 0x00a3, 0x9d => 0x00a5, 0x9e => 0x20a7, 0x9f => 0x0192, 0xa0 => 0x00e1, 0xa1 => 0x00ed, 0xa2 => 0x00f3, 0xa3 => 0x00fa, 0xa4 => 0x00f1, 0xa5 => 0x00d1, 0xa6 => 0x00aa, 0xa7 => 0x00ba, 0xa8 => 0x00bf, 0xa9 => 0x2310, 0xaa => 0x00ac, 0xab => 0x00bd, 0xac => 0x00bc, 0xad => 0x00a1, 0xae => 0x00ab, 0xaf => 0x00bb, 0xb0 => 0x2591, 0xb1 => 0x2592, 0xb2 => 0x2593, 0xb3 => 0x2502, 0xb4 => 0x2524, 0xb5 => 0x2561, 0xb6 => 0x2562, 0xb7 => 0x2556, 0xb8 => 0x2555, 0xb9 => 0x2563, 0xba => 0x2551, 0xbb => 0x2557, 0xbc => 0x255d, 0xbd => 0x255c, 0xbe => 0x255b, 0xbf => 0x2510, 0xc0 => 0x2514, 0xc1 => 0x2534, 0xc2 => 0x252c, 0xc3 => 0x251c, 0xc4 => 0x2500, 0xc5 => 0x253c, 0xc6 => 0x255e, 0xc7 => 0x255f, 0xc8 => 0x255a, 0xc9 => 0x2554, 0xca => 0x2569, 0xcb => 0x2566, 0xcc => 0x2560, 0xcd => 0x2550, 0xce => 0x256c, 0xcf => 0x2567, 0xd0 => 0x2568, 0xd1 => 0x2564, 0xd2 => 0x2565, 0xd3 => 0x2559, 0xd4 => 0x2558, 0xd5 => 0x2552, 0xd6 => 0x2553, 0xd7 => 0x256b, 0xd8 => 0x256a, 0xd9 => 0x2518, 0xda => 0x250c, 0xdb => 0x2588, 0xdc => 0x2584, 0xdd => 0x258c, 0xde => 0x2590, 0xdf => 0x2580, 0xe0 => 0x03b1, 0xe1 => 0x00df, 0xe2 => 0x0393, 0xe3 => 0x03c0, 0xe4 => 0x03a3, 0xe5 => 0x03c3, 0xe6 => 0x00b5, 0xe7 => 0x03c4, 0xe8 => 0x03a6, 0xe9 => 0x0398, 0xea => 0x03a9, 0xeb => 0x03b4, 0xec => 0x221e, 0xed => 0x03c6, 0xee => 0x03b5, 0xef => 0x2229, 0xf0 => 0x2261, 0xf1 => 0x00b1, 0xf2 => 0x2265, 0xf3 => 0x2264, 0xf4 => 0x2320, 0xf5 => 0x2321, 0xf6 => 0x00f7, 0xf7 => 0x2248, 0xf8 => 0x00b0, 0xf9 => 0x2219, 0xfa => 0x00b7, 0xfb => 0x221a, 0xfc => 0x207f, 0xfd => 0x00b2, 0xfe => 0x25a0, 0xff => 0x00a0, }; ::std::char::from_u32(output).unwrap() } #[cfg(test)] mod test { #[test] fn to_char_valid() { for i in 0x00_u32..0x100 { super::to_char(i as u8); } } #[test] fn
() { for i in 0x00..0x80 { assert_eq!(super::to_char(i), i as char); } } #[test] fn example_slice() { use super::FromCp437; let data = b"Cura\x87ao"; assert!(::std::str::from_utf8(data).is_err()); assert_eq!(data.from_cp437(), "Curaçao"); } #[test] fn example_vec() { use super::FromCp437; let data = vec![0xCC, 0xCD, 0xCD, 0xB9]; assert!(String::from_utf8(data.clone()).is_err()); assert_eq!(&data.from_cp437(), "╠══╣"); } }
ascii
identifier_name
cp437.rs
//! Convert a string in IBM codepage 437 to UTF-8 /// Trait to convert IBM codepage 437 to the target type pub trait FromCp437 { /// Target type type Target; /// Function that does the conversion from cp437. /// Generally allocations will be avoided if all data falls into the ASCII range. #[allow(clippy::wrong_self_convention)] fn from_cp437(self) -> Self::Target; } impl<'a> FromCp437 for &'a [u8] { type Target = ::std::borrow::Cow<'a, str>; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { ::std::str::from_utf8(self).unwrap().into() } else {
impl FromCp437 for Vec<u8> { type Target = String; fn from_cp437(self) -> Self::Target { if self.iter().all(|c| *c < 0x80) { String::from_utf8(self).unwrap() } else { self.into_iter().map(to_char).collect() } } } fn to_char(input: u8) -> char { let output = match input { 0x00..=0x7f => input as u32, 0x80 => 0x00c7, 0x81 => 0x00fc, 0x82 => 0x00e9, 0x83 => 0x00e2, 0x84 => 0x00e4, 0x85 => 0x00e0, 0x86 => 0x00e5, 0x87 => 0x00e7, 0x88 => 0x00ea, 0x89 => 0x00eb, 0x8a => 0x00e8, 0x8b => 0x00ef, 0x8c => 0x00ee, 0x8d => 0x00ec, 0x8e => 0x00c4, 0x8f => 0x00c5, 0x90 => 0x00c9, 0x91 => 0x00e6, 0x92 => 0x00c6, 0x93 => 0x00f4, 0x94 => 0x00f6, 0x95 => 0x00f2, 0x96 => 0x00fb, 0x97 => 0x00f9, 0x98 => 0x00ff, 0x99 => 0x00d6, 0x9a => 0x00dc, 0x9b => 0x00a2, 0x9c => 0x00a3, 0x9d => 0x00a5, 0x9e => 0x20a7, 0x9f => 0x0192, 0xa0 => 0x00e1, 0xa1 => 0x00ed, 0xa2 => 0x00f3, 0xa3 => 0x00fa, 0xa4 => 0x00f1, 0xa5 => 0x00d1, 0xa6 => 0x00aa, 0xa7 => 0x00ba, 0xa8 => 0x00bf, 0xa9 => 0x2310, 0xaa => 0x00ac, 0xab => 0x00bd, 0xac => 0x00bc, 0xad => 0x00a1, 0xae => 0x00ab, 0xaf => 0x00bb, 0xb0 => 0x2591, 0xb1 => 0x2592, 0xb2 => 0x2593, 0xb3 => 0x2502, 0xb4 => 0x2524, 0xb5 => 0x2561, 0xb6 => 0x2562, 0xb7 => 0x2556, 0xb8 => 0x2555, 0xb9 => 0x2563, 0xba => 0x2551, 0xbb => 0x2557, 0xbc => 0x255d, 0xbd => 0x255c, 0xbe => 0x255b, 0xbf => 0x2510, 0xc0 => 0x2514, 0xc1 => 0x2534, 0xc2 => 0x252c, 0xc3 => 0x251c, 0xc4 => 0x2500, 0xc5 => 0x253c, 0xc6 => 0x255e, 0xc7 => 0x255f, 0xc8 => 0x255a, 0xc9 => 0x2554, 0xca => 0x2569, 0xcb => 0x2566, 0xcc => 0x2560, 0xcd => 0x2550, 0xce => 0x256c, 0xcf => 0x2567, 0xd0 => 0x2568, 0xd1 => 0x2564, 0xd2 => 0x2565, 0xd3 => 0x2559, 0xd4 => 0x2558, 0xd5 => 0x2552, 0xd6 => 0x2553, 0xd7 => 0x256b, 0xd8 => 0x256a, 0xd9 => 0x2518, 0xda => 0x250c, 0xdb => 0x2588, 0xdc => 0x2584, 0xdd => 0x258c, 0xde => 0x2590, 0xdf => 0x2580, 0xe0 => 0x03b1, 0xe1 => 0x00df, 0xe2 => 0x0393, 0xe3 => 0x03c0, 0xe4 => 0x03a3, 0xe5 => 0x03c3, 0xe6 => 0x00b5, 0xe7 => 0x03c4, 0xe8 => 0x03a6, 0xe9 => 0x0398, 0xea => 0x03a9, 0xeb => 0x03b4, 0xec => 0x221e, 0xed => 0x03c6, 0xee => 0x03b5, 0xef => 0x2229, 0xf0 => 0x2261, 0xf1 => 0x00b1, 0xf2 => 0x2265, 0xf3 => 0x2264, 0xf4 => 0x2320, 0xf5 => 0x2321, 0xf6 => 0x00f7, 0xf7 => 0x2248, 0xf8 => 0x00b0, 0xf9 => 0x2219, 0xfa => 0x00b7, 0xfb => 0x221a, 0xfc => 0x207f, 0xfd => 0x00b2, 0xfe => 0x25a0, 0xff => 0x00a0, }; ::std::char::from_u32(output).unwrap() } #[cfg(test)] mod test { #[test] fn to_char_valid() { for i in 0x00_u32..0x100 { super::to_char(i as u8); } } #[test] fn ascii() { for i in 0x00..0x80 { assert_eq!(super::to_char(i), i as char); } } #[test] fn example_slice() { use super::FromCp437; let data = b"Cura\x87ao"; assert!(::std::str::from_utf8(data).is_err()); assert_eq!(data.from_cp437(), "Curaçao"); } #[test] fn example_vec() { use super::FromCp437; let data = vec![0xCC, 0xCD, 0xCD, 0xB9]; assert!(String::from_utf8(data.clone()).is_err()); assert_eq!(&data.from_cp437(), "╠══╣"); } }
self.iter().map(|c| to_char(*c)).collect::<String>().into() } } }
random_line_split
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT { match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win,.. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed); 0 }, winapi::WM_ERASEBKGND =>
, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y))); 0 }, winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Right)); 0 }, winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, x if x == *super::WAKEUP_MSG_ID => { use events::Event::Awakened; send_event(window, Awakened); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
{ 1 }
conditional_block
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn
(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT { match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win,.. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed); 0 }, winapi::WM_ERASEBKGND => { 1 }, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y))); 0 }, winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Right)); 0 }, winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, x if x == *super::WAKEUP_MSG_ID => { use events::Event::Awakened; send_event(window, Awakened); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
callback
identifier_name
callback.rs
use std::mem; use std::ptr; use std::cell::RefCell; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use CursorState; use Event; use super::event; use user32; use shell32; use winapi; /// There's no parameters passed to the callback function, so it needs to get /// its context (the HWND, the Sender for events, etc.) stashed in /// a thread-local variable. thread_local!(pub static CONTEXT_STASH: RefCell<Option<ThreadLocalData>> = RefCell::new(None)); pub struct ThreadLocalData { pub win: winapi::HWND, pub sender: Sender<Event>, pub cursor_state: Arc<Mutex<CursorState>> } /// Checks that the window is the good one, and if so send the event to it. fn send_event(input_window: winapi::HWND, event: Event) { CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win, ref sender,.. } = stored; if win!= &input_window { return; } sender.send(event).ok(); // ignoring if closed }); } /// This is the callback that is called by `DispatchMessage` in the events loop. /// /// Returning 0 tells the Win32 API that the message has been processed. // FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary pub unsafe extern "system" fn callback(window: winapi::HWND, msg: winapi::UINT, wparam: winapi::WPARAM, lparam: winapi::LPARAM) -> winapi::LRESULT { match msg { winapi::WM_DESTROY => { use events::Event::Closed; CONTEXT_STASH.with(|context_stash| { let context_stash = context_stash.borrow(); let stored = match *context_stash { None => return, Some(ref v) => v }; let &ThreadLocalData { ref win,.. } = stored; if win == &window { user32::PostQuitMessage(0); } }); send_event(window, Closed); 0 }, winapi::WM_ERASEBKGND => { 1 }, winapi::WM_SIZE => { use events::Event::Resized; let w = winapi::LOWORD(lparam as winapi::DWORD) as u32; let h = winapi::HIWORD(lparam as winapi::DWORD) as u32; send_event(window, Resized(w, h)); 0 }, winapi::WM_MOVE => { use events::Event::Moved; let x = winapi::LOWORD(lparam as winapi::DWORD) as i32; let y = winapi::HIWORD(lparam as winapi::DWORD) as i32; send_event(window, Moved(x, y)); 0 }, winapi::WM_CHAR => { use std::mem; use events::Event::ReceivedCharacter; let chr: char = mem::transmute(wparam as u32); send_event(window, ReceivedCharacter(chr)); 0 }, // Prevents default windows menu hotkeys playing unwanted // "ding" sounds. Alternatively could check for WM_SYSCOMMAND // with wparam being SC_KEYMENU, but this may prevent some // other unwanted default hotkeys as well. winapi::WM_SYSCHAR => { 0 } winapi::WM_MOUSEMOVE => { use events::Event::MouseMoved; let x = winapi::GET_X_LPARAM(lparam) as i32; let y = winapi::GET_Y_LPARAM(lparam) as i32; send_event(window, MouseMoved((x, y))); 0 }, winapi::WM_MOUSEWHEEL => { use events::Event::MouseWheel; use events::MouseScrollDelta::LineDelta; let value = (wparam >> 16) as i16; let value = value as i32; let value = value as f32 / winapi::WHEEL_DELTA as f32; send_event(window, MouseWheel(LineDelta(0.0, value))); 0 }, winapi::WM_KEYDOWN | winapi::WM_SYSKEYDOWN => { use events::Event::KeyboardInput; use events::ElementState::Pressed; if msg == winapi::WM_SYSKEYDOWN && wparam as i32 == winapi::VK_F4 { user32::DefWindowProcW(window, msg, wparam, lparam) } else { let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Pressed, scancode, vkey)); 0 } }, winapi::WM_KEYUP | winapi::WM_SYSKEYUP => { use events::Event::KeyboardInput; use events::ElementState::Released; let (scancode, vkey) = event::vkeycode_to_element(wparam, lparam); send_event(window, KeyboardInput(Released, scancode, vkey)); 0 }, winapi::WM_LBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Left)); 0 }, winapi::WM_LBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Left; use events::ElementState::Released; send_event(window, MouseInput(Released, Left)); 0 }, winapi::WM_RBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Pressed;
winapi::WM_RBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Right; use events::ElementState::Released; send_event(window, MouseInput(Released, Right)); 0 }, winapi::WM_MBUTTONDOWN => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Pressed; send_event(window, MouseInput(Pressed, Middle)); 0 }, winapi::WM_MBUTTONUP => { use events::Event::MouseInput; use events::MouseButton::Middle; use events::ElementState::Released; send_event(window, MouseInput(Released, Middle)); 0 }, winapi::WM_INPUT => { let mut data: winapi::RAWINPUT = mem::uninitialized(); let mut data_size = mem::size_of::<winapi::RAWINPUT>() as winapi::UINT; user32::GetRawInputData(mem::transmute(lparam), winapi::RID_INPUT, mem::transmute(&mut data), &mut data_size, mem::size_of::<winapi::RAWINPUTHEADER>() as winapi::UINT); if data.header.dwType == winapi::RIM_TYPEMOUSE { let _x = data.mouse.lLastX; // FIXME: this is not always the relative movement let _y = data.mouse.lLastY; // TODO: //send_event(window, Event::MouseRawMovement { x: x, y: y }); 0 } else { user32::DefWindowProcW(window, msg, wparam, lparam) } }, winapi::WM_SETFOCUS => { use events::Event::Focused; send_event(window, Focused(true)); 0 }, winapi::WM_KILLFOCUS => { use events::Event::Focused; send_event(window, Focused(false)); 0 }, winapi::WM_SETCURSOR => { CONTEXT_STASH.with(|context_stash| { let cstash = context_stash.borrow(); let cstash = cstash.as_ref(); // there's a very bizarre borrow checker bug // possibly related to rust-lang/rust/#23338 let _cursor_state = if let Some(cstash) = cstash { if let Ok(cursor_state) = cstash.cursor_state.lock() { match *cursor_state { CursorState::Normal => { user32::SetCursor(user32::LoadCursorW( ptr::null_mut(), winapi::IDC_ARROW)); }, CursorState::Grab | CursorState::Hide => { user32::SetCursor(ptr::null_mut()); } } } } else { return }; // let &ThreadLocalData { ref cursor_state,.. } = stored; }); 0 }, winapi::WM_DROPFILES => { use events::Event::DroppedFile; let hdrop = wparam as winapi::HDROP; let mut pathbuf: [u16; winapi::MAX_PATH] = mem::uninitialized(); let num_drops = shell32::DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); for i in 0..num_drops { let nch = shell32::DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), winapi::MAX_PATH as u32) as usize; if nch > 0 { send_event(window, DroppedFile(OsString::from_wide(&pathbuf[0..nch]).into())); } } shell32::DragFinish(hdrop); 0 }, x if x == *super::WAKEUP_MSG_ID => { use events::Event::Awakened; send_event(window, Awakened); 0 }, _ => { user32::DefWindowProcW(window, msg, wparam, lparam) } } }
send_event(window, MouseInput(Pressed, Right)); 0 },
random_line_split
index.rs
//! Index for finding Project Gutenberg texts by subject, author, or title. /* * ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data * Copyright 2015 Tommy M. McGuire * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ use std::cmp::{Ord,Ordering}; use std::collections::HashMap; use iterator_utilities::equivalence_class::equivalence_classes; use metadata::Metadata; use nysiis::encode_strict; use recommendation::{Etext,Score}; type ScoredResult = (Etext,Score); type ScoredDictionary = HashMap<String,Vec<ScoredResult>>; #[derive(Debug)] pub struct Index { index: ScoredDictionary, } impl Index { pub fn new(metadata: &Metadata) -> Index { // Compute a vector of keyword, etext_no, simple score triples. let mut postings: Vec<(String,Etext,Score)> = Vec::new(); for (&etext_no, text) in metadata.iter() { postings.extend( text.title.split(' ').map(encode_strict).map( |t| (t, etext_no, 3.0) ) ); postings.extend( text.author.split(' ').map(encode_strict).map( |a| (a, etext_no, 2.0) ) ); postings.extend( text.subject.split(' ').map(encode_strict).map( |s| (s, etext_no, 1.0) ) ); } // Sort postings by keyword, then by etext_no. postings.sort_by(compare); // Accumulate scores for keyword, etext_no, then insert // etext_no and combined score into index under keyword. let mut index = HashMap::new(); for cls in equivalence_classes(&postings, |l,r| l.0 == r.0 && l.1 == r.1 ) { let r: (&str,Etext,Score) = cls.fold(("", 0, 0 as Score), |a,p| (&p.0, p.1, a.2+p.2)); index.entry(r.0.to_string()).or_insert( Vec::new() ).push( (r.1,r.2) ); } // Sort stored postings lists by etext_no. for (_,postings) in index.iter_mut() { postings.sort_by(|l,r| l.0.cmp(&r.0)); } Index { index: index } } pub fn
(&self, s: &str) -> Vec<ScoredResult> { let mut results = Vec::new(); for key in s.split(' ').map( encode_strict ) { self.accept_or_merge_postings(&mut results, &key); } // Sort results by score, decreasing. results.sort_by( |l,r| { match l.1.partial_cmp(&r.1) { Some(o) => o.reverse(), // floating point numbers are a pain in the ass. None => unimplemented!() } }); results } fn accept_or_merge_postings(&self, results: &mut Vec<ScoredResult>, key: &String) { match self.index.get(key) { Some(postings) => { if results.len() == 0 { for posting in postings.iter() { results.push(posting.clone()); } } else { merge_postings(results, postings); } } None => { } } } } fn merge_postings(results: &mut Vec<ScoredResult>, postings: &Vec<ScoredResult>) { let mut r = 0; let mut p = 0; while r < results.len() && p < postings.len() { if results[r].0 > postings[p].0 { p += 1; } else if results[r].0 < postings[p].0 { results.remove(r); } else /* results[r].0 == postings[p].0 */ { results[r].1 += postings[p].1; r += 1; p += 1; } } while r < results.len() { results.remove(r); } } fn compare(left: &(String,Etext,Score), right: &(String,Etext,Score)) -> Ordering { match left.0.cmp(&right.0) { Ordering::Equal => left.1.cmp(&right.1), other => other } }
get_entries
identifier_name
index.rs
//! Index for finding Project Gutenberg texts by subject, author, or title. /* * ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data * Copyright 2015 Tommy M. McGuire * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ use std::cmp::{Ord,Ordering}; use std::collections::HashMap; use iterator_utilities::equivalence_class::equivalence_classes; use metadata::Metadata; use nysiis::encode_strict; use recommendation::{Etext,Score}; type ScoredResult = (Etext,Score); type ScoredDictionary = HashMap<String,Vec<ScoredResult>>; #[derive(Debug)] pub struct Index { index: ScoredDictionary, } impl Index { pub fn new(metadata: &Metadata) -> Index { // Compute a vector of keyword, etext_no, simple score triples. let mut postings: Vec<(String,Etext,Score)> = Vec::new(); for (&etext_no, text) in metadata.iter() { postings.extend( text.title.split(' ').map(encode_strict).map( |t| (t, etext_no, 3.0) ) ); postings.extend( text.author.split(' ').map(encode_strict).map( |a| (a, etext_no, 2.0) ) ); postings.extend( text.subject.split(' ').map(encode_strict).map( |s| (s, etext_no, 1.0) ) ); } // Sort postings by keyword, then by etext_no. postings.sort_by(compare); // Accumulate scores for keyword, etext_no, then insert // etext_no and combined score into index under keyword. let mut index = HashMap::new(); for cls in equivalence_classes(&postings, |l,r| l.0 == r.0 && l.1 == r.1 ) { let r: (&str,Etext,Score) = cls.fold(("", 0, 0 as Score), |a,p| (&p.0, p.1, a.2+p.2)); index.entry(r.0.to_string()).or_insert( Vec::new() ).push( (r.1,r.2) ); } // Sort stored postings lists by etext_no. for (_,postings) in index.iter_mut() { postings.sort_by(|l,r| l.0.cmp(&r.0)); } Index { index: index } } pub fn get_entries(&self, s: &str) -> Vec<ScoredResult>
fn accept_or_merge_postings(&self, results: &mut Vec<ScoredResult>, key: &String) { match self.index.get(key) { Some(postings) => { if results.len() == 0 { for posting in postings.iter() { results.push(posting.clone()); } } else { merge_postings(results, postings); } } None => { } } } } fn merge_postings(results: &mut Vec<ScoredResult>, postings: &Vec<ScoredResult>) { let mut r = 0; let mut p = 0; while r < results.len() && p < postings.len() { if results[r].0 > postings[p].0 { p += 1; } else if results[r].0 < postings[p].0 { results.remove(r); } else /* results[r].0 == postings[p].0 */ { results[r].1 += postings[p].1; r += 1; p += 1; } } while r < results.len() { results.remove(r); } } fn compare(left: &(String,Etext,Score), right: &(String,Etext,Score)) -> Ordering { match left.0.cmp(&right.0) { Ordering::Equal => left.1.cmp(&right.1), other => other } }
{ let mut results = Vec::new(); for key in s.split(' ').map( encode_strict ) { self.accept_or_merge_postings(&mut results, &key); } // Sort results by score, decreasing. results.sort_by( |l,r| { match l.1.partial_cmp(&r.1) { Some(o) => o.reverse(), // floating point numbers are a pain in the ass. None => unimplemented!() } }); results }
identifier_body
index.rs
//! Index for finding Project Gutenberg texts by subject, author, or title. /* * ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data * Copyright 2015 Tommy M. McGuire * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. *
* along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ use std::cmp::{Ord,Ordering}; use std::collections::HashMap; use iterator_utilities::equivalence_class::equivalence_classes; use metadata::Metadata; use nysiis::encode_strict; use recommendation::{Etext,Score}; type ScoredResult = (Etext,Score); type ScoredDictionary = HashMap<String,Vec<ScoredResult>>; #[derive(Debug)] pub struct Index { index: ScoredDictionary, } impl Index { pub fn new(metadata: &Metadata) -> Index { // Compute a vector of keyword, etext_no, simple score triples. let mut postings: Vec<(String,Etext,Score)> = Vec::new(); for (&etext_no, text) in metadata.iter() { postings.extend( text.title.split(' ').map(encode_strict).map( |t| (t, etext_no, 3.0) ) ); postings.extend( text.author.split(' ').map(encode_strict).map( |a| (a, etext_no, 2.0) ) ); postings.extend( text.subject.split(' ').map(encode_strict).map( |s| (s, etext_no, 1.0) ) ); } // Sort postings by keyword, then by etext_no. postings.sort_by(compare); // Accumulate scores for keyword, etext_no, then insert // etext_no and combined score into index under keyword. let mut index = HashMap::new(); for cls in equivalence_classes(&postings, |l,r| l.0 == r.0 && l.1 == r.1 ) { let r: (&str,Etext,Score) = cls.fold(("", 0, 0 as Score), |a,p| (&p.0, p.1, a.2+p.2)); index.entry(r.0.to_string()).or_insert( Vec::new() ).push( (r.1,r.2) ); } // Sort stored postings lists by etext_no. for (_,postings) in index.iter_mut() { postings.sort_by(|l,r| l.0.cmp(&r.0)); } Index { index: index } } pub fn get_entries(&self, s: &str) -> Vec<ScoredResult> { let mut results = Vec::new(); for key in s.split(' ').map( encode_strict ) { self.accept_or_merge_postings(&mut results, &key); } // Sort results by score, decreasing. results.sort_by( |l,r| { match l.1.partial_cmp(&r.1) { Some(o) => o.reverse(), // floating point numbers are a pain in the ass. None => unimplemented!() } }); results } fn accept_or_merge_postings(&self, results: &mut Vec<ScoredResult>, key: &String) { match self.index.get(key) { Some(postings) => { if results.len() == 0 { for posting in postings.iter() { results.push(posting.clone()); } } else { merge_postings(results, postings); } } None => { } } } } fn merge_postings(results: &mut Vec<ScoredResult>, postings: &Vec<ScoredResult>) { let mut r = 0; let mut p = 0; while r < results.len() && p < postings.len() { if results[r].0 > postings[p].0 { p += 1; } else if results[r].0 < postings[p].0 { results.remove(r); } else /* results[r].0 == postings[p].0 */ { results[r].1 += postings[p].1; r += 1; p += 1; } } while r < results.len() { results.remove(r); } } fn compare(left: &(String,Etext,Score), right: &(String,Etext,Score)) -> Ordering { match left.0.cmp(&right.0) { Ordering::Equal => left.1.cmp(&right.1), other => other } }
* You should have received a copy of the GNU General Public License
random_line_split
boss.rs
// Copyright 2015 SiegeLord // // See LICENSE for terms. use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE}; use dollar::new_dollar; use std::f32::consts::PI; use rand::{self, Rng}; use allegro::*; pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) -> Object { let mut obj = Object::new(state.new_id()); obj.is_boss = true; obj.has_pos = true; obj.x = BOSS_RX; obj.y = -DEATH; obj.parent = parent; obj.start_time = state.time; obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.png").unwrap()); obj.color = random_color(); obj.size = 32.0; obj.dollar_spawn_color = dollar_spawn_color; obj } simple_behavior! { BossLogic[obj.is_boss] |obj, state| { let theta = 2.0 * PI * (state.time - obj.start_time) / BOSS_RATE; obj.x = BOSS_RX * theta.cos(); obj.y = BOSS_RY * theta.sin() - DEATH; let mut rng = rand::thread_rng();
{ let n = 13; for i in 0..n { let theta = 2.0 * PI * (i as f32) / (n as f32); let dollar = new_dollar(obj.parent, obj.dollar_spawn_color, obj.x, obj.y, theta.cos() * 256.0, theta.sin() * 256.0, state); state.add_object(dollar); } } } }
if rng.gen::<f32>() < 0.2 * DT
random_line_split
boss.rs
// Copyright 2015 SiegeLord // // See LICENSE for terms. use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE}; use dollar::new_dollar; use std::f32::consts::PI; use rand::{self, Rng}; use allegro::*; pub fn
(parent: usize, dollar_spawn_color: Color, state: &mut GameState) -> Object { let mut obj = Object::new(state.new_id()); obj.is_boss = true; obj.has_pos = true; obj.x = BOSS_RX; obj.y = -DEATH; obj.parent = parent; obj.start_time = state.time; obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.png").unwrap()); obj.color = random_color(); obj.size = 32.0; obj.dollar_spawn_color = dollar_spawn_color; obj } simple_behavior! { BossLogic[obj.is_boss] |obj, state| { let theta = 2.0 * PI * (state.time - obj.start_time) / BOSS_RATE; obj.x = BOSS_RX * theta.cos(); obj.y = BOSS_RY * theta.sin() - DEATH; let mut rng = rand::thread_rng(); if rng.gen::<f32>() < 0.2 * DT { let n = 13; for i in 0..n { let theta = 2.0 * PI * (i as f32) / (n as f32); let dollar = new_dollar(obj.parent, obj.dollar_spawn_color, obj.x, obj.y, theta.cos() * 256.0, theta.sin() * 256.0, state); state.add_object(dollar); } } } }
new_boss
identifier_name
boss.rs
// Copyright 2015 SiegeLord // // See LICENSE for terms. use game_state::{GameState, random_color, Object, DEATH, DT, BOSS_RX, BOSS_RY, BOSS_RATE}; use dollar::new_dollar; use std::f32::consts::PI; use rand::{self, Rng}; use allegro::*; pub fn new_boss(parent: usize, dollar_spawn_color: Color, state: &mut GameState) -> Object
simple_behavior! { BossLogic[obj.is_boss] |obj, state| { let theta = 2.0 * PI * (state.time - obj.start_time) / BOSS_RATE; obj.x = BOSS_RX * theta.cos(); obj.y = BOSS_RY * theta.sin() - DEATH; let mut rng = rand::thread_rng(); if rng.gen::<f32>() < 0.2 * DT { let n = 13; for i in 0..n { let theta = 2.0 * PI * (i as f32) / (n as f32); let dollar = new_dollar(obj.parent, obj.dollar_spawn_color, obj.x, obj.y, theta.cos() * 256.0, theta.sin() * 256.0, state); state.add_object(dollar); } } } }
{ let mut obj = Object::new(state.new_id()); obj.is_boss = true; obj.has_pos = true; obj.x = BOSS_RX; obj.y = -DEATH; obj.parent = parent; obj.start_time = state.time; obj.sprite = Some(state.bitmap_manager.load(&state.core, "data/boss.png").unwrap()); obj.color = random_color(); obj.size = 32.0; obj.dollar_spawn_color = dollar_spawn_color; obj }
identifier_body
utils.rs
val::JSVal; use js::jsval::{PrivateValue, ObjectValue, NullValue}; use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue}; use js::rust::with_compartment; use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT}; use js::JSFUN_CONSTRUCTOR; use js; /// Proxy handler for a WindowProxy. pub struct WindowProxyHandler(pub *const libc::c_void); #[allow(raw_pointer_derive)] #[jstraceable] /// Static data associated with a global object. pub struct GlobalStaticData { /// The WindowProxy proxy handler for this global. pub windowproxy_handler: WindowProxyHandler, } impl GlobalStaticData { /// Creates a new GlobalStaticData.
} // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0; /// The index of the slot that contains a reference to the ProtoOrIfaceArray. // All DOM globals must have a slot at DOM_PROTOTYPE_SLOT. pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; /// The flag set on the `JSClass`es for DOM global objects. // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; /// Representation of an IDL constant value. #[derive(Clone)] pub enum ConstantVal { /// `long` constant. IntVal(i32), /// `unsigned long` constant. UintVal(u32), /// `double` constant. DoubleVal(f64), /// `boolean` constant. BoolVal(bool), /// `null` constant. NullVal, } /// Representation of an IDL constant. #[derive(Clone)] pub struct ConstantSpec { /// name of the constant. pub name: &'static [u8], /// value of the constant. pub value: ConstantVal } impl ConstantSpec { /// Returns a `JSVal` that represents the value of this `ConstantSpec`. pub fn get_value(&self) -> JSVal { match self.value { ConstantVal::NullVal => NullValue(), ConstantVal::IntVal(i) => Int32Value(i), ConstantVal::UintVal(u) => UInt32Value(u), ConstantVal::DoubleVal(d) => DoubleValue(d), ConstantVal::BoolVal(b) => BooleanValue(b), } } } /// Helper structure for cross-origin wrappers for DOM binding objects. pub struct NativePropertyHooks { /// The property arrays for this interface. pub native_properties: &'static NativeProperties, /// The NativePropertyHooks instance for the parent interface, if any. pub proto_hooks: Option<&'static NativePropertyHooks>, } /// The struct that holds inheritance information for DOM object reflectors. #[derive(Copy)] pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH], /// The NativePropertyHooks for the interface associated with this class. pub native_hooks: &'static NativePropertyHooks, } unsafe impl Sync for DOMClass {} /// The JSClass used for DOM object reflectors. #[derive(Copy)] pub struct DOMJSClass { /// The actual JSClass. pub base: js::Class, /// Associated data for DOM object reflectors. pub dom_class: DOMClass } unsafe impl Sync for DOMJSClass {} /// Returns the ProtoOrIfaceArray for the given global object. /// Fails if `global` is not a DOM global object. pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut *mut JSObject { unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut *mut JSObject } } /// Contains references to lists of methods, attributes, and constants for a /// given interface. pub struct NativeProperties { /// Instance methods for the interface. pub methods: Option<&'static [JSFunctionSpec]>, /// Instance attributes for the interface. pub attrs: Option<&'static [JSPropertySpec]>, /// Constants for the interface. pub consts: Option<&'static [ConstantSpec]>, /// Static methods for the interface. pub static_methods: Option<&'static [JSFunctionSpec]>, /// Static attributes for the interface. pub static_attrs: Option<&'static [JSPropertySpec]>, } unsafe impl Sync for NativeProperties {} /// A JSNative that cannot be null. pub type NonNullJSNative = unsafe extern "C" fn (arg1: *mut JSContext, arg2: c_uint, arg3: *mut JSVal) -> JSBool; /// Creates the *interface prototype object* and the *interface object* (if /// needed). /// Fails on JSAPI failure. pub fn do_create_interface_objects(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, proto_proto: *mut JSObject, proto_class: &'static JSClass, constructor: Option<(NonNullJSNative, &'static str, u32)>, dom_class: *const DOMClass, members: &'static NativeProperties) -> *mut JSObject { let proto = create_interface_prototype_object(cx, global, proto_proto, proto_class, members); unsafe { JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT, PrivateValue(dom_class as *const libc::c_void)); } match constructor { Some((native, name, nargs)) => { let s = CString::new(name).unwrap(); create_interface_object(cx, global, receiver, native, nargs, proto, members, s.as_ptr()) }, None => (), } proto } /// Creates the *interface object*. /// Fails on JSAPI failure. fn create_interface_object(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, constructor_native: NonNullJSNative, ctor_nargs: u32, proto: *mut JSObject, members: &'static NativeProperties, name: *const libc::c_char) { unsafe { let fun = JS_NewFunction(cx, Some(constructor_native), ctor_nargs, JSFUN_CONSTRUCTOR, global, name); assert!(!fun.is_null()); let constructor = JS_GetFunctionObject(fun); assert!(!constructor.is_null()); if let Some(static_methods) = members.static_methods { define_methods(cx, constructor, static_methods); } if let Some(static_properties) = members.static_attrs { define_properties(cx, constructor, static_properties); } if let Some(constants) = members.consts { define_constants(cx, constructor, constants); } if!proto.is_null() { assert!(JS_LinkConstructorAndPrototype(cx, constructor, proto)!= 0); } let mut already_defined = 0; assert!(JS_AlreadyHasOwnProperty(cx, receiver, name, &mut already_defined)!= 0); if already_defined == 0 { assert!(JS_DefineProperty(cx, receiver, name, ObjectValue(&*constructor), None, None, 0)!= 0); } } } /// Defines constants on `obj`. /// Fails on JSAPI failure. fn define_constants(cx: *mut JSContext, obj: *mut JSObject, constants: &'static [ConstantSpec]) { for spec in constants.iter() { unsafe { assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char, spec.get_value(), None, None, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)!= 0); } } } /// Defines methods on `obj`. The last entry of `methods` must contain zeroed /// memory. /// Fails on JSAPI failure. fn define_methods(cx: *mut JSContext, obj: *mut JSObject, methods: &'static [JSFunctionSpec]) { unsafe { assert!(JS_DefineFunctions(cx, obj, methods.as_ptr())!= 0); } } /// Defines attributes on `obj`. The last entry of `properties` must contain /// zeroed memory. /// Fails on JSAPI failure. fn define_properties(cx: *mut JSContext, obj: *mut JSObject, properties: &'static [JSPropertySpec]) { unsafe { assert!(JS_DefineProperties(cx, obj, properties.as_ptr())!= 0); } } /// Creates the *interface prototype object*. /// Fails on JSAPI failure. fn create_interface_prototype_object(cx: *mut JSContext, global: *mut JSObject, parent_proto: *mut JSObject, proto_class: &'static JSClass, members: &'static NativeProperties) -> *mut JSObject { unsafe { let our_proto = JS_NewObjectWithUniqueType(cx, proto_class, &*parent_proto, &*global); assert!(!our_proto.is_null()); if let Some(methods) = members.methods { define_methods(cx, our_proto, methods); } if let Some(properties) = members.attrs { define_properties(cx, our_proto, properties); } if let Some(constants) = members.consts { define_constants(cx, our_proto, constants); } return our_proto; } } /// A throwing constructor, for those interfaces that have neither /// `NoInterfaceObject` nor `Constructor`. pub unsafe extern fn throwing_constructor(cx: *mut JSContext, _argc: c_uint, _vp: *mut JSVal) -> JSBool { throw_type_error(cx, "Illegal constructor."); return 0; } type ProtoOrIfaceArray = [*mut JSObject; PrototypeList::ID::Count as usize]; /// Construct and cache the ProtoOrIfaceArray for the given global. /// Fails if the argument is not a DOM global. pub fn initialize_global(global: *mut JSObject) { let proto_array: Box<ProtoOrIfaceArray> = box () ([0 as *mut JSObject; PrototypeList::ID::Count as usize]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); let box_ = boxed::into_raw(proto_array); JS_SetReservedSlot(global, DOM_PROTOTYPE_SLOT, PrivateValue(box_ as *const libc::c_void)); } } /// A trait to provide access to the `Reflector` for a DOM object. pub trait Reflectable { /// Returns the receiver's reflector. fn reflector<'a>(&'a self) -> &'a Reflector; } /// Create the reflector for a new DOM object and yield ownership to the /// reflector. pub fn reflect_dom_object<T: Reflectable> (obj: Box<T>, global: GlobalRef, wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<T>) -> Temporary<T>) -> Temporary<T> { wrap_fn(global.get_cx(), global, obj) } /// A struct to store a reference to the reflector of a DOM object. // Allowing unused_attribute because the lint sometimes doesn't run in order #[allow(raw_pointer_derive, unrooted_must_root, unused_attributes)] #[derive(PartialEq)] #[must_root] #[servo_lang = "reflector"] // If you're renaming or moving this field, update the path in plugins::reflector as well pub struct Reflector { object: Cell<*mut JSObject>, } impl Reflector { /// Get the reflector. #[inline] pub fn get_jsobject(&self) -> *mut JSObject { self.object.get() } /// Initialize the reflector. (May be called only once.) pub fn set_jsobject(&self, object: *mut JSObject) { assert!(self.object.get().is_null()); assert!(!object.is_null()); self.object.set(object); } /// Return a pointer to the memory location at which the JS reflector /// object is stored. Used by Temporary values to root the reflector, as /// required by the JSAPI rooting APIs. pub unsafe fn rootable(&self) -> *mut *mut JSObject { self.object.as_unsafe_cell().get() } /// Create an uninitialized `Reflector`. pub fn new() -> Reflector { Reflector { object: Cell::new(ptr::null_mut()), } } } /// Gets the property `id` on `proxy`'s prototype. If it exists, `*found` is /// set to true and `*vp` to the value, otherwise `*found` is set to false. /// /// Returns false on JSAPI failure. pub fn get_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, found: *mut bool, vp: *mut JSVal) -> bool { unsafe { //let proto = GetObjectProto(proxy); let proto = JS_GetPrototype(proxy); if proto.is_null() { *found = false; return true; } let mut has_property = 0; if JS_HasPropertyById(cx, proto, id, &mut has_property) == 0 { return false; } *found = has_property!= 0; let no_output = vp.is_null(); if has_property == 0 || no_output { return true; } JS_ForwardGetPropertyTo(cx, proto, id, proxy, vp)!= 0 } } /// Get an array index from the given `jsid`. Returns `None` if the given /// `jsid` is not an integer. pub fn get_array_index_from_id(_cx: *mut JSContext, id: jsid) -> Option<u32> { unsafe { if RUST_JSID_IS_INT(id)!= 0 { return Some(RUST_JSID_TO_INT(id) as u32); } return None; } // if id is length atom, -1, otherwise /*return if JSID_IS_ATOM(id) { let atom = JSID_TO_ATOM(id); //let s = *GetAtomChars(id); if s > 'a' && s < 'z' { return -1; } let i = 0; let str = AtomToLinearString(JSID_TO_ATOM(id)); return if StringIsArray(str, &mut i)!= 0 { i } else { -1 } } else { IdToInt32(cx, id); }*/ } /// Find the index of a string given by `v` in `values`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no matching string. pub fn find_enum_string_index(cx: *mut JSContext, v: JSVal, values: &[&'static str]) -> Result<Option<usize>, ()> { unsafe { let jsstr = JS_ValueToString(cx, v); if jsstr.is_null() { return Err(()); } let mut length = 0; let chars = JS_GetStringCharsAndLength(cx, jsstr, &mut length); if chars.is_null() { return Err(()); } Ok(values.iter().position(|value| { value.len() == length as usize && range(0, length as usize).all(|j| { value.as_bytes()[j] as u16 == *chars.offset(j as isize) }) })) } } /// Returns wether `obj` is a platform object /// http://heycam.github.io/webidl/#dfn-platform-object pub fn is_platform_object(obj: *mut JSObject) -> bool { unsafe { // Fast-path the common case let mut clasp = JS_GetClass(obj); if is_dom_class(&*clasp) { return true; } // Now for simplicity check for security wrappers before anything else if IsWrapper(obj) == 1 { let unwrapped_obj = UnwrapObject(obj, /* stopAtOuter = */ 0, ptr::null_mut()); if unwrapped_obj.is_null() { return false; } clasp = js::jsapi::JS_GetClass(obj); } // TODO also check if JS_IsArrayBufferObject return is_dom_class(&*clasp); } } /// Get the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no property with the given name. pub fn get_dictionary_property(cx: *mut JSContext, object: *mut JSObject, property: &str) -> Result<Option<JSVal>, ()> { use std::ffi::CString; fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, found: &mut JSBool) -> bool { unsafe { JS_HasProperty(cx, object, property.as_ptr(), found)!= 0 } } fn get_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, value: &mut JSVal) -> bool { unsafe { JS_GetProperty(cx, object, property.as_ptr(), value)!= 0 } } let property = CString::new(property).unwrap(); if object.is_null() { return Ok(None); } let mut found: JSBool = 0; if!has_property(cx, object, &property, &mut found) { return Err(()); } if found == 0 { return Ok(None); } let mut value = NullValue(); if!get_property(cx, object, &property, &mut value) { return Err(()); } Ok(Some(value)) } /// Returns whether `proxy` has a property `id` on its prototype. pub fn has_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid) -> bool { // MOZ_ASSERT(js::IsProxy(proxy) && js::GetProxyHandler(proxy) == handler); let mut found = false; return!get_property_on_prototype(cx, proxy, id, &mut found, ptr::null_mut()) || found; } /// Create a DOM global object with the given class. pub fn create_dom_global(cx: *mut JSContext, class: *const JSClass) -> *mut JSObject { unsafe { let obj = JS_NewGlobalObject(cx, class, ptr::null_mut()); if obj.is_null() { return ptr::null_mut(); } with_compartment(cx, obj, || { JS_InitStandardClasses(cx, obj); }); initialize_global(obj); obj } } /// Drop the resources held by reserved slots of a global object pub unsafe fn finalize_global(obj: *mut JSObject) { let _: Box<ProtoOrIfaceArray> = Box::from_raw(get_proto_or_iface_array(obj) as *mut ProtoOrIfaceArray); } /// Callback to outerize windows when wrapping. pub unsafe extern fn wrap_for_same_compartment(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObject { JS_ObjectToOuterObject(cx, obj) } /// Callback to outerize windows before wrapping. pub unsafe extern fn pre_wrap(cx: *mut JSContext, _scope: *mut JSObject, obj: *mut JSObject, _flags: c_uint) -> *mut JSObject { JS_ObjectToOuterObject(cx, obj) } /// Callback to outerize windows. pub extern fn outerize_global(_cx: *mut JSContext, obj: JSHandleObject) -> *mut JSObject { unsafe { debug!("outerizing"); let obj = *obj.unnamed_field1; let win: Root<window::Window> = native_from_reflector_jsmanaged(obj).unwrap().root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let win = win.r(); let context = win.browser_context(); context.as_ref().unwrap().window_proxy() } } /// Deletes the property `id` from `object`. pub unsafe fn delete_property_by_id(cx: *mut JSContext, object: *mut JSObject, id: jsid, bp: &mut bool) -> bool { let mut value = UndefinedValue();
pub fn new() -> GlobalStaticData { GlobalStaticData { windowproxy_handler: browsercontext::new_window_proxy_handler(), } }
random_line_split
utils.rs
::JSVal; use js::jsval::{PrivateValue, ObjectValue, NullValue}; use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue}; use js::rust::with_compartment; use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT}; use js::JSFUN_CONSTRUCTOR; use js; /// Proxy handler for a WindowProxy. pub struct WindowProxyHandler(pub *const libc::c_void); #[allow(raw_pointer_derive)] #[jstraceable] /// Static data associated with a global object. pub struct GlobalStaticData { /// The WindowProxy proxy handler for this global. pub windowproxy_handler: WindowProxyHandler, } impl GlobalStaticData { /// Creates a new GlobalStaticData. pub fn new() -> GlobalStaticData { GlobalStaticData { windowproxy_handler: browsercontext::new_window_proxy_handler(), } } } // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0; /// The index of the slot that contains a reference to the ProtoOrIfaceArray. // All DOM globals must have a slot at DOM_PROTOTYPE_SLOT. pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; /// The flag set on the `JSClass`es for DOM global objects. // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; /// Representation of an IDL constant value. #[derive(Clone)] pub enum ConstantVal { /// `long` constant. IntVal(i32), /// `unsigned long` constant. UintVal(u32), /// `double` constant. DoubleVal(f64), /// `boolean` constant. BoolVal(bool), /// `null` constant. NullVal, } /// Representation of an IDL constant. #[derive(Clone)] pub struct ConstantSpec { /// name of the constant. pub name: &'static [u8], /// value of the constant. pub value: ConstantVal } impl ConstantSpec { /// Returns a `JSVal` that represents the value of this `ConstantSpec`. pub fn get_value(&self) -> JSVal { match self.value { ConstantVal::NullVal => NullValue(), ConstantVal::IntVal(i) => Int32Value(i), ConstantVal::UintVal(u) => UInt32Value(u), ConstantVal::DoubleVal(d) => DoubleValue(d), ConstantVal::BoolVal(b) => BooleanValue(b), } } } /// Helper structure for cross-origin wrappers for DOM binding objects. pub struct NativePropertyHooks { /// The property arrays for this interface. pub native_properties: &'static NativeProperties, /// The NativePropertyHooks instance for the parent interface, if any. pub proto_hooks: Option<&'static NativePropertyHooks>, } /// The struct that holds inheritance information for DOM object reflectors. #[derive(Copy)] pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH], /// The NativePropertyHooks for the interface associated with this class. pub native_hooks: &'static NativePropertyHooks, } unsafe impl Sync for DOMClass {} /// The JSClass used for DOM object reflectors. #[derive(Copy)] pub struct DOMJSClass { /// The actual JSClass. pub base: js::Class, /// Associated data for DOM object reflectors. pub dom_class: DOMClass } unsafe impl Sync for DOMJSClass {} /// Returns the ProtoOrIfaceArray for the given global object. /// Fails if `global` is not a DOM global object. pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut *mut JSObject { unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut *mut JSObject } } /// Contains references to lists of methods, attributes, and constants for a /// given interface. pub struct NativeProperties { /// Instance methods for the interface. pub methods: Option<&'static [JSFunctionSpec]>, /// Instance attributes for the interface. pub attrs: Option<&'static [JSPropertySpec]>, /// Constants for the interface. pub consts: Option<&'static [ConstantSpec]>, /// Static methods for the interface. pub static_methods: Option<&'static [JSFunctionSpec]>, /// Static attributes for the interface. pub static_attrs: Option<&'static [JSPropertySpec]>, } unsafe impl Sync for NativeProperties {} /// A JSNative that cannot be null. pub type NonNullJSNative = unsafe extern "C" fn (arg1: *mut JSContext, arg2: c_uint, arg3: *mut JSVal) -> JSBool; /// Creates the *interface prototype object* and the *interface object* (if /// needed). /// Fails on JSAPI failure. pub fn do_create_interface_objects(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, proto_proto: *mut JSObject, proto_class: &'static JSClass, constructor: Option<(NonNullJSNative, &'static str, u32)>, dom_class: *const DOMClass, members: &'static NativeProperties) -> *mut JSObject { let proto = create_interface_prototype_object(cx, global, proto_proto, proto_class, members); unsafe { JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT, PrivateValue(dom_class as *const libc::c_void)); } match constructor { Some((native, name, nargs)) => { let s = CString::new(name).unwrap(); create_interface_object(cx, global, receiver, native, nargs, proto, members, s.as_ptr()) }, None => (), } proto } /// Creates the *interface object*. /// Fails on JSAPI failure. fn create_interface_object(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, constructor_native: NonNullJSNative, ctor_nargs: u32, proto: *mut JSObject, members: &'static NativeProperties, name: *const libc::c_char) { unsafe { let fun = JS_NewFunction(cx, Some(constructor_native), ctor_nargs, JSFUN_CONSTRUCTOR, global, name); assert!(!fun.is_null()); let constructor = JS_GetFunctionObject(fun); assert!(!constructor.is_null()); if let Some(static_methods) = members.static_methods { define_methods(cx, constructor, static_methods); } if let Some(static_properties) = members.static_attrs { define_properties(cx, constructor, static_properties); } if let Some(constants) = members.consts { define_constants(cx, constructor, constants); } if!proto.is_null() { assert!(JS_LinkConstructorAndPrototype(cx, constructor, proto)!= 0); } let mut already_defined = 0; assert!(JS_AlreadyHasOwnProperty(cx, receiver, name, &mut already_defined)!= 0); if already_defined == 0 { assert!(JS_DefineProperty(cx, receiver, name, ObjectValue(&*constructor), None, None, 0)!= 0); } } } /// Defines constants on `obj`. /// Fails on JSAPI failure. fn define_constants(cx: *mut JSContext, obj: *mut JSObject, constants: &'static [ConstantSpec]) { for spec in constants.iter() { unsafe { assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char, spec.get_value(), None, None, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)!= 0); } } } /// Defines methods on `obj`. The last entry of `methods` must contain zeroed /// memory. /// Fails on JSAPI failure. fn define_methods(cx: *mut JSContext, obj: *mut JSObject, methods: &'static [JSFunctionSpec]) { unsafe { assert!(JS_DefineFunctions(cx, obj, methods.as_ptr())!= 0); } } /// Defines attributes on `obj`. The last entry of `properties` must contain /// zeroed memory. /// Fails on JSAPI failure. fn define_properties(cx: *mut JSContext, obj: *mut JSObject, properties: &'static [JSPropertySpec]) { unsafe { assert!(JS_DefineProperties(cx, obj, properties.as_ptr())!= 0); } } /// Creates the *interface prototype object*. /// Fails on JSAPI failure. fn create_interface_prototype_object(cx: *mut JSContext, global: *mut JSObject, parent_proto: *mut JSObject, proto_class: &'static JSClass, members: &'static NativeProperties) -> *mut JSObject { unsafe { let our_proto = JS_NewObjectWithUniqueType(cx, proto_class, &*parent_proto, &*global); assert!(!our_proto.is_null()); if let Some(methods) = members.methods { define_methods(cx, our_proto, methods); } if let Some(properties) = members.attrs { define_properties(cx, our_proto, properties); } if let Some(constants) = members.consts { define_constants(cx, our_proto, constants); } return our_proto; } } /// A throwing constructor, for those interfaces that have neither /// `NoInterfaceObject` nor `Constructor`. pub unsafe extern fn throwing_constructor(cx: *mut JSContext, _argc: c_uint, _vp: *mut JSVal) -> JSBool { throw_type_error(cx, "Illegal constructor."); return 0; } type ProtoOrIfaceArray = [*mut JSObject; PrototypeList::ID::Count as usize]; /// Construct and cache the ProtoOrIfaceArray for the given global. /// Fails if the argument is not a DOM global. pub fn initialize_global(global: *mut JSObject) { let proto_array: Box<ProtoOrIfaceArray> = box () ([0 as *mut JSObject; PrototypeList::ID::Count as usize]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); let box_ = boxed::into_raw(proto_array); JS_SetReservedSlot(global, DOM_PROTOTYPE_SLOT, PrivateValue(box_ as *const libc::c_void)); } } /// A trait to provide access to the `Reflector` for a DOM object. pub trait Reflectable { /// Returns the receiver's reflector. fn reflector<'a>(&'a self) -> &'a Reflector; } /// Create the reflector for a new DOM object and yield ownership to the /// reflector. pub fn reflect_dom_object<T: Reflectable> (obj: Box<T>, global: GlobalRef, wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<T>) -> Temporary<T>) -> Temporary<T> { wrap_fn(global.get_cx(), global, obj) } /// A struct to store a reference to the reflector of a DOM object. // Allowing unused_attribute because the lint sometimes doesn't run in order #[allow(raw_pointer_derive, unrooted_must_root, unused_attributes)] #[derive(PartialEq)] #[must_root] #[servo_lang = "reflector"] // If you're renaming or moving this field, update the path in plugins::reflector as well pub struct Reflector { object: Cell<*mut JSObject>, } impl Reflector { /// Get the reflector. #[inline] pub fn get_jsobject(&self) -> *mut JSObject { self.object.get() } /// Initialize the reflector. (May be called only once.) pub fn set_jsobject(&self, object: *mut JSObject) { assert!(self.object.get().is_null()); assert!(!object.is_null()); self.object.set(object); } /// Return a pointer to the memory location at which the JS reflector /// object is stored. Used by Temporary values to root the reflector, as /// required by the JSAPI rooting APIs. pub unsafe fn rootable(&self) -> *mut *mut JSObject { self.object.as_unsafe_cell().get() } /// Create an uninitialized `Reflector`. pub fn new() -> Reflector { Reflector { object: Cell::new(ptr::null_mut()), } } } /// Gets the property `id` on `proxy`'s prototype. If it exists, `*found` is /// set to true and `*vp` to the value, otherwise `*found` is set to false. /// /// Returns false on JSAPI failure. pub fn get_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, found: *mut bool, vp: *mut JSVal) -> bool { unsafe { //let proto = GetObjectProto(proxy); let proto = JS_GetPrototype(proxy); if proto.is_null() { *found = false; return true; } let mut has_property = 0; if JS_HasPropertyById(cx, proto, id, &mut has_property) == 0 { return false; } *found = has_property!= 0; let no_output = vp.is_null(); if has_property == 0 || no_output { return true; } JS_ForwardGetPropertyTo(cx, proto, id, proxy, vp)!= 0 } } /// Get an array index from the given `jsid`. Returns `None` if the given /// `jsid` is not an integer. pub fn get_array_index_from_id(_cx: *mut JSContext, id: jsid) -> Option<u32> { unsafe { if RUST_JSID_IS_INT(id)!= 0 { return Some(RUST_JSID_TO_INT(id) as u32); } return None; } // if id is length atom, -1, otherwise /*return if JSID_IS_ATOM(id) { let atom = JSID_TO_ATOM(id); //let s = *GetAtomChars(id); if s > 'a' && s < 'z' { return -1; } let i = 0; let str = AtomToLinearString(JSID_TO_ATOM(id)); return if StringIsArray(str, &mut i)!= 0 { i } else { -1 } } else { IdToInt32(cx, id); }*/ } /// Find the index of a string given by `v` in `values`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no matching string. pub fn find_enum_string_index(cx: *mut JSContext, v: JSVal, values: &[&'static str]) -> Result<Option<usize>, ()> { unsafe { let jsstr = JS_ValueToString(cx, v); if jsstr.is_null() { return Err(()); } let mut length = 0; let chars = JS_GetStringCharsAndLength(cx, jsstr, &mut length); if chars.is_null() { return Err(()); } Ok(values.iter().position(|value| { value.len() == length as usize && range(0, length as usize).all(|j| { value.as_bytes()[j] as u16 == *chars.offset(j as isize) }) })) } } /// Returns wether `obj` is a platform object /// http://heycam.github.io/webidl/#dfn-platform-object pub fn is_platform_object(obj: *mut JSObject) -> bool { unsafe { // Fast-path the common case let mut clasp = JS_GetClass(obj); if is_dom_class(&*clasp) { return true; } // Now for simplicity check for security wrappers before anything else if IsWrapper(obj) == 1 { let unwrapped_obj = UnwrapObject(obj, /* stopAtOuter = */ 0, ptr::null_mut()); if unwrapped_obj.is_null() { return false; } clasp = js::jsapi::JS_GetClass(obj); } // TODO also check if JS_IsArrayBufferObject return is_dom_class(&*clasp); } } /// Get the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no property with the given name. pub fn get_dictionary_property(cx: *mut JSContext, object: *mut JSObject, property: &str) -> Result<Option<JSVal>, ()> { use std::ffi::CString; fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, found: &mut JSBool) -> bool { unsafe { JS_HasProperty(cx, object, property.as_ptr(), found)!= 0 } } fn get_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, value: &mut JSVal) -> bool { unsafe { JS_GetProperty(cx, object, property.as_ptr(), value)!= 0 } } let property = CString::new(property).unwrap(); if object.is_null() { return Ok(None); } let mut found: JSBool = 0; if!has_property(cx, object, &property, &mut found) { return Err(()); } if found == 0 { return Ok(None); } let mut value = NullValue(); if!get_property(cx, object, &property, &mut value) { return Err(()); } Ok(Some(value)) } /// Returns whether `proxy` has a property `id` on its prototype. pub fn has_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid) -> bool { // MOZ_ASSERT(js::IsProxy(proxy) && js::GetProxyHandler(proxy) == handler); let mut found = false; return!get_property_on_prototype(cx, proxy, id, &mut found, ptr::null_mut()) || found; } /// Create a DOM global object with the given class. pub fn create_dom_global(cx: *mut JSContext, class: *const JSClass) -> *mut JSObject { unsafe { let obj = JS_NewGlobalObject(cx, class, ptr::null_mut()); if obj.is_null() { return ptr::null_mut(); } with_compartment(cx, obj, || { JS_InitStandardClasses(cx, obj); }); initialize_global(obj); obj } } /// Drop the resources held by reserved slots of a global object pub unsafe fn finalize_global(obj: *mut JSObject) { let _: Box<ProtoOrIfaceArray> = Box::from_raw(get_proto_or_iface_array(obj) as *mut ProtoOrIfaceArray); } /// Callback to outerize windows when wrapping. pub unsafe extern fn wrap_for_same_compartment(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObject { JS_ObjectToOuterObject(cx, obj) } /// Callback to outerize windows before wrapping. pub unsafe extern fn pre_wrap(cx: *mut JSContext, _scope: *mut JSObject, obj: *mut JSObject, _flags: c_uint) -> *mut JSObject { JS_ObjectToOuterObject(cx, obj) } /// Callback to outerize windows. pub extern fn outerize_global(_cx: *mut JSContext, obj: JSHandleObject) -> *mut JSObject { unsafe { debug!("outerizing"); let obj = *obj.unnamed_field1; let win: Root<window::Window> = native_from_reflector_jsmanaged(obj).unwrap().root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let win = win.r(); let context = win.browser_context(); context.as_ref().unwrap().window_proxy() } } /// Deletes the property `id` from `object`. pub unsafe fn
(cx: *mut JSContext, object: *mut JSObject, id: jsid, bp: &mut bool) -> bool { let mut value = UndefinedValue();
delete_property_by_id
identifier_name
utils.rs
::JSVal; use js::jsval::{PrivateValue, ObjectValue, NullValue}; use js::jsval::{Int32Value, UInt32Value, DoubleValue, BooleanValue, UndefinedValue}; use js::rust::with_compartment; use js::{JSPROP_ENUMERATE, JSPROP_READONLY, JSPROP_PERMANENT}; use js::JSFUN_CONSTRUCTOR; use js; /// Proxy handler for a WindowProxy. pub struct WindowProxyHandler(pub *const libc::c_void); #[allow(raw_pointer_derive)] #[jstraceable] /// Static data associated with a global object. pub struct GlobalStaticData { /// The WindowProxy proxy handler for this global. pub windowproxy_handler: WindowProxyHandler, } impl GlobalStaticData { /// Creates a new GlobalStaticData. pub fn new() -> GlobalStaticData { GlobalStaticData { windowproxy_handler: browsercontext::new_window_proxy_handler(), } } } // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. const DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0; /// The index of the slot that contains a reference to the ProtoOrIfaceArray. // All DOM globals must have a slot at DOM_PROTOTYPE_SLOT. pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT; /// The flag set on the `JSClass`es for DOM global objects. // NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and // LSetDOMProperty. Those constants need to be changed accordingly if this value // changes. pub const JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1; /// Representation of an IDL constant value. #[derive(Clone)] pub enum ConstantVal { /// `long` constant. IntVal(i32), /// `unsigned long` constant. UintVal(u32), /// `double` constant. DoubleVal(f64), /// `boolean` constant. BoolVal(bool), /// `null` constant. NullVal, } /// Representation of an IDL constant. #[derive(Clone)] pub struct ConstantSpec { /// name of the constant. pub name: &'static [u8], /// value of the constant. pub value: ConstantVal } impl ConstantSpec { /// Returns a `JSVal` that represents the value of this `ConstantSpec`. pub fn get_value(&self) -> JSVal { match self.value { ConstantVal::NullVal => NullValue(), ConstantVal::IntVal(i) => Int32Value(i), ConstantVal::UintVal(u) => UInt32Value(u), ConstantVal::DoubleVal(d) => DoubleValue(d), ConstantVal::BoolVal(b) => BooleanValue(b), } } } /// Helper structure for cross-origin wrappers for DOM binding objects. pub struct NativePropertyHooks { /// The property arrays for this interface. pub native_properties: &'static NativeProperties, /// The NativePropertyHooks instance for the parent interface, if any. pub proto_hooks: Option<&'static NativePropertyHooks>, } /// The struct that holds inheritance information for DOM object reflectors. #[derive(Copy)] pub struct DOMClass { /// A list of interfaces that this object implements, in order of decreasing /// derivedness. pub interface_chain: [PrototypeList::ID; MAX_PROTO_CHAIN_LENGTH], /// The NativePropertyHooks for the interface associated with this class. pub native_hooks: &'static NativePropertyHooks, } unsafe impl Sync for DOMClass {} /// The JSClass used for DOM object reflectors. #[derive(Copy)] pub struct DOMJSClass { /// The actual JSClass. pub base: js::Class, /// Associated data for DOM object reflectors. pub dom_class: DOMClass } unsafe impl Sync for DOMJSClass {} /// Returns the ProtoOrIfaceArray for the given global object. /// Fails if `global` is not a DOM global object. pub fn get_proto_or_iface_array(global: *mut JSObject) -> *mut *mut JSObject { unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT).to_private() as *mut *mut JSObject } } /// Contains references to lists of methods, attributes, and constants for a /// given interface. pub struct NativeProperties { /// Instance methods for the interface. pub methods: Option<&'static [JSFunctionSpec]>, /// Instance attributes for the interface. pub attrs: Option<&'static [JSPropertySpec]>, /// Constants for the interface. pub consts: Option<&'static [ConstantSpec]>, /// Static methods for the interface. pub static_methods: Option<&'static [JSFunctionSpec]>, /// Static attributes for the interface. pub static_attrs: Option<&'static [JSPropertySpec]>, } unsafe impl Sync for NativeProperties {} /// A JSNative that cannot be null. pub type NonNullJSNative = unsafe extern "C" fn (arg1: *mut JSContext, arg2: c_uint, arg3: *mut JSVal) -> JSBool; /// Creates the *interface prototype object* and the *interface object* (if /// needed). /// Fails on JSAPI failure. pub fn do_create_interface_objects(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, proto_proto: *mut JSObject, proto_class: &'static JSClass, constructor: Option<(NonNullJSNative, &'static str, u32)>, dom_class: *const DOMClass, members: &'static NativeProperties) -> *mut JSObject { let proto = create_interface_prototype_object(cx, global, proto_proto, proto_class, members); unsafe { JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT, PrivateValue(dom_class as *const libc::c_void)); } match constructor { Some((native, name, nargs)) => { let s = CString::new(name).unwrap(); create_interface_object(cx, global, receiver, native, nargs, proto, members, s.as_ptr()) }, None => (), } proto } /// Creates the *interface object*. /// Fails on JSAPI failure. fn create_interface_object(cx: *mut JSContext, global: *mut JSObject, receiver: *mut JSObject, constructor_native: NonNullJSNative, ctor_nargs: u32, proto: *mut JSObject, members: &'static NativeProperties, name: *const libc::c_char) { unsafe { let fun = JS_NewFunction(cx, Some(constructor_native), ctor_nargs, JSFUN_CONSTRUCTOR, global, name); assert!(!fun.is_null()); let constructor = JS_GetFunctionObject(fun); assert!(!constructor.is_null()); if let Some(static_methods) = members.static_methods { define_methods(cx, constructor, static_methods); } if let Some(static_properties) = members.static_attrs { define_properties(cx, constructor, static_properties); } if let Some(constants) = members.consts { define_constants(cx, constructor, constants); } if!proto.is_null() { assert!(JS_LinkConstructorAndPrototype(cx, constructor, proto)!= 0); } let mut already_defined = 0; assert!(JS_AlreadyHasOwnProperty(cx, receiver, name, &mut already_defined)!= 0); if already_defined == 0 { assert!(JS_DefineProperty(cx, receiver, name, ObjectValue(&*constructor), None, None, 0)!= 0); } } } /// Defines constants on `obj`. /// Fails on JSAPI failure. fn define_constants(cx: *mut JSContext, obj: *mut JSObject, constants: &'static [ConstantSpec]) { for spec in constants.iter() { unsafe { assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char, spec.get_value(), None, None, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT)!= 0); } } } /// Defines methods on `obj`. The last entry of `methods` must contain zeroed /// memory. /// Fails on JSAPI failure. fn define_methods(cx: *mut JSContext, obj: *mut JSObject, methods: &'static [JSFunctionSpec]) { unsafe { assert!(JS_DefineFunctions(cx, obj, methods.as_ptr())!= 0); } } /// Defines attributes on `obj`. The last entry of `properties` must contain /// zeroed memory. /// Fails on JSAPI failure. fn define_properties(cx: *mut JSContext, obj: *mut JSObject, properties: &'static [JSPropertySpec]) { unsafe { assert!(JS_DefineProperties(cx, obj, properties.as_ptr())!= 0); } } /// Creates the *interface prototype object*. /// Fails on JSAPI failure. fn create_interface_prototype_object(cx: *mut JSContext, global: *mut JSObject, parent_proto: *mut JSObject, proto_class: &'static JSClass, members: &'static NativeProperties) -> *mut JSObject { unsafe { let our_proto = JS_NewObjectWithUniqueType(cx, proto_class, &*parent_proto, &*global); assert!(!our_proto.is_null()); if let Some(methods) = members.methods { define_methods(cx, our_proto, methods); } if let Some(properties) = members.attrs { define_properties(cx, our_proto, properties); } if let Some(constants) = members.consts { define_constants(cx, our_proto, constants); } return our_proto; } } /// A throwing constructor, for those interfaces that have neither /// `NoInterfaceObject` nor `Constructor`. pub unsafe extern fn throwing_constructor(cx: *mut JSContext, _argc: c_uint, _vp: *mut JSVal) -> JSBool { throw_type_error(cx, "Illegal constructor."); return 0; } type ProtoOrIfaceArray = [*mut JSObject; PrototypeList::ID::Count as usize]; /// Construct and cache the ProtoOrIfaceArray for the given global. /// Fails if the argument is not a DOM global. pub fn initialize_global(global: *mut JSObject) { let proto_array: Box<ProtoOrIfaceArray> = box () ([0 as *mut JSObject; PrototypeList::ID::Count as usize]); unsafe { assert!(((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL)!= 0); let box_ = boxed::into_raw(proto_array); JS_SetReservedSlot(global, DOM_PROTOTYPE_SLOT, PrivateValue(box_ as *const libc::c_void)); } } /// A trait to provide access to the `Reflector` for a DOM object. pub trait Reflectable { /// Returns the receiver's reflector. fn reflector<'a>(&'a self) -> &'a Reflector; } /// Create the reflector for a new DOM object and yield ownership to the /// reflector. pub fn reflect_dom_object<T: Reflectable> (obj: Box<T>, global: GlobalRef, wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<T>) -> Temporary<T>) -> Temporary<T> { wrap_fn(global.get_cx(), global, obj) } /// A struct to store a reference to the reflector of a DOM object. // Allowing unused_attribute because the lint sometimes doesn't run in order #[allow(raw_pointer_derive, unrooted_must_root, unused_attributes)] #[derive(PartialEq)] #[must_root] #[servo_lang = "reflector"] // If you're renaming or moving this field, update the path in plugins::reflector as well pub struct Reflector { object: Cell<*mut JSObject>, } impl Reflector { /// Get the reflector. #[inline] pub fn get_jsobject(&self) -> *mut JSObject { self.object.get() } /// Initialize the reflector. (May be called only once.) pub fn set_jsobject(&self, object: *mut JSObject) { assert!(self.object.get().is_null()); assert!(!object.is_null()); self.object.set(object); } /// Return a pointer to the memory location at which the JS reflector /// object is stored. Used by Temporary values to root the reflector, as /// required by the JSAPI rooting APIs. pub unsafe fn rootable(&self) -> *mut *mut JSObject { self.object.as_unsafe_cell().get() } /// Create an uninitialized `Reflector`. pub fn new() -> Reflector { Reflector { object: Cell::new(ptr::null_mut()), } } } /// Gets the property `id` on `proxy`'s prototype. If it exists, `*found` is /// set to true and `*vp` to the value, otherwise `*found` is set to false. /// /// Returns false on JSAPI failure. pub fn get_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, found: *mut bool, vp: *mut JSVal) -> bool { unsafe { //let proto = GetObjectProto(proxy); let proto = JS_GetPrototype(proxy); if proto.is_null() { *found = false; return true; } let mut has_property = 0; if JS_HasPropertyById(cx, proto, id, &mut has_property) == 0 { return false; } *found = has_property!= 0; let no_output = vp.is_null(); if has_property == 0 || no_output { return true; } JS_ForwardGetPropertyTo(cx, proto, id, proxy, vp)!= 0 } } /// Get an array index from the given `jsid`. Returns `None` if the given /// `jsid` is not an integer. pub fn get_array_index_from_id(_cx: *mut JSContext, id: jsid) -> Option<u32> { unsafe { if RUST_JSID_IS_INT(id)!= 0 { return Some(RUST_JSID_TO_INT(id) as u32); } return None; } // if id is length atom, -1, otherwise /*return if JSID_IS_ATOM(id) { let atom = JSID_TO_ATOM(id); //let s = *GetAtomChars(id); if s > 'a' && s < 'z' { return -1; } let i = 0; let str = AtomToLinearString(JSID_TO_ATOM(id)); return if StringIsArray(str, &mut i)!= 0 { i } else { -1 } } else { IdToInt32(cx, id); }*/ } /// Find the index of a string given by `v` in `values`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no matching string. pub fn find_enum_string_index(cx: *mut JSContext, v: JSVal, values: &[&'static str]) -> Result<Option<usize>, ()> { unsafe { let jsstr = JS_ValueToString(cx, v); if jsstr.is_null() { return Err(()); } let mut length = 0; let chars = JS_GetStringCharsAndLength(cx, jsstr, &mut length); if chars.is_null() { return Err(()); } Ok(values.iter().position(|value| { value.len() == length as usize && range(0, length as usize).all(|j| { value.as_bytes()[j] as u16 == *chars.offset(j as isize) }) })) } } /// Returns wether `obj` is a platform object /// http://heycam.github.io/webidl/#dfn-platform-object pub fn is_platform_object(obj: *mut JSObject) -> bool { unsafe { // Fast-path the common case let mut clasp = JS_GetClass(obj); if is_dom_class(&*clasp) { return true; } // Now for simplicity check for security wrappers before anything else if IsWrapper(obj) == 1 { let unwrapped_obj = UnwrapObject(obj, /* stopAtOuter = */ 0, ptr::null_mut()); if unwrapped_obj.is_null() { return false; } clasp = js::jsapi::JS_GetClass(obj); } // TODO also check if JS_IsArrayBufferObject return is_dom_class(&*clasp); } } /// Get the property with name `property` from `object`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and /// `Ok(None)` if there was no property with the given name. pub fn get_dictionary_property(cx: *mut JSContext, object: *mut JSObject, property: &str) -> Result<Option<JSVal>, ()> { use std::ffi::CString; fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, found: &mut JSBool) -> bool { unsafe { JS_HasProperty(cx, object, property.as_ptr(), found)!= 0 } } fn get_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, value: &mut JSVal) -> bool { unsafe { JS_GetProperty(cx, object, property.as_ptr(), value)!= 0 } } let property = CString::new(property).unwrap(); if object.is_null() { return Ok(None); } let mut found: JSBool = 0; if!has_property(cx, object, &property, &mut found) { return Err(()); } if found == 0 { return Ok(None); } let mut value = NullValue(); if!get_property(cx, object, &property, &mut value) { return Err(()); } Ok(Some(value)) } /// Returns whether `proxy` has a property `id` on its prototype. pub fn has_property_on_prototype(cx: *mut JSContext, proxy: *mut JSObject, id: jsid) -> bool { // MOZ_ASSERT(js::IsProxy(proxy) && js::GetProxyHandler(proxy) == handler); let mut found = false; return!get_property_on_prototype(cx, proxy, id, &mut found, ptr::null_mut()) || found; } /// Create a DOM global object with the given class. pub fn create_dom_global(cx: *mut JSContext, class: *const JSClass) -> *mut JSObject { unsafe { let obj = JS_NewGlobalObject(cx, class, ptr::null_mut()); if obj.is_null() { return ptr::null_mut(); } with_compartment(cx, obj, || { JS_InitStandardClasses(cx, obj); }); initialize_global(obj); obj } } /// Drop the resources held by reserved slots of a global object pub unsafe fn finalize_global(obj: *mut JSObject) { let _: Box<ProtoOrIfaceArray> = Box::from_raw(get_proto_or_iface_array(obj) as *mut ProtoOrIfaceArray); } /// Callback to outerize windows when wrapping. pub unsafe extern fn wrap_for_same_compartment(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObject { JS_ObjectToOuterObject(cx, obj) } /// Callback to outerize windows before wrapping. pub unsafe extern fn pre_wrap(cx: *mut JSContext, _scope: *mut JSObject, obj: *mut JSObject, _flags: c_uint) -> *mut JSObject
/// Callback to outerize windows. pub extern fn outerize_global(_cx: *mut JSContext, obj: JSHandleObject) -> *mut JSObject { unsafe { debug!("outerizing"); let obj = *obj.unnamed_field1; let win: Root<window::Window> = native_from_reflector_jsmanaged(obj).unwrap().root(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let win = win.r(); let context = win.browser_context(); context.as_ref().unwrap().window_proxy() } } /// Deletes the property `id` from `object`. pub unsafe fn delete_property_by_id(cx: *mut JSContext, object: *mut JSObject, id: jsid, bp: &mut bool) -> bool { let mut value = UndefinedValue();
{ JS_ObjectToOuterObject(cx, obj) }
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/. */ // Servo, the mighty web browser engine from the future. // // This is a very simple library that wires all of Servo's components // together as type `Browser`, along with a generic client // implementing the `WindowMethods` trait, to create a working web // browser. // // The `Browser` type is responsible for configuring a // `Constellation`, which does the heavy lifting of coordinating all // of Servo's internal subsystems, including the `ScriptTask` and the // `LayoutTask`, as well maintains the navigation context. // // The `Browser` is fed events from a generic type that implements the // `WindowMethods` trait. #[macro_use] extern crate util as _util; mod export { extern crate canvas; extern crate canvas_traits; extern crate compositing; extern crate devtools; extern crate devtools_traits; extern crate euclid; extern crate gfx; extern crate gleam; extern crate layers; extern crate layout; extern crate msg; extern crate net; extern crate net_traits; extern crate profile; extern crate profile_traits; extern crate script; extern crate script_traits; extern crate style; extern crate url; } extern crate libc; #[cfg(feature = "webdriver")] extern crate webdriver_server; #[cfg(feature = "webdriver")] fn webdriver(port: u16, constellation: msg::constellation_msg::ConstellationChan) { webdriver_server::start_server(port, constellation.clone()); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: msg::constellation_msg::ConstellationChan) { } use compositing::CompositorEventListener; use compositing::compositor_task::InitialCompositorState; use compositing::constellation::InitialConstellationState; use compositing::windowing::WindowEvent; use compositing::windowing::WindowMethods; use compositing::{CompositorProxy, CompositorTask, Constellation}; use gfx::font_cache_task::FontCacheTask; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use net::image_cache_task::new_image_cache_task; use net::resource_task::new_resource_task; use net::storage_task::StorageTaskFactory; use net_traits::storage_task::StorageTask; use profile::mem as profile_mem; use profile::time as profile_time; use profile_traits::mem; use profile_traits::time; use std::borrow::Borrow; use std::rc::Rc; use std::sync::mpsc::Sender; use util::opts; pub use _util as util; pub use export::canvas; pub use export::canvas_traits; pub use export::compositing; pub use export::devtools; pub use export::devtools_traits; pub use export::euclid; pub use export::gfx; pub use export::gleam::gl; pub use export::layers; pub use export::layout; pub use export::msg; pub use export::net; pub use export::net_traits; pub use export::profile; pub use export::profile_traits; pub use export::script; pub use export::script_traits; pub use export::style; pub use export::url; pub struct Browser { compositor: Box<CompositorEventListener +'static>, } /// The in-process interface to Servo. /// /// It does everything necessary to render the web, primarily /// orchestrating the interaction between JavaScript, CSS layout, /// rendering, and the client window. /// /// Clients create a `Browser` for a given reference-counted type /// implementing `WindowMethods`, which is the bridge to whatever /// application Servo is embedded in. Clients then create an event /// loop to pump messages between the embedding application and /// various browser components. impl Browser { pub fn new<Window>(window: Option<Rc<Window>>) -> Browser where Window: WindowMethods +'static { // Global configuration options, parsed from the command line. let opts = opts::get(); script::init(); // Get both endpoints of a special channel for communication between // the client window and the compositor. This channel is unique because // messages to client may need to pump a platform-specific event loop // to deliver the message. let (compositor_proxy, compositor_receiver) = WindowMethods::create_compositor_channel(&window); let supports_clipboard = match window { Some(ref win_rc) => { let win: &Window = win_rc.borrow(); win.supports_clipboard() } None => false }; let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period); let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period); let devtools_chan = opts.devtools_port.map(|port| { devtools::start_server(port) }); // Create the constellation, which maintains the engine // pipelines, including the script and layout threads, as well // as the navigation context. let constellation_chan = create_constellation(opts.clone(), compositor_proxy.clone_compositor_proxy(), time_profiler_chan.clone(), mem_profiler_chan.clone(), devtools_chan, supports_clipboard); if cfg!(feature = "webdriver") { if let Some(port) = opts.webdriver_port { webdriver(port, constellation_chan.clone()); } } // The compositor coordinates with the client window to create the final // rendered page and display it somewhere. let compositor = CompositorTask::create(window, InitialCompositorState { sender: compositor_proxy, receiver: compositor_receiver, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, }); Browser { compositor: compositor, } } pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool { self.compositor.handle_events(events) } pub fn repaint_synchronously(&mut self) { self.compositor.repaint_synchronously() } pub fn pinch_zoom_level(&self) -> f32 { self.compositor.pinch_zoom_level() } pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } } fn
(opts: opts::Opts, compositor_proxy: Box<CompositorProxy + Send>, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>, supports_clipboard: bool) -> ConstellationChan { let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone()); let image_cache_task = new_image_cache_task(resource_task.clone()); let font_cache_task = FontCacheTask::new(resource_task.clone()); let storage_task: StorageTask = StorageTaskFactory::new(); let initial_state = InitialConstellationState { compositor_proxy: compositor_proxy, devtools_chan: devtools_chan, image_cache_task: image_cache_task, font_cache_task: font_cache_task, resource_task: resource_task, storage_task: storage_task, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, supports_clipboard: supports_clipboard, }; let constellation_chan = Constellation::<layout::layout_task::LayoutTask, script::script_task::ScriptTask>::start(initial_state); // Send the URL command to the constellation. match opts.url { Some(url) => { let ConstellationChan(ref chan) = constellation_chan; chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap(); }, None => () }; constellation_chan }
create_constellation
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/. */ // Servo, the mighty web browser engine from the future. // // This is a very simple library that wires all of Servo's components // together as type `Browser`, along with a generic client // implementing the `WindowMethods` trait, to create a working web // browser. // // The `Browser` type is responsible for configuring a // `Constellation`, which does the heavy lifting of coordinating all // of Servo's internal subsystems, including the `ScriptTask` and the // `LayoutTask`, as well maintains the navigation context. // // The `Browser` is fed events from a generic type that implements the // `WindowMethods` trait. #[macro_use] extern crate util as _util; mod export { extern crate canvas; extern crate canvas_traits; extern crate compositing; extern crate devtools; extern crate devtools_traits; extern crate euclid; extern crate gfx; extern crate gleam; extern crate layers; extern crate layout; extern crate msg; extern crate net; extern crate net_traits; extern crate profile; extern crate profile_traits; extern crate script; extern crate script_traits; extern crate style; extern crate url; } extern crate libc; #[cfg(feature = "webdriver")] extern crate webdriver_server; #[cfg(feature = "webdriver")] fn webdriver(port: u16, constellation: msg::constellation_msg::ConstellationChan) { webdriver_server::start_server(port, constellation.clone()); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: msg::constellation_msg::ConstellationChan) { } use compositing::CompositorEventListener; use compositing::compositor_task::InitialCompositorState; use compositing::constellation::InitialConstellationState; use compositing::windowing::WindowEvent; use compositing::windowing::WindowMethods; use compositing::{CompositorProxy, CompositorTask, Constellation}; use gfx::font_cache_task::FontCacheTask; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use net::image_cache_task::new_image_cache_task; use net::resource_task::new_resource_task; use net::storage_task::StorageTaskFactory; use net_traits::storage_task::StorageTask; use profile::mem as profile_mem; use profile::time as profile_time; use profile_traits::mem; use profile_traits::time; use std::borrow::Borrow; use std::rc::Rc; use std::sync::mpsc::Sender; use util::opts; pub use _util as util; pub use export::canvas; pub use export::canvas_traits; pub use export::compositing; pub use export::devtools; pub use export::devtools_traits; pub use export::euclid; pub use export::gfx; pub use export::gleam::gl; pub use export::layers; pub use export::layout; pub use export::msg; pub use export::net; pub use export::net_traits; pub use export::profile; pub use export::profile_traits; pub use export::script; pub use export::script_traits; pub use export::style; pub use export::url; pub struct Browser { compositor: Box<CompositorEventListener +'static>, } /// The in-process interface to Servo. /// /// It does everything necessary to render the web, primarily /// orchestrating the interaction between JavaScript, CSS layout, /// rendering, and the client window. /// /// Clients create a `Browser` for a given reference-counted type /// implementing `WindowMethods`, which is the bridge to whatever /// application Servo is embedded in. Clients then create an event /// loop to pump messages between the embedding application and /// various browser components. impl Browser { pub fn new<Window>(window: Option<Rc<Window>>) -> Browser where Window: WindowMethods +'static { // Global configuration options, parsed from the command line. let opts = opts::get(); script::init(); // Get both endpoints of a special channel for communication between // the client window and the compositor. This channel is unique because // messages to client may need to pump a platform-specific event loop // to deliver the message. let (compositor_proxy, compositor_receiver) = WindowMethods::create_compositor_channel(&window); let supports_clipboard = match window { Some(ref win_rc) => { let win: &Window = win_rc.borrow(); win.supports_clipboard() } None => false }; let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period); let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period); let devtools_chan = opts.devtools_port.map(|port| { devtools::start_server(port) }); // Create the constellation, which maintains the engine // pipelines, including the script and layout threads, as well // as the navigation context. let constellation_chan = create_constellation(opts.clone(), compositor_proxy.clone_compositor_proxy(), time_profiler_chan.clone(), mem_profiler_chan.clone(), devtools_chan, supports_clipboard); if cfg!(feature = "webdriver") { if let Some(port) = opts.webdriver_port { webdriver(port, constellation_chan.clone()); } } // The compositor coordinates with the client window to create the final // rendered page and display it somewhere. let compositor = CompositorTask::create(window, InitialCompositorState { sender: compositor_proxy, receiver: compositor_receiver, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, }); Browser { compositor: compositor, } } pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool { self.compositor.handle_events(events) } pub fn repaint_synchronously(&mut self) { self.compositor.repaint_synchronously() } pub fn pinch_zoom_level(&self) -> f32
pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } } fn create_constellation(opts: opts::Opts, compositor_proxy: Box<CompositorProxy + Send>, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>, supports_clipboard: bool) -> ConstellationChan { let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone()); let image_cache_task = new_image_cache_task(resource_task.clone()); let font_cache_task = FontCacheTask::new(resource_task.clone()); let storage_task: StorageTask = StorageTaskFactory::new(); let initial_state = InitialConstellationState { compositor_proxy: compositor_proxy, devtools_chan: devtools_chan, image_cache_task: image_cache_task, font_cache_task: font_cache_task, resource_task: resource_task, storage_task: storage_task, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, supports_clipboard: supports_clipboard, }; let constellation_chan = Constellation::<layout::layout_task::LayoutTask, script::script_task::ScriptTask>::start(initial_state); // Send the URL command to the constellation. match opts.url { Some(url) => { let ConstellationChan(ref chan) = constellation_chan; chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap(); }, None => () }; constellation_chan }
{ self.compositor.pinch_zoom_level() }
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/. */ // Servo, the mighty web browser engine from the future. // // This is a very simple library that wires all of Servo's components // together as type `Browser`, along with a generic client // implementing the `WindowMethods` trait, to create a working web // browser. // // The `Browser` type is responsible for configuring a // `Constellation`, which does the heavy lifting of coordinating all // of Servo's internal subsystems, including the `ScriptTask` and the // `LayoutTask`, as well maintains the navigation context. // // The `Browser` is fed events from a generic type that implements the // `WindowMethods` trait. #[macro_use] extern crate util as _util; mod export { extern crate canvas; extern crate canvas_traits; extern crate compositing; extern crate devtools; extern crate devtools_traits; extern crate euclid; extern crate gfx; extern crate gleam; extern crate layers; extern crate layout; extern crate msg; extern crate net; extern crate net_traits; extern crate profile; extern crate profile_traits; extern crate script; extern crate script_traits; extern crate style; extern crate url; } extern crate libc; #[cfg(feature = "webdriver")] extern crate webdriver_server; #[cfg(feature = "webdriver")] fn webdriver(port: u16, constellation: msg::constellation_msg::ConstellationChan) { webdriver_server::start_server(port, constellation.clone()); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: msg::constellation_msg::ConstellationChan) { } use compositing::CompositorEventListener; use compositing::compositor_task::InitialCompositorState; use compositing::constellation::InitialConstellationState; use compositing::windowing::WindowEvent; use compositing::windowing::WindowMethods; use compositing::{CompositorProxy, CompositorTask, Constellation}; use gfx::font_cache_task::FontCacheTask; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use net::image_cache_task::new_image_cache_task; use net::resource_task::new_resource_task; use net::storage_task::StorageTaskFactory; use net_traits::storage_task::StorageTask; use profile::mem as profile_mem; use profile::time as profile_time; use profile_traits::mem; use profile_traits::time; use std::borrow::Borrow; use std::rc::Rc; use std::sync::mpsc::Sender; use util::opts; pub use _util as util; pub use export::canvas; pub use export::canvas_traits; pub use export::compositing; pub use export::devtools; pub use export::devtools_traits; pub use export::euclid; pub use export::gfx; pub use export::gleam::gl; pub use export::layers; pub use export::layout; pub use export::msg; pub use export::net; pub use export::net_traits; pub use export::profile; pub use export::profile_traits; pub use export::script; pub use export::script_traits; pub use export::style; pub use export::url; pub struct Browser { compositor: Box<CompositorEventListener +'static>, } /// The in-process interface to Servo. /// /// It does everything necessary to render the web, primarily /// orchestrating the interaction between JavaScript, CSS layout, /// rendering, and the client window. /// /// Clients create a `Browser` for a given reference-counted type /// implementing `WindowMethods`, which is the bridge to whatever /// application Servo is embedded in. Clients then create an event /// loop to pump messages between the embedding application and /// various browser components. impl Browser { pub fn new<Window>(window: Option<Rc<Window>>) -> Browser where Window: WindowMethods +'static { // Global configuration options, parsed from the command line. let opts = opts::get(); script::init(); // Get both endpoints of a special channel for communication between // the client window and the compositor. This channel is unique because // messages to client may need to pump a platform-specific event loop // to deliver the message. let (compositor_proxy, compositor_receiver) = WindowMethods::create_compositor_channel(&window); let supports_clipboard = match window { Some(ref win_rc) => { let win: &Window = win_rc.borrow(); win.supports_clipboard() } None => false }; let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period); let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period); let devtools_chan = opts.devtools_port.map(|port| { devtools::start_server(port) }); // Create the constellation, which maintains the engine // pipelines, including the script and layout threads, as well // as the navigation context. let constellation_chan = create_constellation(opts.clone(), compositor_proxy.clone_compositor_proxy(), time_profiler_chan.clone(), mem_profiler_chan.clone(), devtools_chan, supports_clipboard); if cfg!(feature = "webdriver") { if let Some(port) = opts.webdriver_port
} // The compositor coordinates with the client window to create the final // rendered page and display it somewhere. let compositor = CompositorTask::create(window, InitialCompositorState { sender: compositor_proxy, receiver: compositor_receiver, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, }); Browser { compositor: compositor, } } pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool { self.compositor.handle_events(events) } pub fn repaint_synchronously(&mut self) { self.compositor.repaint_synchronously() } pub fn pinch_zoom_level(&self) -> f32 { self.compositor.pinch_zoom_level() } pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } } fn create_constellation(opts: opts::Opts, compositor_proxy: Box<CompositorProxy + Send>, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>, supports_clipboard: bool) -> ConstellationChan { let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone()); let image_cache_task = new_image_cache_task(resource_task.clone()); let font_cache_task = FontCacheTask::new(resource_task.clone()); let storage_task: StorageTask = StorageTaskFactory::new(); let initial_state = InitialConstellationState { compositor_proxy: compositor_proxy, devtools_chan: devtools_chan, image_cache_task: image_cache_task, font_cache_task: font_cache_task, resource_task: resource_task, storage_task: storage_task, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, supports_clipboard: supports_clipboard, }; let constellation_chan = Constellation::<layout::layout_task::LayoutTask, script::script_task::ScriptTask>::start(initial_state); // Send the URL command to the constellation. match opts.url { Some(url) => { let ConstellationChan(ref chan) = constellation_chan; chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap(); }, None => () }; constellation_chan }
{ webdriver(port, constellation_chan.clone()); }
conditional_block
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/. */ // Servo, the mighty web browser engine from the future. // // This is a very simple library that wires all of Servo's components // together as type `Browser`, along with a generic client // implementing the `WindowMethods` trait, to create a working web // browser. // // The `Browser` type is responsible for configuring a // `Constellation`, which does the heavy lifting of coordinating all // of Servo's internal subsystems, including the `ScriptTask` and the // `LayoutTask`, as well maintains the navigation context. // // The `Browser` is fed events from a generic type that implements the // `WindowMethods` trait. #[macro_use] extern crate util as _util; mod export { extern crate canvas; extern crate canvas_traits; extern crate compositing; extern crate devtools; extern crate devtools_traits; extern crate euclid; extern crate gfx; extern crate gleam; extern crate layers; extern crate layout; extern crate msg; extern crate net; extern crate net_traits; extern crate profile; extern crate profile_traits; extern crate script; extern crate script_traits; extern crate style; extern crate url; } extern crate libc; #[cfg(feature = "webdriver")] extern crate webdriver_server; #[cfg(feature = "webdriver")] fn webdriver(port: u16, constellation: msg::constellation_msg::ConstellationChan) { webdriver_server::start_server(port, constellation.clone()); } #[cfg(not(feature = "webdriver"))] fn webdriver(_port: u16, _constellation: msg::constellation_msg::ConstellationChan) { } use compositing::CompositorEventListener; use compositing::compositor_task::InitialCompositorState; use compositing::constellation::InitialConstellationState; use compositing::windowing::WindowEvent; use compositing::windowing::WindowMethods; use compositing::{CompositorProxy, CompositorTask, Constellation}; use gfx::font_cache_task::FontCacheTask; use msg::constellation_msg::ConstellationChan; use msg::constellation_msg::Msg as ConstellationMsg; use net::image_cache_task::new_image_cache_task; use net::resource_task::new_resource_task; use net::storage_task::StorageTaskFactory; use net_traits::storage_task::StorageTask; use profile::mem as profile_mem; use profile::time as profile_time; use profile_traits::mem; use profile_traits::time; use std::borrow::Borrow;
pub use _util as util; pub use export::canvas; pub use export::canvas_traits; pub use export::compositing; pub use export::devtools; pub use export::devtools_traits; pub use export::euclid; pub use export::gfx; pub use export::gleam::gl; pub use export::layers; pub use export::layout; pub use export::msg; pub use export::net; pub use export::net_traits; pub use export::profile; pub use export::profile_traits; pub use export::script; pub use export::script_traits; pub use export::style; pub use export::url; pub struct Browser { compositor: Box<CompositorEventListener +'static>, } /// The in-process interface to Servo. /// /// It does everything necessary to render the web, primarily /// orchestrating the interaction between JavaScript, CSS layout, /// rendering, and the client window. /// /// Clients create a `Browser` for a given reference-counted type /// implementing `WindowMethods`, which is the bridge to whatever /// application Servo is embedded in. Clients then create an event /// loop to pump messages between the embedding application and /// various browser components. impl Browser { pub fn new<Window>(window: Option<Rc<Window>>) -> Browser where Window: WindowMethods +'static { // Global configuration options, parsed from the command line. let opts = opts::get(); script::init(); // Get both endpoints of a special channel for communication between // the client window and the compositor. This channel is unique because // messages to client may need to pump a platform-specific event loop // to deliver the message. let (compositor_proxy, compositor_receiver) = WindowMethods::create_compositor_channel(&window); let supports_clipboard = match window { Some(ref win_rc) => { let win: &Window = win_rc.borrow(); win.supports_clipboard() } None => false }; let time_profiler_chan = profile_time::Profiler::create(opts.time_profiler_period); let mem_profiler_chan = profile_mem::Profiler::create(opts.mem_profiler_period); let devtools_chan = opts.devtools_port.map(|port| { devtools::start_server(port) }); // Create the constellation, which maintains the engine // pipelines, including the script and layout threads, as well // as the navigation context. let constellation_chan = create_constellation(opts.clone(), compositor_proxy.clone_compositor_proxy(), time_profiler_chan.clone(), mem_profiler_chan.clone(), devtools_chan, supports_clipboard); if cfg!(feature = "webdriver") { if let Some(port) = opts.webdriver_port { webdriver(port, constellation_chan.clone()); } } // The compositor coordinates with the client window to create the final // rendered page and display it somewhere. let compositor = CompositorTask::create(window, InitialCompositorState { sender: compositor_proxy, receiver: compositor_receiver, constellation_chan: constellation_chan, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, }); Browser { compositor: compositor, } } pub fn handle_events(&mut self, events: Vec<WindowEvent>) -> bool { self.compositor.handle_events(events) } pub fn repaint_synchronously(&mut self) { self.compositor.repaint_synchronously() } pub fn pinch_zoom_level(&self) -> f32 { self.compositor.pinch_zoom_level() } pub fn request_title_for_main_frame(&self) { self.compositor.title_for_main_frame() } } fn create_constellation(opts: opts::Opts, compositor_proxy: Box<CompositorProxy + Send>, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<Sender<devtools_traits::DevtoolsControlMsg>>, supports_clipboard: bool) -> ConstellationChan { let resource_task = new_resource_task(opts.user_agent.clone(), devtools_chan.clone()); let image_cache_task = new_image_cache_task(resource_task.clone()); let font_cache_task = FontCacheTask::new(resource_task.clone()); let storage_task: StorageTask = StorageTaskFactory::new(); let initial_state = InitialConstellationState { compositor_proxy: compositor_proxy, devtools_chan: devtools_chan, image_cache_task: image_cache_task, font_cache_task: font_cache_task, resource_task: resource_task, storage_task: storage_task, time_profiler_chan: time_profiler_chan, mem_profiler_chan: mem_profiler_chan, supports_clipboard: supports_clipboard, }; let constellation_chan = Constellation::<layout::layout_task::LayoutTask, script::script_task::ScriptTask>::start(initial_state); // Send the URL command to the constellation. match opts.url { Some(url) => { let ConstellationChan(ref chan) = constellation_chan; chan.send(ConstellationMsg::InitLoadUrl(url)).unwrap(); }, None => () }; constellation_chan }
use std::rc::Rc; use std::sync::mpsc::Sender; use util::opts;
random_line_split
cpu.rs
extern crate rand; use self::rand::ThreadRng; use self::rand::Rng; pub struct Cpu { pub registers: Reg, rng: ThreadRng, } impl Cpu { pub fn init() -> Self { Cpu { registers: Reg::default(), rng: rand::thread_rng(), } } /// Generates a random byte pub fn random_byte(&mut self) -> u8 { self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX) } } #[derive(Default)] pub struct Reg { pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8, pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8, pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8, pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8, pub i: u16, pub pc: u16, pub sp: u8, } impl Reg { #[inline] pub fn get(&self, idx: u8) -> Option<u8> { match idx { 0x0 => {Some(self.v0)}, 0x1 => {Some(self.v1)}, 0x2 => {Some(self.v2)}, 0x3 => {Some(self.v3)}, 0x4 => {Some(self.v4)}, 0x5 => {Some(self.v5)}, 0x6 => {Some(self.v6)}, 0x7 => {Some(self.v7)}, 0x8 => {Some(self.v8)}, 0x9 => {Some(self.v9)}, 0xa => {Some(self.va)}, 0xb => {Some(self.vb)}, 0xc => {Some(self.vc)}, 0xd => {Some(self.vd)}, 0xe => {Some(self.ve)}, 0xf => {Some(self.vf)}, _ => {None}, } } #[inline] pub fn set(&mut self, idx: u8, value: u8) { match idx { 0x0 => {self.v0 = value}, 0x1 => {self.v1 = value}, 0x2 =>
, 0x3 => {self.v3 = value}, 0x4 => {self.v4 = value}, 0x5 => {self.v5 = value}, 0x6 => {self.v6 = value}, 0x7 => {self.v7 = value}, 0x8 => {self.v8 = value}, 0x9 => {self.v9 = value}, 0xa => {self.va = value}, 0xb => {self.vb = value}, 0xc => {self.vc = value}, 0xd => {self.vd = value}, 0xe => {self.ve = value}, 0xf => {self.vf = value}, _ => {}, } } }
{self.v2 = value}
conditional_block
cpu.rs
extern crate rand; use self::rand::ThreadRng; use self::rand::Rng; pub struct Cpu { pub registers: Reg, rng: ThreadRng, }
pub fn init() -> Self { Cpu { registers: Reg::default(), rng: rand::thread_rng(), } } /// Generates a random byte pub fn random_byte(&mut self) -> u8 { self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX) } } #[derive(Default)] pub struct Reg { pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8, pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8, pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8, pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8, pub i: u16, pub pc: u16, pub sp: u8, } impl Reg { #[inline] pub fn get(&self, idx: u8) -> Option<u8> { match idx { 0x0 => {Some(self.v0)}, 0x1 => {Some(self.v1)}, 0x2 => {Some(self.v2)}, 0x3 => {Some(self.v3)}, 0x4 => {Some(self.v4)}, 0x5 => {Some(self.v5)}, 0x6 => {Some(self.v6)}, 0x7 => {Some(self.v7)}, 0x8 => {Some(self.v8)}, 0x9 => {Some(self.v9)}, 0xa => {Some(self.va)}, 0xb => {Some(self.vb)}, 0xc => {Some(self.vc)}, 0xd => {Some(self.vd)}, 0xe => {Some(self.ve)}, 0xf => {Some(self.vf)}, _ => {None}, } } #[inline] pub fn set(&mut self, idx: u8, value: u8) { match idx { 0x0 => {self.v0 = value}, 0x1 => {self.v1 = value}, 0x2 => {self.v2 = value}, 0x3 => {self.v3 = value}, 0x4 => {self.v4 = value}, 0x5 => {self.v5 = value}, 0x6 => {self.v6 = value}, 0x7 => {self.v7 = value}, 0x8 => {self.v8 = value}, 0x9 => {self.v9 = value}, 0xa => {self.va = value}, 0xb => {self.vb = value}, 0xc => {self.vc = value}, 0xd => {self.vd = value}, 0xe => {self.ve = value}, 0xf => {self.vf = value}, _ => {}, } } }
impl Cpu {
random_line_split
cpu.rs
extern crate rand; use self::rand::ThreadRng; use self::rand::Rng; pub struct
{ pub registers: Reg, rng: ThreadRng, } impl Cpu { pub fn init() -> Self { Cpu { registers: Reg::default(), rng: rand::thread_rng(), } } /// Generates a random byte pub fn random_byte(&mut self) -> u8 { self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX) } } #[derive(Default)] pub struct Reg { pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8, pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8, pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8, pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8, pub i: u16, pub pc: u16, pub sp: u8, } impl Reg { #[inline] pub fn get(&self, idx: u8) -> Option<u8> { match idx { 0x0 => {Some(self.v0)}, 0x1 => {Some(self.v1)}, 0x2 => {Some(self.v2)}, 0x3 => {Some(self.v3)}, 0x4 => {Some(self.v4)}, 0x5 => {Some(self.v5)}, 0x6 => {Some(self.v6)}, 0x7 => {Some(self.v7)}, 0x8 => {Some(self.v8)}, 0x9 => {Some(self.v9)}, 0xa => {Some(self.va)}, 0xb => {Some(self.vb)}, 0xc => {Some(self.vc)}, 0xd => {Some(self.vd)}, 0xe => {Some(self.ve)}, 0xf => {Some(self.vf)}, _ => {None}, } } #[inline] pub fn set(&mut self, idx: u8, value: u8) { match idx { 0x0 => {self.v0 = value}, 0x1 => {self.v1 = value}, 0x2 => {self.v2 = value}, 0x3 => {self.v3 = value}, 0x4 => {self.v4 = value}, 0x5 => {self.v5 = value}, 0x6 => {self.v6 = value}, 0x7 => {self.v7 = value}, 0x8 => {self.v8 = value}, 0x9 => {self.v9 = value}, 0xa => {self.va = value}, 0xb => {self.vb = value}, 0xc => {self.vc = value}, 0xd => {self.vd = value}, 0xe => {self.ve = value}, 0xf => {self.vf = value}, _ => {}, } } }
Cpu
identifier_name
cpu.rs
extern crate rand; use self::rand::ThreadRng; use self::rand::Rng; pub struct Cpu { pub registers: Reg, rng: ThreadRng, } impl Cpu { pub fn init() -> Self { Cpu { registers: Reg::default(), rng: rand::thread_rng(), } } /// Generates a random byte pub fn random_byte(&mut self) -> u8
} #[derive(Default)] pub struct Reg { pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8, pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8, pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8, pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8, pub i: u16, pub pc: u16, pub sp: u8, } impl Reg { #[inline] pub fn get(&self, idx: u8) -> Option<u8> { match idx { 0x0 => {Some(self.v0)}, 0x1 => {Some(self.v1)}, 0x2 => {Some(self.v2)}, 0x3 => {Some(self.v3)}, 0x4 => {Some(self.v4)}, 0x5 => {Some(self.v5)}, 0x6 => {Some(self.v6)}, 0x7 => {Some(self.v7)}, 0x8 => {Some(self.v8)}, 0x9 => {Some(self.v9)}, 0xa => {Some(self.va)}, 0xb => {Some(self.vb)}, 0xc => {Some(self.vc)}, 0xd => {Some(self.vd)}, 0xe => {Some(self.ve)}, 0xf => {Some(self.vf)}, _ => {None}, } } #[inline] pub fn set(&mut self, idx: u8, value: u8) { match idx { 0x0 => {self.v0 = value}, 0x1 => {self.v1 = value}, 0x2 => {self.v2 = value}, 0x3 => {self.v3 = value}, 0x4 => {self.v4 = value}, 0x5 => {self.v5 = value}, 0x6 => {self.v6 = value}, 0x7 => {self.v7 = value}, 0x8 => {self.v8 = value}, 0x9 => {self.v9 = value}, 0xa => {self.va = value}, 0xb => {self.vb = value}, 0xc => {self.vc = value}, 0xd => {self.vd = value}, 0xe => {self.ve = value}, 0xf => {self.vf = value}, _ => {}, } } }
{ self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX) }
identifier_body
implicit_infer.rs
use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; use super::explicit::ExplicitPredicatesMap; use super::utils::*; /// Infer predicates for the items in the crate. /// /// `global_inferred_outlives`: this is initially the empty map that /// was generated by walking the items in the crate. This will /// now be filled with inferred predicates. pub fn infer_predicates<'tcx>( tcx: TyCtxt<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> { debug!("infer_predicates"); let mut predicates_added = true; let mut global_inferred_outlives = FxHashMap::default(); // If new predicates were added then we need to re-calculate // all crates since there could be new implied predicates. while predicates_added { predicates_added = false; let mut visitor = InferVisitor { tcx, global_inferred_outlives: &mut global_inferred_outlives, predicates_added: &mut predicates_added, explicit_map, }; // Visit all the crates and infer predicates tcx.hir().visit_all_item_likes(&mut visitor); } global_inferred_outlives } pub struct InferVisitor<'cx, 'tcx> { tcx: TyCtxt<'tcx>, global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>, predicates_added: &'cx mut bool, explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>, } impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { let item_did = item.def_id; debug!("InferVisitor::visit_item(item={:?})", item_did); let mut item_required_predicates = RequiredPredicates::default(); match item.kind { hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => { let adt_def = self.tcx.adt_def(item_did.to_def_id()); // Iterate over all fields in item_did for field_def in adt_def.all_fields() { // Calculating the predicate requirements necessary // for item_did. // // For field of type &'a T (reference) or Adt // (struct/enum/union) there will be outlive // requirements for adt_def. let field_ty = self.tcx.type_of(field_def.did); let field_span = self.tcx.def_span(field_def.did); insert_required_predicates_to_be_wf( self.tcx, field_ty, field_span, self.global_inferred_outlives, &mut item_required_predicates, &mut self.explicit_map, ); } } _ => {} }; // If new predicates were added (`local_predicate_map` has more // predicates than the `global_inferred_outlives`), the new predicates // might result in implied predicates for their parent types. // Therefore mark `predicates_added` as true and which will ensure // we walk the crates again and re-calculate predicates for all // items. let item_predicates_len: usize = self.global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.len()); if item_required_predicates.len() > item_predicates_len { *self.predicates_added = true; self.global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates); } } fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {} fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {} fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {} } fn insert_required_predicates_to_be_wf<'tcx>( tcx: TyCtxt<'tcx>, field_ty: Ty<'tcx>, field_span: Span, global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>, required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ) { // We must not look into the default substs of consts // as computing those depends on the results of `predicates_of`. // // Luckily the only types contained in default substs are type // parameters which don't matter here. // // FIXME(adt_const_params): Once complex const parameter types // are allowed, this might be incorrect. I think that we will still be // fine, as all outlives relations of the const param types should also // be part of the adt containing it, but we should still both update the // documentation and add some tests for this. for arg in field_ty.walk_ignoring_default_const_substs() { let ty = match arg.unpack() { GenericArgKind::Type(ty) => ty, // No predicates from lifetimes or constants, except potentially // constants' types, but `walk` will get to them as well. GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue, }; match *ty.kind() { // The field is of type &'a T which means that we will have // a predicate requirement of T: 'a (T outlives 'a). // // We also want to calculate potential predicates for the T ty::Ref(region, rty, _) => { debug!("Ref"); insert_outlives_predicate(tcx, rty.into(), region, field_span, required_predicates); } // For each Adt (struct/enum/union) type `Foo<'a, T>`, we // can load the current set of inferred and explicit // predicates from `global_inferred_outlives` and filter the // ones that are TypeOutlives. ty::Adt(def, substs) => { // First check the inferred predicates // // Example 1: // // struct Foo<'a, T> { // field1: Bar<'a, T> // } // // struct Bar<'b, U> { // field2: &'b U // } // // Here, when processing the type of `field1`, we would // request the set of implicit predicates computed for `Bar` // thus far. This will initially come back empty, but in next // round we will get `U: 'b`. We then apply the substitution // `['b => 'a, U => T]` and thus get the requirement that `T: // 'a` holds for `Foo`. debug!("Adt"); if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) { for (unsubstituted_predicate, &span) in unsubstituted_predicates { // `unsubstituted_predicate` is `U: 'b` in the // example above. So apply the substitution to // get `T: 'a` (or `predicate`): let predicate = unsubstituted_predicate.subst(tcx, substs); insert_outlives_predicate( tcx, predicate.0, predicate.1, span, required_predicates, ); } } // Check if the type has any explicit predicates that need // to be added to `required_predicates` // let _: () = substs.region_at(0); check_explicit_predicates( tcx, def.did, substs, required_predicates, explicit_map, None, ); } ty::Dynamic(obj,..) => { // This corresponds to `dyn Trait<..>`. In this case, we should // use the explicit predicates as well. debug!("Dynamic"); debug!("field_ty = {}", &field_ty); debug!("ty in field = {}", &ty); if let Some(ex_trait_ref) = obj.principal() { // Here, we are passing the type `usize` as a // placeholder value with the function // `with_self_ty`, since there is no concrete type // `Self` for a `dyn Trait` at this // stage. Therefore when checking explicit // predicates in `check_explicit_predicates` we // need to ignore checking the explicit_map for // Self type. let substs = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().substs; check_explicit_predicates( tcx, ex_trait_ref.skip_binder().def_id, substs, required_predicates, explicit_map, Some(tcx.types.self_param), ); } } ty::Projection(obj) => { // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the // explicit predicates as well. debug!("Projection"); check_explicit_predicates( tcx, tcx.associated_item(obj.item_def_id).container.id(), obj.substs, required_predicates, explicit_map, None, ); } _ => {} } } } /// We also have to check the explicit predicates /// declared on the type. /// /// struct Foo<'a, T> { /// field1: Bar<T> /// } /// /// struct Bar<U> where U:'static, U: Foo { /// ... /// } /// /// Here, we should fetch the explicit predicates, which /// will give us `U:'static` and `U: Foo`. The latter we /// can ignore, but we will want to process `U:'static`, /// applying the substitution as above. pub fn check_explicit_predicates<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, substs: &[GenericArg<'tcx>], required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ignored_self_ty: Option<Ty<'tcx>>, ) { debug!( "check_explicit_predicates(def_id={:?}, \ substs={:?}, \ explicit_map={:?}, \ required_predicates={:?}, \ ignored_self_ty={:?})", def_id, substs, explicit_map, required_predicates, ignored_self_ty, ); let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id); for (outlives_predicate, &span) in explicit_predicates { debug!("outlives_predicate = {:?}", &outlives_predicate); // Careful: If we are inferring the effects of a `dyn Trait<..>` // type, then when we look up the predicates for `Trait`, // we may find some that reference `Self`. e.g., perhaps the // definition of `Trait` was: // // ``` // trait Trait<'a, T> where Self: 'a {.. } // ``` // // we want to ignore such predicates here, because // there is no type parameter for them to affect. Consider // a struct containing `dyn Trait`: // // ``` // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> } // ``` // // The `where Self: 'a` predicate refers to the *existential, hidden type* // that is represented by the `dyn Trait`, not to the `X` type parameter // (or any other generic parameter) declared on `MyStruct`. // // Note that we do this check for self **before** applying `substs`. In the // case that `substs` come from a `dyn Trait` type, our caller will have // included `Self = usize` as the value for `Self`. If we were // to apply the substs, and not filter this predicate, we might then falsely // conclude that e.g., `X: 'x` was a reasonable inferred requirement. // // Another similar case is where we have an inferred // requirement like `<Self as Trait>::Foo: 'b`. We presently // ignore such requirements as well (cc #54467)-- though // conceivably it might be better if we could extract the `Foo // = X` binding from the object type (there must be such a // binding) and thus infer an outlives requirement that `X: // 'b`. if let Some(self_ty) = ignored_self_ty { if let GenericArgKind::Type(ty) = outlives_predicate.0.unpack() { if ty.walk(tcx).any(|arg| arg == self_ty.into()) {
} let predicate = outlives_predicate.subst(tcx, substs); debug!("predicate = {:?}", &predicate); insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates); } }
debug!("skipping self ty = {:?}", &ty); continue; } }
random_line_split
implicit_infer.rs
use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; use super::explicit::ExplicitPredicatesMap; use super::utils::*; /// Infer predicates for the items in the crate. /// /// `global_inferred_outlives`: this is initially the empty map that /// was generated by walking the items in the crate. This will /// now be filled with inferred predicates. pub fn infer_predicates<'tcx>( tcx: TyCtxt<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> { debug!("infer_predicates"); let mut predicates_added = true; let mut global_inferred_outlives = FxHashMap::default(); // If new predicates were added then we need to re-calculate // all crates since there could be new implied predicates. while predicates_added { predicates_added = false; let mut visitor = InferVisitor { tcx, global_inferred_outlives: &mut global_inferred_outlives, predicates_added: &mut predicates_added, explicit_map, }; // Visit all the crates and infer predicates tcx.hir().visit_all_item_likes(&mut visitor); } global_inferred_outlives } pub struct InferVisitor<'cx, 'tcx> { tcx: TyCtxt<'tcx>, global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>, predicates_added: &'cx mut bool, explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>, } impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { let item_did = item.def_id; debug!("InferVisitor::visit_item(item={:?})", item_did); let mut item_required_predicates = RequiredPredicates::default(); match item.kind { hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => { let adt_def = self.tcx.adt_def(item_did.to_def_id()); // Iterate over all fields in item_did for field_def in adt_def.all_fields() { // Calculating the predicate requirements necessary // for item_did. // // For field of type &'a T (reference) or Adt // (struct/enum/union) there will be outlive // requirements for adt_def. let field_ty = self.tcx.type_of(field_def.did); let field_span = self.tcx.def_span(field_def.did); insert_required_predicates_to_be_wf( self.tcx, field_ty, field_span, self.global_inferred_outlives, &mut item_required_predicates, &mut self.explicit_map, ); } } _ => {} }; // If new predicates were added (`local_predicate_map` has more // predicates than the `global_inferred_outlives`), the new predicates // might result in implied predicates for their parent types. // Therefore mark `predicates_added` as true and which will ensure // we walk the crates again and re-calculate predicates for all // items. let item_predicates_len: usize = self.global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.len()); if item_required_predicates.len() > item_predicates_len { *self.predicates_added = true; self.global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates); } } fn visit_trait_item(&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {} fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {} fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {} } fn insert_required_predicates_to_be_wf<'tcx>( tcx: TyCtxt<'tcx>, field_ty: Ty<'tcx>, field_span: Span, global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>, required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, )
match *ty.kind() { // The field is of type &'a T which means that we will have // a predicate requirement of T: 'a (T outlives 'a). // // We also want to calculate potential predicates for the T ty::Ref(region, rty, _) => { debug!("Ref"); insert_outlives_predicate(tcx, rty.into(), region, field_span, required_predicates); } // For each Adt (struct/enum/union) type `Foo<'a, T>`, we // can load the current set of inferred and explicit // predicates from `global_inferred_outlives` and filter the // ones that are TypeOutlives. ty::Adt(def, substs) => { // First check the inferred predicates // // Example 1: // // struct Foo<'a, T> { // field1: Bar<'a, T> // } // // struct Bar<'b, U> { // field2: &'b U // } // // Here, when processing the type of `field1`, we would // request the set of implicit predicates computed for `Bar` // thus far. This will initially come back empty, but in next // round we will get `U: 'b`. We then apply the substitution // `['b => 'a, U => T]` and thus get the requirement that `T: // 'a` holds for `Foo`. debug!("Adt"); if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) { for (unsubstituted_predicate, &span) in unsubstituted_predicates { // `unsubstituted_predicate` is `U: 'b` in the // example above. So apply the substitution to // get `T: 'a` (or `predicate`): let predicate = unsubstituted_predicate.subst(tcx, substs); insert_outlives_predicate( tcx, predicate.0, predicate.1, span, required_predicates, ); } } // Check if the type has any explicit predicates that need // to be added to `required_predicates` // let _: () = substs.region_at(0); check_explicit_predicates( tcx, def.did, substs, required_predicates, explicit_map, None, ); } ty::Dynamic(obj,..) => { // This corresponds to `dyn Trait<..>`. In this case, we should // use the explicit predicates as well. debug!("Dynamic"); debug!("field_ty = {}", &field_ty); debug!("ty in field = {}", &ty); if let Some(ex_trait_ref) = obj.principal() { // Here, we are passing the type `usize` as a // placeholder value with the function // `with_self_ty`, since there is no concrete type // `Self` for a `dyn Trait` at this // stage. Therefore when checking explicit // predicates in `check_explicit_predicates` we // need to ignore checking the explicit_map for // Self type. let substs = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().substs; check_explicit_predicates( tcx, ex_trait_ref.skip_binder().def_id, substs, required_predicates, explicit_map, Some(tcx.types.self_param), ); } } ty::Projection(obj) => { // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the // explicit predicates as well. debug!("Projection"); check_explicit_predicates( tcx, tcx.associated_item(obj.item_def_id).container.id(), obj.substs, required_predicates, explicit_map, None, ); } _ => {} } } } /// We also have to check the explicit predicates /// declared on the type. /// /// struct Foo<'a, T> { /// field1: Bar<T> /// } /// /// struct Bar<U> where U:'static, U: Foo { /// ... /// } /// /// Here, we should fetch the explicit predicates, which /// will give us `U:'static` and `U: Foo`. The latter we /// can ignore, but we will want to process `U:'static`, /// applying the substitution as above. pub fn check_explicit_predicates<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, substs: &[GenericArg<'tcx>], required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ignored_self_ty: Option<Ty<'tcx>>, ) { debug!( "check_explicit_predicates(def_id={:?}, \ substs={:?}, \ explicit_map={:?}, \ required_predicates={:?}, \ ignored_self_ty={:?})", def_id, substs, explicit_map, required_predicates, ignored_self_ty, ); let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id); for (outlives_predicate, &span) in explicit_predicates { debug!("outlives_predicate = {:?}", &outlives_predicate); // Careful: If we are inferring the effects of a `dyn Trait<..>` // type, then when we look up the predicates for `Trait`, // we may find some that reference `Self`. e.g., perhaps the // definition of `Trait` was: // // ``` // trait Trait<'a, T> where Self: 'a {.. } // ``` // // we want to ignore such predicates here, because // there is no type parameter for them to affect. Consider // a struct containing `dyn Trait`: // // ``` // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> } // ``` // // The `where Self: 'a` predicate refers to the *existential, hidden type* // that is represented by the `dyn Trait`, not to the `X` type parameter // (or any other generic parameter) declared on `MyStruct`. // // Note that we do this check for self **before** applying `substs`. In the // case that `substs` come from a `dyn Trait` type, our caller will have // included `Self = usize` as the value for `Self`. If we were // to apply the substs, and not filter this predicate, we might then falsely // conclude that e.g., `X: 'x` was a reasonable inferred requirement. // // Another similar case is where we have an inferred // requirement like `<Self as Trait>::Foo: 'b`. We presently // ignore such requirements as well (cc #54467)-- though // conceivably it might be better if we could extract the `Foo // = X` binding from the object type (there must be such a // binding) and thus infer an outlives requirement that `X: // 'b`. if let Some(self_ty) = ignored_self_ty { if let GenericArgKind::Type(ty) = outlives_predicate.0.unpack() { if ty.walk(tcx).any(|arg| arg == self_ty.into()) { debug!("skipping self ty = {:?}", &ty); continue; } } } let predicate = outlives_predicate.subst(tcx, substs); debug!("predicate = {:?}", &predicate); insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates); } }
{ // We must not look into the default substs of consts // as computing those depends on the results of `predicates_of`. // // Luckily the only types contained in default substs are type // parameters which don't matter here. // // FIXME(adt_const_params): Once complex const parameter types // are allowed, this might be incorrect. I think that we will still be // fine, as all outlives relations of the const param types should also // be part of the adt containing it, but we should still both update the // documentation and add some tests for this. for arg in field_ty.walk_ignoring_default_const_substs() { let ty = match arg.unpack() { GenericArgKind::Type(ty) => ty, // No predicates from lifetimes or constants, except potentially // constants' types, but `walk` will get to them as well. GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue, };
identifier_body
implicit_infer.rs
use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; use super::explicit::ExplicitPredicatesMap; use super::utils::*; /// Infer predicates for the items in the crate. /// /// `global_inferred_outlives`: this is initially the empty map that /// was generated by walking the items in the crate. This will /// now be filled with inferred predicates. pub fn infer_predicates<'tcx>( tcx: TyCtxt<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ) -> FxHashMap<DefId, RequiredPredicates<'tcx>> { debug!("infer_predicates"); let mut predicates_added = true; let mut global_inferred_outlives = FxHashMap::default(); // If new predicates were added then we need to re-calculate // all crates since there could be new implied predicates. while predicates_added { predicates_added = false; let mut visitor = InferVisitor { tcx, global_inferred_outlives: &mut global_inferred_outlives, predicates_added: &mut predicates_added, explicit_map, }; // Visit all the crates and infer predicates tcx.hir().visit_all_item_likes(&mut visitor); } global_inferred_outlives } pub struct InferVisitor<'cx, 'tcx> { tcx: TyCtxt<'tcx>, global_inferred_outlives: &'cx mut FxHashMap<DefId, RequiredPredicates<'tcx>>, predicates_added: &'cx mut bool, explicit_map: &'cx mut ExplicitPredicatesMap<'tcx>, } impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> { fn visit_item(&mut self, item: &hir::Item<'_>) { let item_did = item.def_id; debug!("InferVisitor::visit_item(item={:?})", item_did); let mut item_required_predicates = RequiredPredicates::default(); match item.kind { hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => { let adt_def = self.tcx.adt_def(item_did.to_def_id()); // Iterate over all fields in item_did for field_def in adt_def.all_fields() { // Calculating the predicate requirements necessary // for item_did. // // For field of type &'a T (reference) or Adt // (struct/enum/union) there will be outlive // requirements for adt_def. let field_ty = self.tcx.type_of(field_def.did); let field_span = self.tcx.def_span(field_def.did); insert_required_predicates_to_be_wf( self.tcx, field_ty, field_span, self.global_inferred_outlives, &mut item_required_predicates, &mut self.explicit_map, ); } } _ => {} }; // If new predicates were added (`local_predicate_map` has more // predicates than the `global_inferred_outlives`), the new predicates // might result in implied predicates for their parent types. // Therefore mark `predicates_added` as true and which will ensure // we walk the crates again and re-calculate predicates for all // items. let item_predicates_len: usize = self.global_inferred_outlives.get(&item_did.to_def_id()).map_or(0, |p| p.len()); if item_required_predicates.len() > item_predicates_len { *self.predicates_added = true; self.global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates); } } fn
(&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {} fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {} fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {} } fn insert_required_predicates_to_be_wf<'tcx>( tcx: TyCtxt<'tcx>, field_ty: Ty<'tcx>, field_span: Span, global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>, required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ) { // We must not look into the default substs of consts // as computing those depends on the results of `predicates_of`. // // Luckily the only types contained in default substs are type // parameters which don't matter here. // // FIXME(adt_const_params): Once complex const parameter types // are allowed, this might be incorrect. I think that we will still be // fine, as all outlives relations of the const param types should also // be part of the adt containing it, but we should still both update the // documentation and add some tests for this. for arg in field_ty.walk_ignoring_default_const_substs() { let ty = match arg.unpack() { GenericArgKind::Type(ty) => ty, // No predicates from lifetimes or constants, except potentially // constants' types, but `walk` will get to them as well. GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue, }; match *ty.kind() { // The field is of type &'a T which means that we will have // a predicate requirement of T: 'a (T outlives 'a). // // We also want to calculate potential predicates for the T ty::Ref(region, rty, _) => { debug!("Ref"); insert_outlives_predicate(tcx, rty.into(), region, field_span, required_predicates); } // For each Adt (struct/enum/union) type `Foo<'a, T>`, we // can load the current set of inferred and explicit // predicates from `global_inferred_outlives` and filter the // ones that are TypeOutlives. ty::Adt(def, substs) => { // First check the inferred predicates // // Example 1: // // struct Foo<'a, T> { // field1: Bar<'a, T> // } // // struct Bar<'b, U> { // field2: &'b U // } // // Here, when processing the type of `field1`, we would // request the set of implicit predicates computed for `Bar` // thus far. This will initially come back empty, but in next // round we will get `U: 'b`. We then apply the substitution // `['b => 'a, U => T]` and thus get the requirement that `T: // 'a` holds for `Foo`. debug!("Adt"); if let Some(unsubstituted_predicates) = global_inferred_outlives.get(&def.did) { for (unsubstituted_predicate, &span) in unsubstituted_predicates { // `unsubstituted_predicate` is `U: 'b` in the // example above. So apply the substitution to // get `T: 'a` (or `predicate`): let predicate = unsubstituted_predicate.subst(tcx, substs); insert_outlives_predicate( tcx, predicate.0, predicate.1, span, required_predicates, ); } } // Check if the type has any explicit predicates that need // to be added to `required_predicates` // let _: () = substs.region_at(0); check_explicit_predicates( tcx, def.did, substs, required_predicates, explicit_map, None, ); } ty::Dynamic(obj,..) => { // This corresponds to `dyn Trait<..>`. In this case, we should // use the explicit predicates as well. debug!("Dynamic"); debug!("field_ty = {}", &field_ty); debug!("ty in field = {}", &ty); if let Some(ex_trait_ref) = obj.principal() { // Here, we are passing the type `usize` as a // placeholder value with the function // `with_self_ty`, since there is no concrete type // `Self` for a `dyn Trait` at this // stage. Therefore when checking explicit // predicates in `check_explicit_predicates` we // need to ignore checking the explicit_map for // Self type. let substs = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().substs; check_explicit_predicates( tcx, ex_trait_ref.skip_binder().def_id, substs, required_predicates, explicit_map, Some(tcx.types.self_param), ); } } ty::Projection(obj) => { // This corresponds to `<T as Foo<'a>>::Bar`. In this case, we should use the // explicit predicates as well. debug!("Projection"); check_explicit_predicates( tcx, tcx.associated_item(obj.item_def_id).container.id(), obj.substs, required_predicates, explicit_map, None, ); } _ => {} } } } /// We also have to check the explicit predicates /// declared on the type. /// /// struct Foo<'a, T> { /// field1: Bar<T> /// } /// /// struct Bar<U> where U:'static, U: Foo { /// ... /// } /// /// Here, we should fetch the explicit predicates, which /// will give us `U:'static` and `U: Foo`. The latter we /// can ignore, but we will want to process `U:'static`, /// applying the substitution as above. pub fn check_explicit_predicates<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, substs: &[GenericArg<'tcx>], required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ignored_self_ty: Option<Ty<'tcx>>, ) { debug!( "check_explicit_predicates(def_id={:?}, \ substs={:?}, \ explicit_map={:?}, \ required_predicates={:?}, \ ignored_self_ty={:?})", def_id, substs, explicit_map, required_predicates, ignored_self_ty, ); let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id); for (outlives_predicate, &span) in explicit_predicates { debug!("outlives_predicate = {:?}", &outlives_predicate); // Careful: If we are inferring the effects of a `dyn Trait<..>` // type, then when we look up the predicates for `Trait`, // we may find some that reference `Self`. e.g., perhaps the // definition of `Trait` was: // // ``` // trait Trait<'a, T> where Self: 'a {.. } // ``` // // we want to ignore such predicates here, because // there is no type parameter for them to affect. Consider // a struct containing `dyn Trait`: // // ``` // struct MyStruct<'x, X> { field: Box<dyn Trait<'x, X>> } // ``` // // The `where Self: 'a` predicate refers to the *existential, hidden type* // that is represented by the `dyn Trait`, not to the `X` type parameter // (or any other generic parameter) declared on `MyStruct`. // // Note that we do this check for self **before** applying `substs`. In the // case that `substs` come from a `dyn Trait` type, our caller will have // included `Self = usize` as the value for `Self`. If we were // to apply the substs, and not filter this predicate, we might then falsely // conclude that e.g., `X: 'x` was a reasonable inferred requirement. // // Another similar case is where we have an inferred // requirement like `<Self as Trait>::Foo: 'b`. We presently // ignore such requirements as well (cc #54467)-- though // conceivably it might be better if we could extract the `Foo // = X` binding from the object type (there must be such a // binding) and thus infer an outlives requirement that `X: // 'b`. if let Some(self_ty) = ignored_self_ty { if let GenericArgKind::Type(ty) = outlives_predicate.0.unpack() { if ty.walk(tcx).any(|arg| arg == self_ty.into()) { debug!("skipping self ty = {:?}", &ty); continue; } } } let predicate = outlives_predicate.subst(tcx, substs); debug!("predicate = {:?}", &predicate); insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates); } }
visit_trait_item
identifier_name
compiletest.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. #[crate_type = "bin"]; #[allow(non_camel_case_types)]; #[deny(warnings)]; extern mod extra; use std::os; use std::io; use std::io::fs; use extra::getopts; use extra::getopts::groups::{optopt, optflag, reqopt}; use extra::test; use common::config; use common::mode_run_pass; use common::mode_run_fail; use common::mode_compile_fail; use common::mode_pretty; use common::mode_debug_info; use common::mode_codegen; use common::mode; use util::logv; pub mod procsrv; pub mod util; pub mod header; pub mod runtest; pub mod common; pub mod errors; pub fn main() { let args = os::args(); let config = parse_config(args); log_config(&config); run_tests(&config); } pub fn parse_config(args: ~[~str]) -> config { let groups : ~[getopts::groups::OptGroup] = ~[reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"), reqopt("", "run-lib-path", "path to target shared libraries", "PATH"), reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"), optopt("", "clang-path", "path to executable for codegen tests", "PATH"), optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"), reqopt("", "src-base", "directory to scan for test files", "PATH"), reqopt("", "build-base", "directory to deposit test outputs", "PATH"), reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"), reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"), reqopt("", "mode", "which sort of compile tests to run", "(compile-fail|run-fail|run-pass|pretty|debug-info)"), optflag("", "ignored", "run tests marked as ignored / xfailed"), optopt("", "runtool", "supervisor program to run tests under \ (eg. emulator, valgrind)", "PROGRAM"), optopt("", "rustcflags", "flags to pass to rustc", "FLAGS"), optflag("", "verbose", "run tests verbosely, showing all output"), optopt("", "logfile", "file to log test execution to", "FILE"), optopt("", "save-metrics", "file to save metrics to", "FILE"), optopt("", "ratchet-metrics", "file to ratchet metrics against", "FILE"), optopt("", "ratchet-noise-percent", "percent change in metrics to consider noise", "N"), optflag("", "jit", "run tests under the JIT"), optopt("", "target", "the target to build for", "TARGET"), optopt("", "host", "the host to build for", "HOST"), optopt("", "adb-path", "path to the android debugger", "PATH"), optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"), optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", "A.B"), optflag("h", "help", "show this message"), ]; assert!(!args.is_empty()); let argv0 = args[0].clone(); let args_ = args.tail(); if args[1] == ~"-h" || args[1] == ~"--help" { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } let matches = &match getopts::groups::getopts(args_, groups) { Ok(m) => m, Err(f) => fail!("{}", f.to_err_msg()) }; if matches.opt_present("h") || matches.opt_present("help") { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } fn opt_path(m: &getopts::Matches, nm: &str) -> Path { Path::new(m.opt_str(nm).unwrap()) } config { compile_lib_path: matches.opt_str("compile-lib-path").unwrap(), run_lib_path: matches.opt_str("run-lib-path").unwrap(), rustc_path: opt_path(matches, "rustc-path"), clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)), llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)), src_base: opt_path(matches, "src-base"), build_base: opt_path(matches, "build-base"), aux_base: opt_path(matches, "aux-base"), stage_id: matches.opt_str("stage-id").unwrap(), mode: str_mode(matches.opt_str("mode").unwrap()), run_ignored: matches.opt_present("ignored"), filter: if!matches.free.is_empty() { Some(matches.free[0].clone()) } else { None }, logfile: matches.opt_str("logfile").map(|s| Path::new(s)), save_metrics: matches.opt_str("save-metrics").map(|s| Path::new(s)), ratchet_metrics: matches.opt_str("ratchet-metrics").map(|s| Path::new(s)), ratchet_noise_percent: matches.opt_str("ratchet-noise-percent").and_then(|s| from_str::<f64>(s)), runtool: matches.opt_str("runtool"), rustcflags: matches.opt_str("rustcflags"), jit: matches.opt_present("jit"), target: opt_str2(matches.opt_str("target")).to_str(), host: opt_str2(matches.opt_str("host")).to_str(), adb_path: opt_str2(matches.opt_str("adb-path")).to_str(), adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")).to_str(), adb_device_status: "arm-linux-androideabi" == opt_str2(matches.opt_str("target")) && "(none)"!= opt_str2(matches.opt_str("adb-test-dir")) && !opt_str2(matches.opt_str("adb-test-dir")).is_empty(), test_shard: test::opt_shard(matches.opt_str("test-shard")), verbose: matches.opt_present("verbose") } } pub fn log_config(config: &config) { let c = config; logv(c, format!("configuration:")); logv(c, format!("compile_lib_path: {}", config.compile_lib_path)); logv(c, format!("run_lib_path: {}", config.run_lib_path)); logv(c, format!("rustc_path: {}", config.rustc_path.display())); logv(c, format!("src_base: {}", config.src_base.display())); logv(c, format!("build_base: {}", config.build_base.display())); logv(c, format!("stage_id: {}", config.stage_id)); logv(c, format!("mode: {}", mode_str(config.mode))); logv(c, format!("run_ignored: {}", config.run_ignored)); logv(c, format!("filter: {}", opt_str(&config.filter))); logv(c, format!("runtool: {}", opt_str(&config.runtool))); logv(c, format!("rustcflags: {}", opt_str(&config.rustcflags))); logv(c, format!("jit: {}", config.jit)); logv(c, format!("target: {}", config.target)); logv(c, format!("host: {}", config.host)); logv(c, format!("adb_path: {}", config.adb_path)); logv(c, format!("adb_test_dir: {}", config.adb_test_dir)); logv(c, format!("adb_device_status: {}", config.adb_device_status)); match config.test_shard { None => logv(c, ~"test_shard: (all)"), Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b)) } logv(c, format!("verbose: {}", config.verbose)); logv(c, format!("\n")); } pub fn opt_str<'a>(maybestr: &'a Option<~str>) -> &'a str { match *maybestr { None => "(none)", Some(ref s) => { let s: &'a str = *s; s } } } pub fn opt_str2(maybestr: Option<~str>) -> ~str { match maybestr { None => ~"(none)", Some(s) => { s } } } pub fn str_mode(s: ~str) -> mode { match s { ~"compile-fail" => mode_compile_fail, ~"run-fail" => mode_run_fail, ~"run-pass" => mode_run_pass, ~"pretty" => mode_pretty, ~"debug-info" => mode_debug_info, ~"codegen" => mode_codegen, _ => fail!("invalid mode") } } pub fn mode_str(mode: mode) -> ~str { match mode { mode_compile_fail => ~"compile-fail", mode_run_fail => ~"run-fail", mode_run_pass => ~"run-pass", mode_pretty => ~"pretty", mode_debug_info => ~"debug-info", mode_codegen => ~"codegen", } } pub fn run_tests(config: &config) { if config.target == ~"arm-linux-androideabi" { match config.mode{ mode_debug_info => { println!("arm-linux-androideabi debug-info \ test uses tcp 5039 port. please reserve it"); //arm-linux-androideabi debug-info test uses remote debugger //so, we test 1 task at once os::setenv("RUST_TEST_TASKS","1"); } _ =>{} } } let opts = test_opts(config); let tests = make_tests(config); // sadly osx needs some file descriptor limits raised for running tests in // parallel (especially when we have lots and lots of child processes). // For context, see #8904 io::test::raise_fd_limit(); let res = test::run_tests_console(&opts, tests); if!res { fail!("Some tests failed"); } } pub fn test_opts(config: &config) -> test::TestOpts { test::TestOpts { filter: config.filter.clone(), run_ignored: config.run_ignored, logfile: config.logfile.clone(), run_tests: true, run_benchmarks: true, ratchet_metrics: config.ratchet_metrics.clone(), ratchet_noise_percent: config.ratchet_noise_percent.clone(), save_metrics: config.save_metrics.clone(), test_shard: config.test_shard.clone() } } pub fn
(config: &config) -> ~[test::TestDescAndFn] { debug!("making tests from {}", config.src_base.display()); let mut tests = ~[]; let dirs = fs::readdir(&config.src_base); for file in dirs.iter() { let file = file.clone(); debug!("inspecting file {}", file.display()); if is_test(config, &file) { let t = make_test(config, &file, || { match config.mode { mode_codegen => make_metrics_test_closure(config, &file), _ => make_test_closure(config, &file) } }); tests.push(t) } } tests } pub fn is_test(config: &config, testfile: &Path) -> bool { // Pretty-printer does not work with.rc files yet let valid_extensions = match config.mode { mode_pretty => ~[~".rs"], _ => ~[~".rc", ~".rs"] }; let invalid_prefixes = ~[~".", ~"#", ~"~"]; let name = testfile.filename_str().unwrap(); let mut valid = false; for ext in valid_extensions.iter() { if name.ends_with(*ext) { valid = true; } } for pre in invalid_prefixes.iter() { if name.starts_with(*pre) { valid = false; } } return valid; } pub fn make_test(config: &config, testfile: &Path, f: || -> test::TestFn) -> test::TestDescAndFn { test::TestDescAndFn { desc: test::TestDesc { name: make_test_name(config, testfile), ignore: header::is_test_ignored(config, testfile), should_fail: false }, testfn: f(), } } pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName { // Try to elide redundant long paths fn shorten(path: &Path) -> ~str { let filename = path.filename_str(); let p = path.dir_path(); let dir = p.filename_str(); format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or("")) } test::DynTestName(format!("[{}] {}", mode_str(config.mode), shorten(testfile))) } pub fn make_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynTestFn(proc() { runtest::run(config, testfile) }) } pub fn make_metrics_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynMetricFn(proc(mm) { runtest::run_metrics(config, testfile, mm) }) }
make_tests
identifier_name
compiletest.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. #[crate_type = "bin"]; #[allow(non_camel_case_types)]; #[deny(warnings)]; extern mod extra; use std::os; use std::io; use std::io::fs; use extra::getopts; use extra::getopts::groups::{optopt, optflag, reqopt}; use extra::test; use common::config; use common::mode_run_pass; use common::mode_run_fail; use common::mode_compile_fail; use common::mode_pretty; use common::mode_debug_info; use common::mode_codegen; use common::mode; use util::logv; pub mod procsrv; pub mod util; pub mod header; pub mod runtest; pub mod common; pub mod errors; pub fn main() { let args = os::args(); let config = parse_config(args); log_config(&config); run_tests(&config); } pub fn parse_config(args: ~[~str]) -> config { let groups : ~[getopts::groups::OptGroup] = ~[reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"), reqopt("", "run-lib-path", "path to target shared libraries", "PATH"), reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"), optopt("", "clang-path", "path to executable for codegen tests", "PATH"), optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"), reqopt("", "src-base", "directory to scan for test files", "PATH"), reqopt("", "build-base", "directory to deposit test outputs", "PATH"), reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"), reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"), reqopt("", "mode", "which sort of compile tests to run", "(compile-fail|run-fail|run-pass|pretty|debug-info)"), optflag("", "ignored", "run tests marked as ignored / xfailed"), optopt("", "runtool", "supervisor program to run tests under \ (eg. emulator, valgrind)", "PROGRAM"), optopt("", "rustcflags", "flags to pass to rustc", "FLAGS"), optflag("", "verbose", "run tests verbosely, showing all output"), optopt("", "logfile", "file to log test execution to", "FILE"), optopt("", "save-metrics", "file to save metrics to", "FILE"), optopt("", "ratchet-metrics", "file to ratchet metrics against", "FILE"), optopt("", "ratchet-noise-percent", "percent change in metrics to consider noise", "N"), optflag("", "jit", "run tests under the JIT"), optopt("", "target", "the target to build for", "TARGET"), optopt("", "host", "the host to build for", "HOST"), optopt("", "adb-path", "path to the android debugger", "PATH"), optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"), optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", "A.B"), optflag("h", "help", "show this message"), ]; assert!(!args.is_empty()); let argv0 = args[0].clone(); let args_ = args.tail(); if args[1] == ~"-h" || args[1] == ~"--help" { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } let matches = &match getopts::groups::getopts(args_, groups) { Ok(m) => m, Err(f) => fail!("{}", f.to_err_msg()) }; if matches.opt_present("h") || matches.opt_present("help") { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } fn opt_path(m: &getopts::Matches, nm: &str) -> Path { Path::new(m.opt_str(nm).unwrap()) } config { compile_lib_path: matches.opt_str("compile-lib-path").unwrap(), run_lib_path: matches.opt_str("run-lib-path").unwrap(), rustc_path: opt_path(matches, "rustc-path"), clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)), llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)), src_base: opt_path(matches, "src-base"), build_base: opt_path(matches, "build-base"), aux_base: opt_path(matches, "aux-base"), stage_id: matches.opt_str("stage-id").unwrap(), mode: str_mode(matches.opt_str("mode").unwrap()), run_ignored: matches.opt_present("ignored"), filter: if!matches.free.is_empty() { Some(matches.free[0].clone()) } else { None }, logfile: matches.opt_str("logfile").map(|s| Path::new(s)), save_metrics: matches.opt_str("save-metrics").map(|s| Path::new(s)), ratchet_metrics: matches.opt_str("ratchet-metrics").map(|s| Path::new(s)), ratchet_noise_percent: matches.opt_str("ratchet-noise-percent").and_then(|s| from_str::<f64>(s)), runtool: matches.opt_str("runtool"), rustcflags: matches.opt_str("rustcflags"), jit: matches.opt_present("jit"), target: opt_str2(matches.opt_str("target")).to_str(), host: opt_str2(matches.opt_str("host")).to_str(), adb_path: opt_str2(matches.opt_str("adb-path")).to_str(), adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")).to_str(), adb_device_status: "arm-linux-androideabi" == opt_str2(matches.opt_str("target")) && "(none)"!= opt_str2(matches.opt_str("adb-test-dir")) && !opt_str2(matches.opt_str("adb-test-dir")).is_empty(), test_shard: test::opt_shard(matches.opt_str("test-shard")), verbose: matches.opt_present("verbose") } } pub fn log_config(config: &config) { let c = config; logv(c, format!("configuration:")); logv(c, format!("compile_lib_path: {}", config.compile_lib_path)); logv(c, format!("run_lib_path: {}", config.run_lib_path)); logv(c, format!("rustc_path: {}", config.rustc_path.display())); logv(c, format!("src_base: {}", config.src_base.display())); logv(c, format!("build_base: {}", config.build_base.display())); logv(c, format!("stage_id: {}", config.stage_id)); logv(c, format!("mode: {}", mode_str(config.mode))); logv(c, format!("run_ignored: {}", config.run_ignored)); logv(c, format!("filter: {}", opt_str(&config.filter))); logv(c, format!("runtool: {}", opt_str(&config.runtool))); logv(c, format!("rustcflags: {}", opt_str(&config.rustcflags))); logv(c, format!("jit: {}", config.jit)); logv(c, format!("target: {}", config.target)); logv(c, format!("host: {}", config.host)); logv(c, format!("adb_path: {}", config.adb_path)); logv(c, format!("adb_test_dir: {}", config.adb_test_dir)); logv(c, format!("adb_device_status: {}", config.adb_device_status)); match config.test_shard { None => logv(c, ~"test_shard: (all)"), Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b)) } logv(c, format!("verbose: {}", config.verbose)); logv(c, format!("\n")); } pub fn opt_str<'a>(maybestr: &'a Option<~str>) -> &'a str { match *maybestr { None => "(none)", Some(ref s) => { let s: &'a str = *s; s } } } pub fn opt_str2(maybestr: Option<~str>) -> ~str
pub fn str_mode(s: ~str) -> mode { match s { ~"compile-fail" => mode_compile_fail, ~"run-fail" => mode_run_fail, ~"run-pass" => mode_run_pass, ~"pretty" => mode_pretty, ~"debug-info" => mode_debug_info, ~"codegen" => mode_codegen, _ => fail!("invalid mode") } } pub fn mode_str(mode: mode) -> ~str { match mode { mode_compile_fail => ~"compile-fail", mode_run_fail => ~"run-fail", mode_run_pass => ~"run-pass", mode_pretty => ~"pretty", mode_debug_info => ~"debug-info", mode_codegen => ~"codegen", } } pub fn run_tests(config: &config) { if config.target == ~"arm-linux-androideabi" { match config.mode{ mode_debug_info => { println!("arm-linux-androideabi debug-info \ test uses tcp 5039 port. please reserve it"); //arm-linux-androideabi debug-info test uses remote debugger //so, we test 1 task at once os::setenv("RUST_TEST_TASKS","1"); } _ =>{} } } let opts = test_opts(config); let tests = make_tests(config); // sadly osx needs some file descriptor limits raised for running tests in // parallel (especially when we have lots and lots of child processes). // For context, see #8904 io::test::raise_fd_limit(); let res = test::run_tests_console(&opts, tests); if!res { fail!("Some tests failed"); } } pub fn test_opts(config: &config) -> test::TestOpts { test::TestOpts { filter: config.filter.clone(), run_ignored: config.run_ignored, logfile: config.logfile.clone(), run_tests: true, run_benchmarks: true, ratchet_metrics: config.ratchet_metrics.clone(), ratchet_noise_percent: config.ratchet_noise_percent.clone(), save_metrics: config.save_metrics.clone(), test_shard: config.test_shard.clone() } } pub fn make_tests(config: &config) -> ~[test::TestDescAndFn] { debug!("making tests from {}", config.src_base.display()); let mut tests = ~[]; let dirs = fs::readdir(&config.src_base); for file in dirs.iter() { let file = file.clone(); debug!("inspecting file {}", file.display()); if is_test(config, &file) { let t = make_test(config, &file, || { match config.mode { mode_codegen => make_metrics_test_closure(config, &file), _ => make_test_closure(config, &file) } }); tests.push(t) } } tests } pub fn is_test(config: &config, testfile: &Path) -> bool { // Pretty-printer does not work with.rc files yet let valid_extensions = match config.mode { mode_pretty => ~[~".rs"], _ => ~[~".rc", ~".rs"] }; let invalid_prefixes = ~[~".", ~"#", ~"~"]; let name = testfile.filename_str().unwrap(); let mut valid = false; for ext in valid_extensions.iter() { if name.ends_with(*ext) { valid = true; } } for pre in invalid_prefixes.iter() { if name.starts_with(*pre) { valid = false; } } return valid; } pub fn make_test(config: &config, testfile: &Path, f: || -> test::TestFn) -> test::TestDescAndFn { test::TestDescAndFn { desc: test::TestDesc { name: make_test_name(config, testfile), ignore: header::is_test_ignored(config, testfile), should_fail: false }, testfn: f(), } } pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName { // Try to elide redundant long paths fn shorten(path: &Path) -> ~str { let filename = path.filename_str(); let p = path.dir_path(); let dir = p.filename_str(); format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or("")) } test::DynTestName(format!("[{}] {}", mode_str(config.mode), shorten(testfile))) } pub fn make_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynTestFn(proc() { runtest::run(config, testfile) }) } pub fn make_metrics_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynMetricFn(proc(mm) { runtest::run_metrics(config, testfile, mm) }) }
{ match maybestr { None => ~"(none)", Some(s) => { s } } }
identifier_body
compiletest.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. #[crate_type = "bin"]; #[allow(non_camel_case_types)]; #[deny(warnings)]; extern mod extra; use std::os; use std::io; use std::io::fs; use extra::getopts; use extra::getopts::groups::{optopt, optflag, reqopt}; use extra::test; use common::config; use common::mode_run_pass; use common::mode_run_fail; use common::mode_compile_fail; use common::mode_pretty; use common::mode_debug_info; use common::mode_codegen; use common::mode; use util::logv; pub mod procsrv; pub mod util; pub mod header; pub mod runtest; pub mod common; pub mod errors; pub fn main() { let args = os::args(); let config = parse_config(args); log_config(&config); run_tests(&config); } pub fn parse_config(args: ~[~str]) -> config { let groups : ~[getopts::groups::OptGroup] = ~[reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"), reqopt("", "run-lib-path", "path to target shared libraries", "PATH"), reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"), optopt("", "clang-path", "path to executable for codegen tests", "PATH"), optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"), reqopt("", "src-base", "directory to scan for test files", "PATH"), reqopt("", "build-base", "directory to deposit test outputs", "PATH"), reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"), reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"), reqopt("", "mode", "which sort of compile tests to run", "(compile-fail|run-fail|run-pass|pretty|debug-info)"), optflag("", "ignored", "run tests marked as ignored / xfailed"), optopt("", "runtool", "supervisor program to run tests under \ (eg. emulator, valgrind)", "PROGRAM"), optopt("", "rustcflags", "flags to pass to rustc", "FLAGS"), optflag("", "verbose", "run tests verbosely, showing all output"), optopt("", "logfile", "file to log test execution to", "FILE"), optopt("", "save-metrics", "file to save metrics to", "FILE"), optopt("", "ratchet-metrics", "file to ratchet metrics against", "FILE"), optopt("", "ratchet-noise-percent", "percent change in metrics to consider noise", "N"), optflag("", "jit", "run tests under the JIT"), optopt("", "target", "the target to build for", "TARGET"), optopt("", "host", "the host to build for", "HOST"), optopt("", "adb-path", "path to the android debugger", "PATH"), optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"), optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", "A.B"), optflag("h", "help", "show this message"), ]; assert!(!args.is_empty()); let argv0 = args[0].clone(); let args_ = args.tail(); if args[1] == ~"-h" || args[1] == ~"--help" { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } let matches = &match getopts::groups::getopts(args_, groups) { Ok(m) => m, Err(f) => fail!("{}", f.to_err_msg()) }; if matches.opt_present("h") || matches.opt_present("help") { let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); println!("{}", getopts::groups::usage(message, groups)); println!(""); fail!() } fn opt_path(m: &getopts::Matches, nm: &str) -> Path { Path::new(m.opt_str(nm).unwrap()) } config { compile_lib_path: matches.opt_str("compile-lib-path").unwrap(), run_lib_path: matches.opt_str("run-lib-path").unwrap(), rustc_path: opt_path(matches, "rustc-path"), clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)), llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)), src_base: opt_path(matches, "src-base"), build_base: opt_path(matches, "build-base"), aux_base: opt_path(matches, "aux-base"), stage_id: matches.opt_str("stage-id").unwrap(), mode: str_mode(matches.opt_str("mode").unwrap()), run_ignored: matches.opt_present("ignored"), filter: if!matches.free.is_empty() { Some(matches.free[0].clone()) } else { None }, logfile: matches.opt_str("logfile").map(|s| Path::new(s)), save_metrics: matches.opt_str("save-metrics").map(|s| Path::new(s)), ratchet_metrics: matches.opt_str("ratchet-metrics").map(|s| Path::new(s)), ratchet_noise_percent: matches.opt_str("ratchet-noise-percent").and_then(|s| from_str::<f64>(s)), runtool: matches.opt_str("runtool"), rustcflags: matches.opt_str("rustcflags"), jit: matches.opt_present("jit"), target: opt_str2(matches.opt_str("target")).to_str(), host: opt_str2(matches.opt_str("host")).to_str(), adb_path: opt_str2(matches.opt_str("adb-path")).to_str(), adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")).to_str(), adb_device_status: "arm-linux-androideabi" == opt_str2(matches.opt_str("target")) && "(none)"!= opt_str2(matches.opt_str("adb-test-dir")) && !opt_str2(matches.opt_str("adb-test-dir")).is_empty(), test_shard: test::opt_shard(matches.opt_str("test-shard")), verbose: matches.opt_present("verbose") } } pub fn log_config(config: &config) { let c = config; logv(c, format!("configuration:")); logv(c, format!("compile_lib_path: {}", config.compile_lib_path)); logv(c, format!("run_lib_path: {}", config.run_lib_path)); logv(c, format!("rustc_path: {}", config.rustc_path.display())); logv(c, format!("src_base: {}", config.src_base.display())); logv(c, format!("build_base: {}", config.build_base.display())); logv(c, format!("stage_id: {}", config.stage_id)); logv(c, format!("mode: {}", mode_str(config.mode))); logv(c, format!("run_ignored: {}", config.run_ignored)); logv(c, format!("filter: {}", opt_str(&config.filter))); logv(c, format!("runtool: {}", opt_str(&config.runtool))); logv(c, format!("rustcflags: {}", opt_str(&config.rustcflags))); logv(c, format!("jit: {}", config.jit)); logv(c, format!("target: {}", config.target)); logv(c, format!("host: {}", config.host)); logv(c, format!("adb_path: {}", config.adb_path)); logv(c, format!("adb_test_dir: {}", config.adb_test_dir)); logv(c, format!("adb_device_status: {}", config.adb_device_status)); match config.test_shard { None => logv(c, ~"test_shard: (all)"), Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b)) } logv(c, format!("verbose: {}", config.verbose)); logv(c, format!("\n")); } pub fn opt_str<'a>(maybestr: &'a Option<~str>) -> &'a str { match *maybestr { None => "(none)", Some(ref s) => { let s: &'a str = *s; s } } } pub fn opt_str2(maybestr: Option<~str>) -> ~str { match maybestr { None => ~"(none)", Some(s) => { s } } } pub fn str_mode(s: ~str) -> mode { match s { ~"compile-fail" => mode_compile_fail, ~"run-fail" => mode_run_fail, ~"run-pass" => mode_run_pass, ~"pretty" => mode_pretty, ~"debug-info" => mode_debug_info, ~"codegen" => mode_codegen, _ => fail!("invalid mode") } } pub fn mode_str(mode: mode) -> ~str { match mode { mode_compile_fail => ~"compile-fail", mode_run_fail => ~"run-fail",
mode_run_pass => ~"run-pass", mode_pretty => ~"pretty", mode_debug_info => ~"debug-info", mode_codegen => ~"codegen", } } pub fn run_tests(config: &config) { if config.target == ~"arm-linux-androideabi" { match config.mode{ mode_debug_info => { println!("arm-linux-androideabi debug-info \ test uses tcp 5039 port. please reserve it"); //arm-linux-androideabi debug-info test uses remote debugger //so, we test 1 task at once os::setenv("RUST_TEST_TASKS","1"); } _ =>{} } } let opts = test_opts(config); let tests = make_tests(config); // sadly osx needs some file descriptor limits raised for running tests in // parallel (especially when we have lots and lots of child processes). // For context, see #8904 io::test::raise_fd_limit(); let res = test::run_tests_console(&opts, tests); if!res { fail!("Some tests failed"); } } pub fn test_opts(config: &config) -> test::TestOpts { test::TestOpts { filter: config.filter.clone(), run_ignored: config.run_ignored, logfile: config.logfile.clone(), run_tests: true, run_benchmarks: true, ratchet_metrics: config.ratchet_metrics.clone(), ratchet_noise_percent: config.ratchet_noise_percent.clone(), save_metrics: config.save_metrics.clone(), test_shard: config.test_shard.clone() } } pub fn make_tests(config: &config) -> ~[test::TestDescAndFn] { debug!("making tests from {}", config.src_base.display()); let mut tests = ~[]; let dirs = fs::readdir(&config.src_base); for file in dirs.iter() { let file = file.clone(); debug!("inspecting file {}", file.display()); if is_test(config, &file) { let t = make_test(config, &file, || { match config.mode { mode_codegen => make_metrics_test_closure(config, &file), _ => make_test_closure(config, &file) } }); tests.push(t) } } tests } pub fn is_test(config: &config, testfile: &Path) -> bool { // Pretty-printer does not work with.rc files yet let valid_extensions = match config.mode { mode_pretty => ~[~".rs"], _ => ~[~".rc", ~".rs"] }; let invalid_prefixes = ~[~".", ~"#", ~"~"]; let name = testfile.filename_str().unwrap(); let mut valid = false; for ext in valid_extensions.iter() { if name.ends_with(*ext) { valid = true; } } for pre in invalid_prefixes.iter() { if name.starts_with(*pre) { valid = false; } } return valid; } pub fn make_test(config: &config, testfile: &Path, f: || -> test::TestFn) -> test::TestDescAndFn { test::TestDescAndFn { desc: test::TestDesc { name: make_test_name(config, testfile), ignore: header::is_test_ignored(config, testfile), should_fail: false }, testfn: f(), } } pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName { // Try to elide redundant long paths fn shorten(path: &Path) -> ~str { let filename = path.filename_str(); let p = path.dir_path(); let dir = p.filename_str(); format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or("")) } test::DynTestName(format!("[{}] {}", mode_str(config.mode), shorten(testfile))) } pub fn make_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynTestFn(proc() { runtest::run(config, testfile) }) } pub fn make_metrics_test_closure(config: &config, testfile: &Path) -> test::TestFn { let config = (*config).clone(); // FIXME (#9639): This needs to handle non-utf8 paths let testfile = testfile.as_str().unwrap().to_owned(); test::DynMetricFn(proc(mm) { runtest::run_metrics(config, testfile, mm) }) }
random_line_split
main.rs
// Copyright 2018 Google Inc. // // 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. use std::{ io::{stdout, BufWriter}, path::Path, process::Command, }; fn main()
{ // Note: This will need to change if the dependency version changes let texture_synthesis_path = Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis"); // Run the command let texture_synthesis_output = Command::new(texture_synthesis_path) .arg("--help") .output() .unwrap(); // Print the results let mut writer = BufWriter::new(stdout()); ferris_says::say(&texture_synthesis_output.stdout, 120, &mut writer).unwrap(); }
identifier_body
main.rs
// Copyright 2018 Google Inc. // // 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. use std::{ io::{stdout, BufWriter}, path::Path, process::Command, }; fn main() {
Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis"); // Run the command let texture_synthesis_output = Command::new(texture_synthesis_path) .arg("--help") .output() .unwrap(); // Print the results let mut writer = BufWriter::new(stdout()); ferris_says::say(&texture_synthesis_output.stdout, 120, &mut writer).unwrap(); }
// Note: This will need to change if the dependency version changes let texture_synthesis_path =
random_line_split
main.rs
// Copyright 2018 Google Inc. // // 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. use std::{ io::{stdout, BufWriter}, path::Path, process::Command, }; fn
() { // Note: This will need to change if the dependency version changes let texture_synthesis_path = Path::new("./external/remote_binary_dependencies__texture_synthesis_cli__0_8_0/cargo_bin_texture_synthesis"); // Run the command let texture_synthesis_output = Command::new(texture_synthesis_path) .arg("--help") .output() .unwrap(); // Print the results let mut writer = BufWriter::new(stdout()); ferris_says::say(&texture_synthesis_output.stdout, 120, &mut writer).unwrap(); }
main
identifier_name
utils.rs
use byteorder::BigEndian; use byteorder::ByteOrder; use fcp_cryptoauth::CAWrapper; use operation::{BackwardPath, ForwardPath}; use packets::switch::Payload as SwitchPayload; use packets::switch::SwitchPacket; use session_manager::{SessionHandle, TheirSessionHandle}; /// Creates a switch packet from a raw payload. /// The content of the packet is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn new_from_raw_content( path: ForwardPath, content: Vec<u8>, handle: Option<TheirSessionHandle>, ) -> SwitchPacket { let first_four_bytes = BigEndian::read_u32(&content[0..4]); match first_four_bytes { 0 | 1 => { // If it is a CryptoAuth handshake Hello packet, send it as is. let payload = SwitchPayload::CryptoAuthHello(content); SwitchPacket::new(path, payload) } 2 | 3 => { // If it is a CryptoAuth handshake Key packet, send it as is. SwitchPacket::new(path, SwitchPayload::CryptoAuthKey(content)) } 0xffffffff => { // Control packet unimplemented!() } _ =>
} } /// Creates a reply switch packet to an other switch packet. /// The content of the reply is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn make_reply<PeerId: Clone>( replied_to_packet: &SwitchPacket, reply_content: Vec<u8>, inner_conn: &CAWrapper<PeerId>, ) -> SwitchPacket { let path = BackwardPath::from(replied_to_packet.label()).reverse(); new_from_raw_content( path, reply_content, inner_conn .peer_session_handle() .map(SessionHandle) .map(TheirSessionHandle), ) }
{ // Otherwise, it is a CryptoAuth data packet. We have to prepend // the session handle to the reply. // This handle is used by the peer to know this packet is coming // from us. let peer_handle = handle.unwrap().0; SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content)) }
conditional_block
utils.rs
use byteorder::BigEndian; use byteorder::ByteOrder; use fcp_cryptoauth::CAWrapper; use operation::{BackwardPath, ForwardPath}; use packets::switch::Payload as SwitchPayload; use packets::switch::SwitchPacket; use session_manager::{SessionHandle, TheirSessionHandle}; /// Creates a switch packet from a raw payload. /// The content of the packet is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn new_from_raw_content( path: ForwardPath, content: Vec<u8>, handle: Option<TheirSessionHandle>, ) -> SwitchPacket
// from us. let peer_handle = handle.unwrap().0; SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content)) } } } /// Creates a reply switch packet to an other switch packet. /// The content of the reply is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn make_reply<PeerId: Clone>( replied_to_packet: &SwitchPacket, reply_content: Vec<u8>, inner_conn: &CAWrapper<PeerId>, ) -> SwitchPacket { let path = BackwardPath::from(replied_to_packet.label()).reverse(); new_from_raw_content( path, reply_content, inner_conn .peer_session_handle() .map(SessionHandle) .map(TheirSessionHandle), ) }
{ let first_four_bytes = BigEndian::read_u32(&content[0..4]); match first_four_bytes { 0 | 1 => { // If it is a CryptoAuth handshake Hello packet, send it as is. let payload = SwitchPayload::CryptoAuthHello(content); SwitchPacket::new(path, payload) } 2 | 3 => { // If it is a CryptoAuth handshake Key packet, send it as is. SwitchPacket::new(path, SwitchPayload::CryptoAuthKey(content)) } 0xffffffff => { // Control packet unimplemented!() } _ => { // Otherwise, it is a CryptoAuth data packet. We have to prepend // the session handle to the reply. // This handle is used by the peer to know this packet is coming
identifier_body
utils.rs
use byteorder::BigEndian; use byteorder::ByteOrder; use fcp_cryptoauth::CAWrapper; use operation::{BackwardPath, ForwardPath}; use packets::switch::Payload as SwitchPayload; use packets::switch::SwitchPacket; use session_manager::{SessionHandle, TheirSessionHandle}; /// Creates a switch packet from a raw payload. /// The content of the packet is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn new_from_raw_content( path: ForwardPath, content: Vec<u8>, handle: Option<TheirSessionHandle>, ) -> SwitchPacket { let first_four_bytes = BigEndian::read_u32(&content[0..4]); match first_four_bytes { 0 | 1 => { // If it is a CryptoAuth handshake Hello packet, send it as is. let payload = SwitchPayload::CryptoAuthHello(content); SwitchPacket::new(path, payload) } 2 | 3 => { // If it is a CryptoAuth handshake Key packet, send it as is. SwitchPacket::new(path, SwitchPayload::CryptoAuthKey(content)) } 0xffffffff => { // Control packet unimplemented!() } _ => { // Otherwise, it is a CryptoAuth data packet. We have to prepend // the session handle to the reply. // This handle is used by the peer to know this packet is coming // from us. let peer_handle = handle.unwrap().0; SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content)) } } } /// Creates a reply switch packet to an other switch packet. /// The content of the reply is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn
<PeerId: Clone>( replied_to_packet: &SwitchPacket, reply_content: Vec<u8>, inner_conn: &CAWrapper<PeerId>, ) -> SwitchPacket { let path = BackwardPath::from(replied_to_packet.label()).reverse(); new_from_raw_content( path, reply_content, inner_conn .peer_session_handle() .map(SessionHandle) .map(TheirSessionHandle), ) }
make_reply
identifier_name
utils.rs
use byteorder::BigEndian; use byteorder::ByteOrder; use fcp_cryptoauth::CAWrapper; use operation::{BackwardPath, ForwardPath}; use packets::switch::Payload as SwitchPayload; use packets::switch::SwitchPacket; use session_manager::{SessionHandle, TheirSessionHandle}; /// Creates a switch packet from a raw payload. /// The content of the packet is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn new_from_raw_content( path: ForwardPath, content: Vec<u8>, handle: Option<TheirSessionHandle>, ) -> SwitchPacket { let first_four_bytes = BigEndian::read_u32(&content[0..4]); match first_four_bytes { 0 | 1 => { // If it is a CryptoAuth handshake Hello packet, send it as is. let payload = SwitchPayload::CryptoAuthHello(content); SwitchPacket::new(path, payload) } 2 | 3 => { // If it is a CryptoAuth handshake Key packet, send it as is. SwitchPacket::new(path, SwitchPayload::CryptoAuthKey(content)) } 0xffffffff => { // Control packet
// This handle is used by the peer to know this packet is coming // from us. let peer_handle = handle.unwrap().0; SwitchPacket::new(path, SwitchPayload::CryptoAuthData(peer_handle, content)) } } } /// Creates a reply switch packet to an other switch packet. /// The content of the reply is given as a byte array (returned by CryptoAuth's /// `wrap_messages`). pub fn make_reply<PeerId: Clone>( replied_to_packet: &SwitchPacket, reply_content: Vec<u8>, inner_conn: &CAWrapper<PeerId>, ) -> SwitchPacket { let path = BackwardPath::from(replied_to_packet.label()).reverse(); new_from_raw_content( path, reply_content, inner_conn .peer_session_handle() .map(SessionHandle) .map(TheirSessionHandle), ) }
unimplemented!() } _ => { // Otherwise, it is a CryptoAuth data packet. We have to prepend // the session handle to the reply.
random_line_split
tcp.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. #![allow(deprecated)] use old_io::net::ip; use old_io::IoResult; use libc; use mem; use ptr; use prelude::v1::*; use super::{last_error, last_net_error, sock_t}; use sync::Arc; use sync::atomic::{AtomicBool, Ordering}; use sys::{self, c, set_nonblocking, wouldblock, timer}; use sys_common::{timeout, eof, net}; pub use sys_common::net::TcpStream; pub struct Event(c::WSAEVENT); unsafe impl Send for Event {} unsafe impl Sync for Event {} impl Event { pub fn new() -> IoResult<Event> { let event = unsafe { c::WSACreateEvent() }; if event == c::WSA_INVALID_EVENT { Err(super::last_error()) } else { Ok(Event(event)) } } pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle } } impl Drop for Event { fn drop(&mut self) { unsafe { let _ = c::WSACloseEvent(self.handle()); } } } //////////////////////////////////////////////////////////////////////////////// // TCP listeners //////////////////////////////////////////////////////////////////////////////// pub struct TcpListener { sock: sock_t } unsafe impl Send for TcpListener {} unsafe impl Sync for TcpListener {} impl TcpListener { pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> { sys::init_net(); let sock = try!(net::socket(addr, libc::SOCK_STREAM)); let ret = TcpListener { sock: sock }; let mut storage = unsafe { mem::zeroed() }; let len = net::addr_to_sockaddr(addr, &mut storage); let addrp = &storage as *const _ as *const libc::sockaddr; match unsafe { libc::bind(sock, addrp, len) } { -1 => Err(last_net_error()), _ => Ok(ret), } } pub fn socket(&self) -> sock_t { self.sock } pub fn listen(self, backlog: int) -> IoResult<TcpAcceptor> { match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } { -1 => Err(last_net_error()), _ => { let accept = try!(Event::new()); let ret = unsafe { c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT) }; if ret!= 0 { return Err(last_net_error()) } Ok(TcpAcceptor { inner: Arc::new(AcceptorInner { listener: self, abort: try!(Event::new()), accept: accept, closed: AtomicBool::new(false), }), deadline: 0, }) } } } pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> { net::sockname(self.socket(), libc::getsockname) } } impl Drop for TcpListener { fn drop(&mut self) { unsafe { super::close_sock(self.sock); } } } pub struct
{ inner: Arc<AcceptorInner>, deadline: u64, } struct AcceptorInner { listener: TcpListener, abort: Event, accept: Event, closed: AtomicBool, } unsafe impl Sync for AcceptorInner {} impl TcpAcceptor { pub fn socket(&self) -> sock_t { self.inner.listener.socket() } pub fn accept(&mut self) -> IoResult<TcpStream> { // Unlink unix, windows cannot invoke `select` on arbitrary file // descriptors like pipes, only sockets. Consequently, windows cannot // use the same implementation as unix for accept() when close_accept() // is considered. // // In order to implement close_accept() and timeouts, windows uses // event handles. An acceptor-specific abort event is created which // will only get set in close_accept(), and it will never be un-set. // Additionally, another acceptor-specific event is associated with the // FD_ACCEPT network event. // // These two events are then passed to WaitForMultipleEvents to see // which one triggers first, and the timeout passed to this function is // the local timeout for the acceptor. // // If the wait times out, then the accept timed out. If the wait // succeeds with the abort event, then we were closed, and if the wait // succeeds otherwise, then we do a nonblocking poll via `accept` to // see if we can accept a connection. The connection is candidate to be // stolen, so we do all of this in a loop as well. let events = [self.inner.abort.handle(), self.inner.accept.handle()]; while!self.inner.closed.load(Ordering::SeqCst) { let ms = if self.deadline == 0 { c::WSA_INFINITE as u64 } else { let now = timer::now(); if self.deadline < now {0} else {self.deadline - now} }; let ret = unsafe { c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE, ms as libc::DWORD, libc::FALSE) }; match ret { c::WSA_WAIT_TIMEOUT => { return Err(timeout("accept timed out")) } c::WSA_WAIT_FAILED => return Err(last_net_error()), c::WSA_WAIT_EVENT_0 => break, n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1), } let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() }; let ret = unsafe { c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents) }; if ret!= 0 { return Err(last_net_error()) } if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue } match unsafe { libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut()) } { -1 if wouldblock() => {} -1 => return Err(last_net_error()), // Accepted sockets inherit the same properties as the caller, // so we need to deregister our event and switch the socket back // to blocking mode socket => { let stream = TcpStream::new(socket); let ret = unsafe { c::WSAEventSelect(socket, events[1], 0) }; if ret!= 0 { return Err(last_net_error()) } set_nonblocking(socket, false); return Ok(stream) } } } Err(eof()) } pub fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); } pub fn close_accept(&mut self) -> IoResult<()> { self.inner.closed.store(true, Ordering::SeqCst); let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) }; if ret == libc::TRUE { Ok(()) } else { Err(last_net_error()) } } } impl Clone for TcpAcceptor { fn clone(&self) -> TcpAcceptor { TcpAcceptor { inner: self.inner.clone(), deadline: 0, } } }
TcpAcceptor
identifier_name
tcp.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. #![allow(deprecated)] use old_io::net::ip; use old_io::IoResult; use libc; use mem; use ptr; use prelude::v1::*; use super::{last_error, last_net_error, sock_t}; use sync::Arc; use sync::atomic::{AtomicBool, Ordering}; use sys::{self, c, set_nonblocking, wouldblock, timer}; use sys_common::{timeout, eof, net}; pub use sys_common::net::TcpStream; pub struct Event(c::WSAEVENT); unsafe impl Send for Event {} unsafe impl Sync for Event {} impl Event { pub fn new() -> IoResult<Event> { let event = unsafe { c::WSACreateEvent() }; if event == c::WSA_INVALID_EVENT { Err(super::last_error()) } else { Ok(Event(event)) } } pub fn handle(&self) -> c::WSAEVENT { let Event(handle) = *self; handle } } impl Drop for Event { fn drop(&mut self) { unsafe { let _ = c::WSACloseEvent(self.handle()); } } } //////////////////////////////////////////////////////////////////////////////// // TCP listeners //////////////////////////////////////////////////////////////////////////////// pub struct TcpListener { sock: sock_t } unsafe impl Send for TcpListener {} unsafe impl Sync for TcpListener {} impl TcpListener { pub fn bind(addr: ip::SocketAddr) -> IoResult<TcpListener> { sys::init_net(); let sock = try!(net::socket(addr, libc::SOCK_STREAM)); let ret = TcpListener { sock: sock }; let mut storage = unsafe { mem::zeroed() }; let len = net::addr_to_sockaddr(addr, &mut storage); let addrp = &storage as *const _ as *const libc::sockaddr; match unsafe { libc::bind(sock, addrp, len) } { -1 => Err(last_net_error()), _ => Ok(ret), } } pub fn socket(&self) -> sock_t { self.sock } pub fn listen(self, backlog: int) -> IoResult<TcpAcceptor> { match unsafe { libc::listen(self.socket(), backlog as libc::c_int) } { -1 => Err(last_net_error()), _ => { let accept = try!(Event::new()); let ret = unsafe { c::WSAEventSelect(self.socket(), accept.handle(), c::FD_ACCEPT) }; if ret!= 0 { return Err(last_net_error()) } Ok(TcpAcceptor { inner: Arc::new(AcceptorInner { listener: self, abort: try!(Event::new()), accept: accept, closed: AtomicBool::new(false), }), deadline: 0, }) } } } pub fn socket_name(&mut self) -> IoResult<ip::SocketAddr> { net::sockname(self.socket(), libc::getsockname) } } impl Drop for TcpListener { fn drop(&mut self) { unsafe { super::close_sock(self.sock); } } } pub struct TcpAcceptor { inner: Arc<AcceptorInner>, deadline: u64, } struct AcceptorInner { listener: TcpListener, abort: Event, accept: Event, closed: AtomicBool, } unsafe impl Sync for AcceptorInner {} impl TcpAcceptor { pub fn socket(&self) -> sock_t { self.inner.listener.socket() } pub fn accept(&mut self) -> IoResult<TcpStream> { // Unlink unix, windows cannot invoke `select` on arbitrary file // descriptors like pipes, only sockets. Consequently, windows cannot // use the same implementation as unix for accept() when close_accept() // is considered. // // In order to implement close_accept() and timeouts, windows uses // event handles. An acceptor-specific abort event is created which // will only get set in close_accept(), and it will never be un-set. // Additionally, another acceptor-specific event is associated with the // FD_ACCEPT network event. // // These two events are then passed to WaitForMultipleEvents to see // which one triggers first, and the timeout passed to this function is // the local timeout for the acceptor. // // If the wait times out, then the accept timed out. If the wait // succeeds with the abort event, then we were closed, and if the wait // succeeds otherwise, then we do a nonblocking poll via `accept` to // see if we can accept a connection. The connection is candidate to be // stolen, so we do all of this in a loop as well. let events = [self.inner.abort.handle(), self.inner.accept.handle()]; while!self.inner.closed.load(Ordering::SeqCst) { let ms = if self.deadline == 0 { c::WSA_INFINITE as u64 } else { let now = timer::now(); if self.deadline < now {0} else {self.deadline - now} }; let ret = unsafe { c::WSAWaitForMultipleEvents(2, events.as_ptr(), libc::FALSE, ms as libc::DWORD, libc::FALSE) }; match ret { c::WSA_WAIT_TIMEOUT => { return Err(timeout("accept timed out")) } c::WSA_WAIT_FAILED => return Err(last_net_error()), c::WSA_WAIT_EVENT_0 => break, n => assert_eq!(n, c::WSA_WAIT_EVENT_0 + 1), } let mut wsaevents: c::WSANETWORKEVENTS = unsafe { mem::zeroed() }; let ret = unsafe { c::WSAEnumNetworkEvents(self.socket(), events[1], &mut wsaevents) }; if ret!= 0 { return Err(last_net_error()) } if wsaevents.lNetworkEvents & c::FD_ACCEPT == 0 { continue } match unsafe { libc::accept(self.socket(), ptr::null_mut(), ptr::null_mut()) } { -1 if wouldblock() => {} -1 => return Err(last_net_error()), // Accepted sockets inherit the same properties as the caller, // so we need to deregister our event and switch the socket back
c::WSAEventSelect(socket, events[1], 0) }; if ret!= 0 { return Err(last_net_error()) } set_nonblocking(socket, false); return Ok(stream) } } } Err(eof()) } pub fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0); } pub fn close_accept(&mut self) -> IoResult<()> { self.inner.closed.store(true, Ordering::SeqCst); let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) }; if ret == libc::TRUE { Ok(()) } else { Err(last_net_error()) } } } impl Clone for TcpAcceptor { fn clone(&self) -> TcpAcceptor { TcpAcceptor { inner: self.inner.clone(), deadline: 0, } } }
// to blocking mode socket => { let stream = TcpStream::new(socket); let ret = unsafe {
random_line_split
github_repositorypermissions.rs
/*
* Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct GithubRepositorypermissions { #[serde(rename = "admin", skip_serializing_if = "Option::is_none")] pub admin: Option<bool>, #[serde(rename = "push", skip_serializing_if = "Option::is_none")] pub push: Option<bool>, #[serde(rename = "pull", skip_serializing_if = "Option::is_none")] pub pull: Option<bool>, #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, } impl GithubRepositorypermissions { pub fn new() -> GithubRepositorypermissions { GithubRepositorypermissions { admin: None, push: None, pull: None, _class: None, } } }
* Swaggy Jenkins *
random_line_split
github_repositorypermissions.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct GithubRepositorypermissions { #[serde(rename = "admin", skip_serializing_if = "Option::is_none")] pub admin: Option<bool>, #[serde(rename = "push", skip_serializing_if = "Option::is_none")] pub push: Option<bool>, #[serde(rename = "pull", skip_serializing_if = "Option::is_none")] pub pull: Option<bool>, #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, } impl GithubRepositorypermissions { pub fn new() -> GithubRepositorypermissions
}
{ GithubRepositorypermissions { admin: None, push: None, pull: None, _class: None, } }
identifier_body
github_repositorypermissions.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct
{ #[serde(rename = "admin", skip_serializing_if = "Option::is_none")] pub admin: Option<bool>, #[serde(rename = "push", skip_serializing_if = "Option::is_none")] pub push: Option<bool>, #[serde(rename = "pull", skip_serializing_if = "Option::is_none")] pub pull: Option<bool>, #[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, } impl GithubRepositorypermissions { pub fn new() -> GithubRepositorypermissions { GithubRepositorypermissions { admin: None, push: None, pull: None, _class: None, } } }
GithubRepositorypermissions
identifier_name
dynamodb.rs
#![cfg(feature = "dynamodb")] extern crate rusoto; use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn
() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); // limit of -1 should generate a validation error let request = ListTablesInput { limit: Some(-1),..Default::default() }; let response = client.list_tables(&request); match response { Err(ListTablesError::Validation(msg)) => { assert!(msg.contains("Member must have value greater than or equal to 1")) } _ => panic!("Should have been a Validation error"), }; } #[test] fn should_list_tables() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = ListTablesInput::default(); client.list_tables(&request).unwrap(); }
should_parse_error_type
identifier_name
dynamodb.rs
#![cfg(feature = "dynamodb")] extern crate rusoto; use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_parse_error_type() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); // limit of -1 should generate a validation error let request = ListTablesInput { limit: Some(-1),..Default::default() }; let response = client.list_tables(&request); match response { Err(ListTablesError::Validation(msg)) =>
_ => panic!("Should have been a Validation error"), }; } #[test] fn should_list_tables() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = ListTablesInput::default(); client.list_tables(&request).unwrap(); }
{ assert!(msg.contains("Member must have value greater than or equal to 1")) }
conditional_block
dynamodb.rs
#![cfg(feature = "dynamodb")] extern crate rusoto; use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_parse_error_type() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); // limit of -1 should generate a validation error let request = ListTablesInput { limit: Some(-1),..Default::default() }; let response = client.list_tables(&request); match response { Err(ListTablesError::Validation(msg)) => { assert!(msg.contains("Member must have value greater than or equal to 1")) } _ => panic!("Should have been a Validation error"), }; } #[test]
fn should_list_tables() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = ListTablesInput::default(); client.list_tables(&request).unwrap(); }
random_line_split
dynamodb.rs
#![cfg(feature = "dynamodb")] extern crate rusoto; use rusoto::dynamodb::{DynamoDb, DynamoDbClient, ListTablesInput, ListTablesError}; use rusoto::{DefaultCredentialsProvider, Region}; use rusoto::default_tls_client; #[test] fn should_parse_error_type() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); // limit of -1 should generate a validation error let request = ListTablesInput { limit: Some(-1),..Default::default() }; let response = client.list_tables(&request); match response { Err(ListTablesError::Validation(msg)) => { assert!(msg.contains("Member must have value greater than or equal to 1")) } _ => panic!("Should have been a Validation error"), }; } #[test] fn should_list_tables()
{ let credentials = DefaultCredentialsProvider::new().unwrap(); let client = DynamoDbClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1); let request = ListTablesInput::default(); client.list_tables(&request).unwrap(); }
identifier_body
error.rs
//! # Keystore files (UTC / JSON) module errors use super::core; use std::{error, fmt}; /// Keystore file errors #[derive(Debug)] pub enum Error { /// An unsupported cipher UnsupportedCipher(String), /// An unsupported key derivation function UnsupportedKdf(String), /// An unsupported pseudo-random function UnsupportedPrf(String), /// `keccak256_mac` field validation failed FailedMacValidation, /// Core module error wrapper CoreFault(core::Error), /// Invalid Kdf depth value InvalidKdfDepth(String), } impl From<core::Error> for Error { fn from(err: core::Error) -> Self { Error::CoreFault(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::UnsupportedCipher(ref str) => write!(f, "Unsupported cipher: {}", str), Error::UnsupportedKdf(ref str) => { write!(f, "Unsupported key derivation function: {}", str) } Error::UnsupportedPrf(ref str) => { write!(f, "Unsupported pseudo-random function: {}", str) } Error::FailedMacValidation => write!(f, "Message authentication code failed"), Error::CoreFault(ref err) => f.write_str(&err.to_string()), Error::InvalidKdfDepth(ref str) => write!(f, "Invalid security level: {}", str), } } } impl error::Error for Error { fn description(&self) -> &str { "Keystore file error" } fn cause(&self) -> Option<&error::Error>
}
{ match *self { Error::CoreFault(ref err) => Some(err), _ => None, } }
identifier_body
error.rs
//! # Keystore files (UTC / JSON) module errors use super::core; use std::{error, fmt}; /// Keystore file errors #[derive(Debug)] pub enum
{ /// An unsupported cipher UnsupportedCipher(String), /// An unsupported key derivation function UnsupportedKdf(String), /// An unsupported pseudo-random function UnsupportedPrf(String), /// `keccak256_mac` field validation failed FailedMacValidation, /// Core module error wrapper CoreFault(core::Error), /// Invalid Kdf depth value InvalidKdfDepth(String), } impl From<core::Error> for Error { fn from(err: core::Error) -> Self { Error::CoreFault(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::UnsupportedCipher(ref str) => write!(f, "Unsupported cipher: {}", str), Error::UnsupportedKdf(ref str) => { write!(f, "Unsupported key derivation function: {}", str) } Error::UnsupportedPrf(ref str) => { write!(f, "Unsupported pseudo-random function: {}", str) } Error::FailedMacValidation => write!(f, "Message authentication code failed"), Error::CoreFault(ref err) => f.write_str(&err.to_string()), Error::InvalidKdfDepth(ref str) => write!(f, "Invalid security level: {}", str), } } } impl error::Error for Error { fn description(&self) -> &str { "Keystore file error" } fn cause(&self) -> Option<&error::Error> { match *self { Error::CoreFault(ref err) => Some(err), _ => None, } } }
Error
identifier_name
error.rs
//! # Keystore files (UTC / JSON) module errors use super::core; use std::{error, fmt}; /// Keystore file errors #[derive(Debug)] pub enum Error { /// An unsupported cipher UnsupportedCipher(String), /// An unsupported key derivation function UnsupportedKdf(String), /// An unsupported pseudo-random function UnsupportedPrf(String), /// `keccak256_mac` field validation failed FailedMacValidation, /// Core module error wrapper CoreFault(core::Error), /// Invalid Kdf depth value InvalidKdfDepth(String), }
impl From<core::Error> for Error { fn from(err: core::Error) -> Self { Error::CoreFault(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::UnsupportedCipher(ref str) => write!(f, "Unsupported cipher: {}", str), Error::UnsupportedKdf(ref str) => { write!(f, "Unsupported key derivation function: {}", str) } Error::UnsupportedPrf(ref str) => { write!(f, "Unsupported pseudo-random function: {}", str) } Error::FailedMacValidation => write!(f, "Message authentication code failed"), Error::CoreFault(ref err) => f.write_str(&err.to_string()), Error::InvalidKdfDepth(ref str) => write!(f, "Invalid security level: {}", str), } } } impl error::Error for Error { fn description(&self) -> &str { "Keystore file error" } fn cause(&self) -> Option<&error::Error> { match *self { Error::CoreFault(ref err) => Some(err), _ => None, } } }
random_line_split
free.rs
//! Free functions that create iterator adaptors or call iterator methods. //! //! The benefit of free functions is that they accept any `IntoIterator` as //! argument, so the resulting code may be easier to read. use std::fmt::Display; use std::iter::{self, Zip}; use Itertools; pub use adaptors::{ interleave, merge, put_back, put_back_n, }; pub use adaptors::multipeek::multipeek; pub use kmerge_impl::kmerge; pub use zip_eq_impl::zip_eq; pub use rciter_impl::rciter; /// Iterate `iterable` with a running index. /// /// `IntoIterator` enabled version of `.enumerate()`. /// /// ``` /// use itertools::enumerate; /// /// for (i, elt) in enumerate(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter> where I: IntoIterator { iterable.into_iter().enumerate() } /// Iterate `iterable` in reverse. /// /// `IntoIterator` enabled version of `.rev()`. /// /// ``` /// use itertools::rev; /// /// for elt in rev(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn rev<I>(iterable: I) -> iter::Rev<I::IntoIter> where I: IntoIterator, I::IntoIter: DoubleEndedIterator { iterable.into_iter().rev() } /// Iterate `i` and `j` in lock step. /// /// `IntoIterator` enabled version of `i.zip(j)`. /// /// ``` /// use itertools::zip; /// /// let data = [1, 2, 3, 4, 5]; /// for (a, b) in zip(&data, &data[1..]) { /// /* loop body */ /// } /// ``` pub fn
<I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter> where I: IntoIterator, J: IntoIterator { i.into_iter().zip(j) } /// Create an iterator that first iterates `i` and then `j`. /// /// `IntoIterator` enabled version of `i.chain(j)`. /// /// ``` /// use itertools::chain; /// /// for elt in chain(&[1, 2, 3], &[4]) { /// /* loop body */ /// } /// ``` pub fn chain<I, J>(i: I, j: J) -> iter::Chain<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter> where I: IntoIterator, J: IntoIterator<Item = I::Item> { i.into_iter().chain(j) } /// Create an iterator that clones each element from &T to T /// /// `IntoIterator` enabled version of `i.cloned()`. /// /// ``` /// use itertools::cloned; /// /// assert_eq!(cloned(b"abc").next(), Some(b'a')); /// ``` pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned<I::IntoIter> where I: IntoIterator<Item=&'a T>, T: Clone, { iterable.into_iter().cloned() } /// Perform a fold operation over the iterable. /// /// `IntoIterator` enabled version of `i.fold(init, f)` /// /// ``` /// use itertools::fold; /// /// assert_eq!(fold(&[1., 2., 3.], 0., |a, &b| f32::max(a, b)), 3.); /// ``` pub fn fold<I, B, F>(iterable: I, init: B, f: F) -> B where I: IntoIterator, F: FnMut(B, I::Item) -> B { iterable.into_iter().fold(init, f) } /// Test whether the predicate holds for all elements in the iterable. /// /// `IntoIterator` enabled version of `i.all(f)` /// /// ``` /// use itertools::all; /// /// assert!(all(&[1, 2, 3], |elt| *elt > 0)); /// ``` pub fn all<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().all(f) } /// Test whether the predicate holds for any elements in the iterable. /// /// `IntoIterator` enabled version of `i.any(f)` /// /// ``` /// use itertools::any; /// /// assert!(any(&[0, -1, 2], |elt| *elt > 0)); /// ``` pub fn any<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().any(f) } /// Return the maximum value of the iterable. /// /// `IntoIterator` enabled version of `i.max()`. /// /// ``` /// use itertools::max; /// /// assert_eq!(max(0..10), Some(9)); /// ``` pub fn max<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().max() } /// Return the minimum value of the iterable. /// /// `IntoIterator` enabled version of `i.min()`. /// /// ``` /// use itertools::min; /// /// assert_eq!(min(0..10), Some(0)); /// ``` pub fn min<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().min() } /// Combine all iterator elements into one String, seperated by `sep`. /// /// `IntoIterator` enabled version of `iterable.join(sep)`. /// /// ``` /// use itertools::join; /// /// assert_eq!(join(&[1, 2, 3], ", "), "1, 2, 3"); /// ``` pub fn join<I>(iterable: I, sep: &str) -> String where I: IntoIterator, I::Item: Display { iterable.into_iter().join(sep) } /// Collect all the iterable's elements into a sorted vector in ascending order. /// /// `IntoIterator` enabled version of `iterable.sorted()`. /// /// ``` /// use itertools::sorted; /// use itertools::assert_equal; /// /// assert_equal(sorted("rust".chars()), "rstu".chars()); /// ``` pub fn sorted<I>(iterable: I) -> Vec<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().sorted() }
zip
identifier_name
free.rs
//! Free functions that create iterator adaptors or call iterator methods. //! //! The benefit of free functions is that they accept any `IntoIterator` as //! argument, so the resulting code may be easier to read. use std::fmt::Display; use std::iter::{self, Zip}; use Itertools; pub use adaptors::{ interleave, merge, put_back, put_back_n, }; pub use adaptors::multipeek::multipeek; pub use kmerge_impl::kmerge; pub use zip_eq_impl::zip_eq; pub use rciter_impl::rciter;
/// `IntoIterator` enabled version of `.enumerate()`. /// /// ``` /// use itertools::enumerate; /// /// for (i, elt) in enumerate(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter> where I: IntoIterator { iterable.into_iter().enumerate() } /// Iterate `iterable` in reverse. /// /// `IntoIterator` enabled version of `.rev()`. /// /// ``` /// use itertools::rev; /// /// for elt in rev(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn rev<I>(iterable: I) -> iter::Rev<I::IntoIter> where I: IntoIterator, I::IntoIter: DoubleEndedIterator { iterable.into_iter().rev() } /// Iterate `i` and `j` in lock step. /// /// `IntoIterator` enabled version of `i.zip(j)`. /// /// ``` /// use itertools::zip; /// /// let data = [1, 2, 3, 4, 5]; /// for (a, b) in zip(&data, &data[1..]) { /// /* loop body */ /// } /// ``` pub fn zip<I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter> where I: IntoIterator, J: IntoIterator { i.into_iter().zip(j) } /// Create an iterator that first iterates `i` and then `j`. /// /// `IntoIterator` enabled version of `i.chain(j)`. /// /// ``` /// use itertools::chain; /// /// for elt in chain(&[1, 2, 3], &[4]) { /// /* loop body */ /// } /// ``` pub fn chain<I, J>(i: I, j: J) -> iter::Chain<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter> where I: IntoIterator, J: IntoIterator<Item = I::Item> { i.into_iter().chain(j) } /// Create an iterator that clones each element from &T to T /// /// `IntoIterator` enabled version of `i.cloned()`. /// /// ``` /// use itertools::cloned; /// /// assert_eq!(cloned(b"abc").next(), Some(b'a')); /// ``` pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned<I::IntoIter> where I: IntoIterator<Item=&'a T>, T: Clone, { iterable.into_iter().cloned() } /// Perform a fold operation over the iterable. /// /// `IntoIterator` enabled version of `i.fold(init, f)` /// /// ``` /// use itertools::fold; /// /// assert_eq!(fold(&[1., 2., 3.], 0., |a, &b| f32::max(a, b)), 3.); /// ``` pub fn fold<I, B, F>(iterable: I, init: B, f: F) -> B where I: IntoIterator, F: FnMut(B, I::Item) -> B { iterable.into_iter().fold(init, f) } /// Test whether the predicate holds for all elements in the iterable. /// /// `IntoIterator` enabled version of `i.all(f)` /// /// ``` /// use itertools::all; /// /// assert!(all(&[1, 2, 3], |elt| *elt > 0)); /// ``` pub fn all<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().all(f) } /// Test whether the predicate holds for any elements in the iterable. /// /// `IntoIterator` enabled version of `i.any(f)` /// /// ``` /// use itertools::any; /// /// assert!(any(&[0, -1, 2], |elt| *elt > 0)); /// ``` pub fn any<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().any(f) } /// Return the maximum value of the iterable. /// /// `IntoIterator` enabled version of `i.max()`. /// /// ``` /// use itertools::max; /// /// assert_eq!(max(0..10), Some(9)); /// ``` pub fn max<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().max() } /// Return the minimum value of the iterable. /// /// `IntoIterator` enabled version of `i.min()`. /// /// ``` /// use itertools::min; /// /// assert_eq!(min(0..10), Some(0)); /// ``` pub fn min<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().min() } /// Combine all iterator elements into one String, seperated by `sep`. /// /// `IntoIterator` enabled version of `iterable.join(sep)`. /// /// ``` /// use itertools::join; /// /// assert_eq!(join(&[1, 2, 3], ", "), "1, 2, 3"); /// ``` pub fn join<I>(iterable: I, sep: &str) -> String where I: IntoIterator, I::Item: Display { iterable.into_iter().join(sep) } /// Collect all the iterable's elements into a sorted vector in ascending order. /// /// `IntoIterator` enabled version of `iterable.sorted()`. /// /// ``` /// use itertools::sorted; /// use itertools::assert_equal; /// /// assert_equal(sorted("rust".chars()), "rstu".chars()); /// ``` pub fn sorted<I>(iterable: I) -> Vec<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().sorted() }
/// Iterate `iterable` with a running index. ///
random_line_split
free.rs
//! Free functions that create iterator adaptors or call iterator methods. //! //! The benefit of free functions is that they accept any `IntoIterator` as //! argument, so the resulting code may be easier to read. use std::fmt::Display; use std::iter::{self, Zip}; use Itertools; pub use adaptors::{ interleave, merge, put_back, put_back_n, }; pub use adaptors::multipeek::multipeek; pub use kmerge_impl::kmerge; pub use zip_eq_impl::zip_eq; pub use rciter_impl::rciter; /// Iterate `iterable` with a running index. /// /// `IntoIterator` enabled version of `.enumerate()`. /// /// ``` /// use itertools::enumerate; /// /// for (i, elt) in enumerate(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter> where I: IntoIterator { iterable.into_iter().enumerate() } /// Iterate `iterable` in reverse. /// /// `IntoIterator` enabled version of `.rev()`. /// /// ``` /// use itertools::rev; /// /// for elt in rev(&[1, 2, 3]) { /// /* loop body */ /// } /// ``` pub fn rev<I>(iterable: I) -> iter::Rev<I::IntoIter> where I: IntoIterator, I::IntoIter: DoubleEndedIterator { iterable.into_iter().rev() } /// Iterate `i` and `j` in lock step. /// /// `IntoIterator` enabled version of `i.zip(j)`. /// /// ``` /// use itertools::zip; /// /// let data = [1, 2, 3, 4, 5]; /// for (a, b) in zip(&data, &data[1..]) { /// /* loop body */ /// } /// ``` pub fn zip<I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter> where I: IntoIterator, J: IntoIterator { i.into_iter().zip(j) } /// Create an iterator that first iterates `i` and then `j`. /// /// `IntoIterator` enabled version of `i.chain(j)`. /// /// ``` /// use itertools::chain; /// /// for elt in chain(&[1, 2, 3], &[4]) { /// /* loop body */ /// } /// ``` pub fn chain<I, J>(i: I, j: J) -> iter::Chain<<I as IntoIterator>::IntoIter, <J as IntoIterator>::IntoIter> where I: IntoIterator, J: IntoIterator<Item = I::Item>
/// Create an iterator that clones each element from &T to T /// /// `IntoIterator` enabled version of `i.cloned()`. /// /// ``` /// use itertools::cloned; /// /// assert_eq!(cloned(b"abc").next(), Some(b'a')); /// ``` pub fn cloned<'a, I, T: 'a>(iterable: I) -> iter::Cloned<I::IntoIter> where I: IntoIterator<Item=&'a T>, T: Clone, { iterable.into_iter().cloned() } /// Perform a fold operation over the iterable. /// /// `IntoIterator` enabled version of `i.fold(init, f)` /// /// ``` /// use itertools::fold; /// /// assert_eq!(fold(&[1., 2., 3.], 0., |a, &b| f32::max(a, b)), 3.); /// ``` pub fn fold<I, B, F>(iterable: I, init: B, f: F) -> B where I: IntoIterator, F: FnMut(B, I::Item) -> B { iterable.into_iter().fold(init, f) } /// Test whether the predicate holds for all elements in the iterable. /// /// `IntoIterator` enabled version of `i.all(f)` /// /// ``` /// use itertools::all; /// /// assert!(all(&[1, 2, 3], |elt| *elt > 0)); /// ``` pub fn all<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().all(f) } /// Test whether the predicate holds for any elements in the iterable. /// /// `IntoIterator` enabled version of `i.any(f)` /// /// ``` /// use itertools::any; /// /// assert!(any(&[0, -1, 2], |elt| *elt > 0)); /// ``` pub fn any<I, F>(iterable: I, f: F) -> bool where I: IntoIterator, F: FnMut(I::Item) -> bool { iterable.into_iter().any(f) } /// Return the maximum value of the iterable. /// /// `IntoIterator` enabled version of `i.max()`. /// /// ``` /// use itertools::max; /// /// assert_eq!(max(0..10), Some(9)); /// ``` pub fn max<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().max() } /// Return the minimum value of the iterable. /// /// `IntoIterator` enabled version of `i.min()`. /// /// ``` /// use itertools::min; /// /// assert_eq!(min(0..10), Some(0)); /// ``` pub fn min<I>(iterable: I) -> Option<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().min() } /// Combine all iterator elements into one String, seperated by `sep`. /// /// `IntoIterator` enabled version of `iterable.join(sep)`. /// /// ``` /// use itertools::join; /// /// assert_eq!(join(&[1, 2, 3], ", "), "1, 2, 3"); /// ``` pub fn join<I>(iterable: I, sep: &str) -> String where I: IntoIterator, I::Item: Display { iterable.into_iter().join(sep) } /// Collect all the iterable's elements into a sorted vector in ascending order. /// /// `IntoIterator` enabled version of `iterable.sorted()`. /// /// ``` /// use itertools::sorted; /// use itertools::assert_equal; /// /// assert_equal(sorted("rust".chars()), "rstu".chars()); /// ``` pub fn sorted<I>(iterable: I) -> Vec<I::Item> where I: IntoIterator, I::Item: Ord { iterable.into_iter().sorted() }
{ i.into_iter().chain(j) }
identifier_body
dbscan.rs
use rm::linalg::Matrix;
#[test] fn test_basic_clusters() { let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.train(&inputs); let clustering = model.clusters().unwrap(); assert!(clustering.data().iter().take(4).all(|x| *x == Some(0))); assert!(clustering.data().iter().skip(4).all(|x| *x == Some(1))); } #[test] fn test_basic_prediction() { let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.set_predictive(true); model.train(&inputs); let new_points = Matrix::new(2,2, vec![1.0, 2.0, 4.0, 4.0]); let classes = model.predict(&new_points); assert!(classes[0] == Some(0)); assert!(classes[1] == None); }
use rm::learning::dbscan::DBSCAN; use rm::learning::UnSupModel;
random_line_split
dbscan.rs
use rm::linalg::Matrix; use rm::learning::dbscan::DBSCAN; use rm::learning::UnSupModel; #[test] fn test_basic_clusters()
#[test] fn test_basic_prediction() { let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.set_predictive(true); model.train(&inputs); let new_points = Matrix::new(2,2, vec![1.0, 2.0, 4.0, 4.0]); let classes = model.predict(&new_points); assert!(classes[0] == Some(0)); assert!(classes[1] == None); }
{ let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.train(&inputs); let clustering = model.clusters().unwrap(); assert!(clustering.data().iter().take(4).all(|x| *x == Some(0))); assert!(clustering.data().iter().skip(4).all(|x| *x == Some(1))); }
identifier_body
dbscan.rs
use rm::linalg::Matrix; use rm::learning::dbscan::DBSCAN; use rm::learning::UnSupModel; #[test] fn
() { let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.train(&inputs); let clustering = model.clusters().unwrap(); assert!(clustering.data().iter().take(4).all(|x| *x == Some(0))); assert!(clustering.data().iter().skip(4).all(|x| *x == Some(1))); } #[test] fn test_basic_prediction() { let inputs = Matrix::new(6, 2, vec![1.0, 2.0, 1.1, 2.2, 0.9, 1.9, 1.0, 2.1, -2.0, 3.0, -2.2, 3.1]); let mut model = DBSCAN::new(0.5, 2); model.set_predictive(true); model.train(&inputs); let new_points = Matrix::new(2,2, vec![1.0, 2.0, 4.0, 4.0]); let classes = model.predict(&new_points); assert!(classes[0] == Some(0)); assert!(classes[1] == None); }
test_basic_clusters
identifier_name
mod.rs
// that the user can type inference_context.tcx.sess.span_bug( span, &format!("coherence encountered unexpected type searching for base type: {}", ty.repr(inference_context.tcx))[]); } } } struct CoherenceChecker<'a, 'tcx: 'a> { crate_context: &'a CrateCtxt<'a, 'tcx>, inference_context: InferCtxt<'a, 'tcx>, inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>, } struct CoherenceCheckVisitor<'a, 'tcx: 'a> { cc: &'a CoherenceChecker<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &Item) { //debug!("(checking coherence) item '{}'", token::get_ident(item.ident)); match item.node { ItemImpl(_, _, _, ref opt_trait, _, _) => { match opt_trait.clone() { Some(opt_trait) => { self.cc.check_implementation(item, &[opt_trait]); } None => self.cc.check_implementation(item, &[]) } } _ => { // Nothing to do. } }; visit::walk_item(self, item); } } impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { fn check(&self, krate: &Crate) { // Check implementations and traits. This populates the tables // containing the inherent methods and extension methods. It also // builds up the trait inheritance table. let mut visitor = CoherenceCheckVisitor { cc: self }; visit::walk_crate(&mut visitor, krate); // Copy over the inherent impls we gathered up during the walk into // the tcx. let mut tcx_inherent_impls = self.crate_context.tcx.inherent_impls.borrow_mut(); for (k, v) in &*self.inherent_impls.borrow() { tcx_inherent_impls.insert((*k).clone(), Rc::new((*v.borrow()).clone())); } // Bring in external crates. It's fine for this to happen after the // coherence checks, because we ensure by construction that no errors // can happen at link time. self.add_external_crates(); // Populate the table of destructors. It might seem a bit strange to // do this here, but it's actually the most convenient place, since // the coherence tables contain the trait -> type mappings. self.populate_destructor_table(); // Check to make sure implementations of `Copy` are legal. self.check_implementations_of_copy(); } fn check_implementation(&self, item: &Item, associated_traits: &[TraitRef]) { let tcx = self.crate_context.tcx; let impl_did = local_def(item.id); let self_type = ty::lookup_item_type(tcx, impl_did); // If there are no traits, then this implementation must have a // base type. let impl_items = self.create_impl_from_item(item); for associated_trait in associated_traits { let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx, associated_trait.ref_id); debug!("(checking implementation) adding impl for trait '{}', item '{}'", trait_ref.repr(self.crate_context.tcx), token::get_ident(item.ident)); enforce_trait_manually_implementable(self.crate_context.tcx, item.span, trait_ref.def_id); self.add_trait_impl(trait_ref.def_id, impl_did); } // Add the implementation to the mapping from implementation to base // type def ID, if there is a base type for this implementation and // the implementation does not have any associated traits. match get_base_type_def_id(&self.inference_context, item.span, self_type.ty) { None => { // Nothing to do. } Some(base_type_def_id) => { // FIXME: Gather up default methods? if associated_traits.len() == 0 { self.add_inherent_impl(base_type_def_id, impl_did); } } } tcx.impl_items.borrow_mut().insert(impl_did, impl_items); } // Creates default method IDs and performs type substitutions for an impl // and trait pair. Then, for each provided method in the trait, inserts a // `ProvidedMethodInfo` instance into the `provided_method_sources` map. fn instantiate_default_methods( &self, impl_id: DefId, trait_ref: &ty::TraitRef<'tcx>, all_impl_items: &mut Vec<ImplOrTraitItemId>) { let tcx = self.crate_context.tcx; debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})", impl_id, trait_ref.repr(tcx)); let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); let prov = ty::provided_trait_methods(tcx, trait_ref.def_id); for trait_method in &prov { // Synthesize an ID. let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx)); // Create substitutions for the various trait parameters. let new_method_ty = Rc::new(subst_receiver_types_in_method_ty( tcx, impl_id, &impl_type_scheme, trait_ref, new_did, &**trait_method, Some(trait_method.def_id))); debug!("new_method_ty={}", new_method_ty.repr(tcx)); all_impl_items.push(MethodTraitItemId(new_did)); // construct the polytype for the method based on the // method_ty. it will have all the generics from the // impl, plus its own. let new_polytype = ty::TypeScheme { generics: new_method_ty.generics.clone(), ty: ty::mk_bare_fn(tcx, Some(new_did), tcx.mk_bare_fn(new_method_ty.fty.clone())) }; debug!("new_polytype={}", new_polytype.repr(tcx)); tcx.tcache.borrow_mut().insert(new_did, new_polytype); tcx.impl_or_trait_items .borrow_mut() .insert(new_did, ty::MethodTraitItem(new_method_ty)); // Pair the new synthesized ID up with the // ID of the method. self.crate_context.tcx.provided_method_sources.borrow_mut() .insert(new_did, trait_method.def_id); } } fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) { match self.inherent_impls.borrow().get(&base_def_id) { Some(implementation_list) => { implementation_list.borrow_mut().push(impl_def_id); return; } None => {} } self.inherent_impls.borrow_mut().insert( base_def_id, Rc::new(RefCell::new(vec!(impl_def_id)))); } fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId)
fn get_self_type_for_implementation(&self, impl_did: DefId) -> TypeScheme<'tcx> { self.crate_context.tcx.tcache.borrow()[impl_did].clone() } // Converts an implementation in the AST to a vector of items. fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> { match item.node { ItemImpl(_, _, _, ref trait_refs, _, ref ast_items) => { let mut items: Vec<ImplOrTraitItemId> = ast_items.iter() .map(|ast_item| { match *ast_item { ast::MethodImplItem(ref ast_method) => { MethodTraitItemId( local_def(ast_method.id)) } ast::TypeImplItem(ref typedef) => { TypeTraitItemId(local_def(typedef.id)) } } }).collect(); if let Some(ref trait_ref) = *trait_refs { let ty_trait_ref = ty::node_id_to_trait_ref( self.crate_context.tcx, trait_ref.ref_id); self.instantiate_default_methods(local_def(item.id), &*ty_trait_ref, &mut items); } items } _ => { self.crate_context.tcx.sess.span_bug(item.span, "can't convert a non-impl to an impl"); } } } // External crate handling fn add_external_impl(&self, impls_seen: &mut HashSet<DefId>, impl_def_id: DefId) { let tcx = self.crate_context.tcx; let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id); // Make sure we don't visit the same implementation multiple times. if!impls_seen.insert(impl_def_id) { // Skip this one. return } // Good. Continue. let _ = lookup_item_type(tcx, impl_def_id); let associated_traits = get_impl_trait(tcx, impl_def_id); // Do a sanity check. assert!(associated_traits.is_some()); // Record all the trait items. if let Some(trait_ref) = associated_traits { self.add_trait_impl(trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for item_def_id in &impl_items { let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id()); match impl_item { ty::MethodTraitItem(ref method) => { if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(item_def_id.def_id(), source); } } ty::TypeTraitItem(_) => {} } } tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items); } // Adds implementations and traits from external crates to the coherence // info. fn add_external_crates(&self) { let mut impls_seen = HashSet::new(); let crate_store = &self.crate_context.tcx.sess.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_impl(crate_store, crate_number, |def_id| { assert_eq!(crate_number, def_id.krate); self.add_external_impl(&mut impls_seen, def_id) }) }) } // // Destructors // fn populate_destructor_table(&self) { let tcx = self.crate_context.tcx; let drop_trait = match tcx.lang_items.drop_trait() { Some(id) => id, None => { return } }; let impl_items = tcx.impl_items.borrow(); let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() { None => return, // No types with (new-style) dtors present. Some(found_impls) => found_impls }; for &impl_did in &*trait_impls.borrow() { let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; } let method_def_id = items[0]; let self_type = self.get_self_type_for_implementation(impl_did); match self_type.ty.sty { ty::ty_enum(type_def_id, _) | ty::ty_struct(type_def_id, _) | ty::ty_closure(type_def_id, _, _) => { tcx.destructor_for_type .borrow_mut() .insert(type_def_id, method_def_id.def_id()); tcx.destructors .borrow_mut() .insert(method_def_id.def_id()); } _ => { // Destructors only work on nominal types. if impl_did.krate == ast::LOCAL_CRATE { { match tcx.map.find(impl_did.node) { Some(ast_map::NodeItem(item)) => { span_err!(tcx.sess, item.span, E0120, "the Drop trait may only be implemented on structures"); } _ => { tcx.sess.bug("didn't find impl in ast \ map"); } } } } else { tcx.sess.bug("found external impl of Drop trait on \ something other than a struct"); } } } } } /// Ensures that implementations of the built-in trait `Copy` are legal. fn check_implementations_of_copy(&self) { let tcx = self.crate_context.tcx; let copy_trait = match tcx.lang_items.copy_trait() { Some(id) => id, None => return, }; let trait_impls = match tcx.trait_impls .borrow() .get(&copy_trait) .cloned() { None => { debug!("check_implementations_of_copy(): no types with \ implementations of `Copy` found"); return } Some(found_impls) => found_impls }; // Clone first to avoid a double borrow error. let trait_impls = trait_impls.borrow().clone(); for &impl_did in &trait_impls { debug!("check_implementations_of_copy: impl_did={}", impl_did.repr(tcx)); if impl_did.krate!= ast::LOCAL_CRATE { debug!("check_implementations_of_copy(): impl not in this \ crate"); continue
{ debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}", base_def_id, impl_def_id); ty::record_trait_implementation(self.crate_context.tcx, base_def_id, impl_def_id); }
identifier_body
mod.rs
// that the user can type inference_context.tcx.sess.span_bug( span, &format!("coherence encountered unexpected type searching for base type: {}", ty.repr(inference_context.tcx))[]); } } } struct
<'a, 'tcx: 'a> { crate_context: &'a CrateCtxt<'a, 'tcx>, inference_context: InferCtxt<'a, 'tcx>, inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>, } struct CoherenceCheckVisitor<'a, 'tcx: 'a> { cc: &'a CoherenceChecker<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &Item) { //debug!("(checking coherence) item '{}'", token::get_ident(item.ident)); match item.node { ItemImpl(_, _, _, ref opt_trait, _, _) => { match opt_trait.clone() { Some(opt_trait) => { self.cc.check_implementation(item, &[opt_trait]); } None => self.cc.check_implementation(item, &[]) } } _ => { // Nothing to do. } }; visit::walk_item(self, item); } } impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { fn check(&self, krate: &Crate) { // Check implementations and traits. This populates the tables // containing the inherent methods and extension methods. It also // builds up the trait inheritance table. let mut visitor = CoherenceCheckVisitor { cc: self }; visit::walk_crate(&mut visitor, krate); // Copy over the inherent impls we gathered up during the walk into // the tcx. let mut tcx_inherent_impls = self.crate_context.tcx.inherent_impls.borrow_mut(); for (k, v) in &*self.inherent_impls.borrow() { tcx_inherent_impls.insert((*k).clone(), Rc::new((*v.borrow()).clone())); } // Bring in external crates. It's fine for this to happen after the // coherence checks, because we ensure by construction that no errors // can happen at link time. self.add_external_crates(); // Populate the table of destructors. It might seem a bit strange to // do this here, but it's actually the most convenient place, since // the coherence tables contain the trait -> type mappings. self.populate_destructor_table(); // Check to make sure implementations of `Copy` are legal. self.check_implementations_of_copy(); } fn check_implementation(&self, item: &Item, associated_traits: &[TraitRef]) { let tcx = self.crate_context.tcx; let impl_did = local_def(item.id); let self_type = ty::lookup_item_type(tcx, impl_did); // If there are no traits, then this implementation must have a // base type. let impl_items = self.create_impl_from_item(item); for associated_trait in associated_traits { let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx, associated_trait.ref_id); debug!("(checking implementation) adding impl for trait '{}', item '{}'", trait_ref.repr(self.crate_context.tcx), token::get_ident(item.ident)); enforce_trait_manually_implementable(self.crate_context.tcx, item.span, trait_ref.def_id); self.add_trait_impl(trait_ref.def_id, impl_did); } // Add the implementation to the mapping from implementation to base // type def ID, if there is a base type for this implementation and // the implementation does not have any associated traits. match get_base_type_def_id(&self.inference_context, item.span, self_type.ty) { None => { // Nothing to do. } Some(base_type_def_id) => { // FIXME: Gather up default methods? if associated_traits.len() == 0 { self.add_inherent_impl(base_type_def_id, impl_did); } } } tcx.impl_items.borrow_mut().insert(impl_did, impl_items); } // Creates default method IDs and performs type substitutions for an impl // and trait pair. Then, for each provided method in the trait, inserts a // `ProvidedMethodInfo` instance into the `provided_method_sources` map. fn instantiate_default_methods( &self, impl_id: DefId, trait_ref: &ty::TraitRef<'tcx>, all_impl_items: &mut Vec<ImplOrTraitItemId>) { let tcx = self.crate_context.tcx; debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})", impl_id, trait_ref.repr(tcx)); let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); let prov = ty::provided_trait_methods(tcx, trait_ref.def_id); for trait_method in &prov { // Synthesize an ID. let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx)); // Create substitutions for the various trait parameters. let new_method_ty = Rc::new(subst_receiver_types_in_method_ty( tcx, impl_id, &impl_type_scheme, trait_ref, new_did, &**trait_method, Some(trait_method.def_id))); debug!("new_method_ty={}", new_method_ty.repr(tcx)); all_impl_items.push(MethodTraitItemId(new_did)); // construct the polytype for the method based on the // method_ty. it will have all the generics from the // impl, plus its own. let new_polytype = ty::TypeScheme { generics: new_method_ty.generics.clone(), ty: ty::mk_bare_fn(tcx, Some(new_did), tcx.mk_bare_fn(new_method_ty.fty.clone())) }; debug!("new_polytype={}", new_polytype.repr(tcx)); tcx.tcache.borrow_mut().insert(new_did, new_polytype); tcx.impl_or_trait_items .borrow_mut() .insert(new_did, ty::MethodTraitItem(new_method_ty)); // Pair the new synthesized ID up with the // ID of the method. self.crate_context.tcx.provided_method_sources.borrow_mut() .insert(new_did, trait_method.def_id); } } fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) { match self.inherent_impls.borrow().get(&base_def_id) { Some(implementation_list) => { implementation_list.borrow_mut().push(impl_def_id); return; } None => {} } self.inherent_impls.borrow_mut().insert( base_def_id, Rc::new(RefCell::new(vec!(impl_def_id)))); } fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) { debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}", base_def_id, impl_def_id); ty::record_trait_implementation(self.crate_context.tcx, base_def_id, impl_def_id); } fn get_self_type_for_implementation(&self, impl_did: DefId) -> TypeScheme<'tcx> { self.crate_context.tcx.tcache.borrow()[impl_did].clone() } // Converts an implementation in the AST to a vector of items. fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> { match item.node { ItemImpl(_, _, _, ref trait_refs, _, ref ast_items) => { let mut items: Vec<ImplOrTraitItemId> = ast_items.iter() .map(|ast_item| { match *ast_item { ast::MethodImplItem(ref ast_method) => { MethodTraitItemId( local_def(ast_method.id)) } ast::TypeImplItem(ref typedef) => { TypeTraitItemId(local_def(typedef.id)) } } }).collect(); if let Some(ref trait_ref) = *trait_refs { let ty_trait_ref = ty::node_id_to_trait_ref( self.crate_context.tcx, trait_ref.ref_id); self.instantiate_default_methods(local_def(item.id), &*ty_trait_ref, &mut items); } items } _ => { self.crate_context.tcx.sess.span_bug(item.span, "can't convert a non-impl to an impl"); } } } // External crate handling fn add_external_impl(&self, impls_seen: &mut HashSet<DefId>, impl_def_id: DefId) { let tcx = self.crate_context.tcx; let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id); // Make sure we don't visit the same implementation multiple times. if!impls_seen.insert(impl_def_id) { // Skip this one. return } // Good. Continue. let _ = lookup_item_type(tcx, impl_def_id); let associated_traits = get_impl_trait(tcx, impl_def_id); // Do a sanity check. assert!(associated_traits.is_some()); // Record all the trait items. if let Some(trait_ref) = associated_traits { self.add_trait_impl(trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for item_def_id in &impl_items { let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id()); match impl_item { ty::MethodTraitItem(ref method) => { if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(item_def_id.def_id(), source); } } ty::TypeTraitItem(_) => {} } } tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items); } // Adds implementations and traits from external crates to the coherence // info. fn add_external_crates(&self) { let mut impls_seen = HashSet::new(); let crate_store = &self.crate_context.tcx.sess.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_impl(crate_store, crate_number, |def_id| { assert_eq!(crate_number, def_id.krate); self.add_external_impl(&mut impls_seen, def_id) }) }) } // // Destructors // fn populate_destructor_table(&self) { let tcx = self.crate_context.tcx; let drop_trait = match tcx.lang_items.drop_trait() { Some(id) => id, None => { return } }; let impl_items = tcx.impl_items.borrow(); let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() { None => return, // No types with (new-style) dtors present. Some(found_impls) => found_impls }; for &impl_did in &*trait_impls.borrow() { let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; } let method_def_id = items[0]; let self_type = self.get_self_type_for_implementation(impl_did); match self_type.ty.sty { ty::ty_enum(type_def_id, _) | ty::ty_struct(type_def_id, _) | ty::ty_closure(type_def_id, _, _) => { tcx.destructor_for_type .borrow_mut() .insert(type_def_id, method_def_id.def_id()); tcx.destructors .borrow_mut() .insert(method_def_id.def_id()); } _ => { // Destructors only work on nominal types. if impl_did.krate == ast::LOCAL_CRATE { { match tcx.map.find(impl_did.node) { Some(ast_map::NodeItem(item)) => { span_err!(tcx.sess, item.span, E0120, "the Drop trait may only be implemented on structures"); } _ => { tcx.sess.bug("didn't find impl in ast \ map"); } } } } else { tcx.sess.bug("found external impl of Drop trait on \ something other than a struct"); } } } } } /// Ensures that implementations of the built-in trait `Copy` are legal. fn check_implementations_of_copy(&self) { let tcx = self.crate_context.tcx; let copy_trait = match tcx.lang_items.copy_trait() { Some(id) => id, None => return, }; let trait_impls = match tcx.trait_impls .borrow() .get(&copy_trait) .cloned() { None => { debug!("check_implementations_of_copy(): no types with \ implementations of `Copy` found"); return } Some(found_impls) => found_impls }; // Clone first to avoid a double borrow error. let trait_impls = trait_impls.borrow().clone(); for &impl_did in &trait_impls { debug!("check_implementations_of_copy: impl_did={}", impl_did.repr(tcx)); if impl_did.krate!= ast::LOCAL_CRATE { debug!("check_implementations_of_copy(): impl not in this \ crate"); continue
CoherenceChecker
identifier_name
mod.rs
ty_infer(..) | ty_closure(..) => { // `ty` comes from a user declaration so we should only expect types // that the user can type inference_context.tcx.sess.span_bug( span, &format!("coherence encountered unexpected type searching for base type: {}", ty.repr(inference_context.tcx))[]); } } } struct CoherenceChecker<'a, 'tcx: 'a> { crate_context: &'a CrateCtxt<'a, 'tcx>, inference_context: InferCtxt<'a, 'tcx>, inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>, } struct CoherenceCheckVisitor<'a, 'tcx: 'a> { cc: &'a CoherenceChecker<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &Item) { //debug!("(checking coherence) item '{}'", token::get_ident(item.ident)); match item.node { ItemImpl(_, _, _, ref opt_trait, _, _) => { match opt_trait.clone() { Some(opt_trait) => { self.cc.check_implementation(item, &[opt_trait]); } None => self.cc.check_implementation(item, &[]) } } _ => { // Nothing to do. } }; visit::walk_item(self, item); } } impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { fn check(&self, krate: &Crate) { // Check implementations and traits. This populates the tables // containing the inherent methods and extension methods. It also // builds up the trait inheritance table. let mut visitor = CoherenceCheckVisitor { cc: self }; visit::walk_crate(&mut visitor, krate); // Copy over the inherent impls we gathered up during the walk into // the tcx. let mut tcx_inherent_impls = self.crate_context.tcx.inherent_impls.borrow_mut(); for (k, v) in &*self.inherent_impls.borrow() { tcx_inherent_impls.insert((*k).clone(), Rc::new((*v.borrow()).clone())); } // Bring in external crates. It's fine for this to happen after the // coherence checks, because we ensure by construction that no errors // can happen at link time. self.add_external_crates(); // Populate the table of destructors. It might seem a bit strange to // do this here, but it's actually the most convenient place, since // the coherence tables contain the trait -> type mappings. self.populate_destructor_table(); // Check to make sure implementations of `Copy` are legal. self.check_implementations_of_copy(); } fn check_implementation(&self, item: &Item, associated_traits: &[TraitRef]) { let tcx = self.crate_context.tcx; let impl_did = local_def(item.id); let self_type = ty::lookup_item_type(tcx, impl_did); // If there are no traits, then this implementation must have a // base type. let impl_items = self.create_impl_from_item(item); for associated_trait in associated_traits { let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx, associated_trait.ref_id); debug!("(checking implementation) adding impl for trait '{}', item '{}'", trait_ref.repr(self.crate_context.tcx), token::get_ident(item.ident)); enforce_trait_manually_implementable(self.crate_context.tcx, item.span, trait_ref.def_id); self.add_trait_impl(trait_ref.def_id, impl_did); } // Add the implementation to the mapping from implementation to base // type def ID, if there is a base type for this implementation and // the implementation does not have any associated traits. match get_base_type_def_id(&self.inference_context, item.span, self_type.ty) { None => { // Nothing to do. } Some(base_type_def_id) => { // FIXME: Gather up default methods? if associated_traits.len() == 0 { self.add_inherent_impl(base_type_def_id, impl_did); } } } tcx.impl_items.borrow_mut().insert(impl_did, impl_items); } // Creates default method IDs and performs type substitutions for an impl // and trait pair. Then, for each provided method in the trait, inserts a // `ProvidedMethodInfo` instance into the `provided_method_sources` map. fn instantiate_default_methods( &self, impl_id: DefId, trait_ref: &ty::TraitRef<'tcx>, all_impl_items: &mut Vec<ImplOrTraitItemId>) { let tcx = self.crate_context.tcx; debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})", impl_id, trait_ref.repr(tcx)); let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); let prov = ty::provided_trait_methods(tcx, trait_ref.def_id); for trait_method in &prov { // Synthesize an ID. let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx)); // Create substitutions for the various trait parameters. let new_method_ty = Rc::new(subst_receiver_types_in_method_ty( tcx, impl_id, &impl_type_scheme, trait_ref, new_did, &**trait_method, Some(trait_method.def_id))); debug!("new_method_ty={}", new_method_ty.repr(tcx)); all_impl_items.push(MethodTraitItemId(new_did)); // construct the polytype for the method based on the // method_ty. it will have all the generics from the // impl, plus its own. let new_polytype = ty::TypeScheme { generics: new_method_ty.generics.clone(), ty: ty::mk_bare_fn(tcx, Some(new_did), tcx.mk_bare_fn(new_method_ty.fty.clone())) }; debug!("new_polytype={}", new_polytype.repr(tcx)); tcx.tcache.borrow_mut().insert(new_did, new_polytype); tcx.impl_or_trait_items .borrow_mut() .insert(new_did, ty::MethodTraitItem(new_method_ty)); // Pair the new synthesized ID up with the // ID of the method. self.crate_context.tcx.provided_method_sources.borrow_mut() .insert(new_did, trait_method.def_id); } } fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) { match self.inherent_impls.borrow().get(&base_def_id) { Some(implementation_list) => { implementation_list.borrow_mut().push(impl_def_id); return; } None => {} } self.inherent_impls.borrow_mut().insert( base_def_id, Rc::new(RefCell::new(vec!(impl_def_id)))); } fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) { debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}", base_def_id, impl_def_id); ty::record_trait_implementation(self.crate_context.tcx, base_def_id, impl_def_id); } fn get_self_type_for_implementation(&self, impl_did: DefId) -> TypeScheme<'tcx> { self.crate_context.tcx.tcache.borrow()[impl_did].clone() } // Converts an implementation in the AST to a vector of items. fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> { match item.node { ItemImpl(_, _, _, ref trait_refs, _, ref ast_items) => { let mut items: Vec<ImplOrTraitItemId> = ast_items.iter() .map(|ast_item| { match *ast_item { ast::MethodImplItem(ref ast_method) => { MethodTraitItemId( local_def(ast_method.id)) } ast::TypeImplItem(ref typedef) => { TypeTraitItemId(local_def(typedef.id)) } } }).collect(); if let Some(ref trait_ref) = *trait_refs { let ty_trait_ref = ty::node_id_to_trait_ref( self.crate_context.tcx, trait_ref.ref_id); self.instantiate_default_methods(local_def(item.id), &*ty_trait_ref, &mut items); } items } _ => { self.crate_context.tcx.sess.span_bug(item.span, "can't convert a non-impl to an impl"); } } } // External crate handling fn add_external_impl(&self, impls_seen: &mut HashSet<DefId>, impl_def_id: DefId) { let tcx = self.crate_context.tcx; let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id); // Make sure we don't visit the same implementation multiple times. if!impls_seen.insert(impl_def_id) { // Skip this one. return } // Good. Continue. let _ = lookup_item_type(tcx, impl_def_id); let associated_traits = get_impl_trait(tcx, impl_def_id); // Do a sanity check. assert!(associated_traits.is_some()); // Record all the trait items. if let Some(trait_ref) = associated_traits { self.add_trait_impl(trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for item_def_id in &impl_items { let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id()); match impl_item { ty::MethodTraitItem(ref method) => { if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(item_def_id.def_id(), source); } } ty::TypeTraitItem(_) => {} } } tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items); } // Adds implementations and traits from external crates to the coherence // info. fn add_external_crates(&self) { let mut impls_seen = HashSet::new(); let crate_store = &self.crate_context.tcx.sess.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_impl(crate_store, crate_number, |def_id| { assert_eq!(crate_number, def_id.krate); self.add_external_impl(&mut impls_seen, def_id) }) }) } // // Destructors // fn populate_destructor_table(&self) { let tcx = self.crate_context.tcx; let drop_trait = match tcx.lang_items.drop_trait() { Some(id) => id, None => { return } }; let impl_items = tcx.impl_items.borrow(); let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() { None => return, // No types with (new-style) dtors present. Some(found_impls) => found_impls }; for &impl_did in &*trait_impls.borrow() { let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; } let method_def_id = items[0]; let self_type = self.get_self_type_for_implementation(impl_did); match self_type.ty.sty { ty::ty_enum(type_def_id, _) | ty::ty_struct(type_def_id, _) | ty::ty_closure(type_def_id, _, _) => { tcx.destructor_for_type .borrow_mut() .insert(type_def_id, method_def_id.def_id()); tcx.destructors .borrow_mut() .insert(method_def_id.def_id()); } _ => { // Destructors only work on nominal types. if impl_did.krate == ast::LOCAL_CRATE { { match tcx.map.find(impl_did.node) { Some(ast_map::NodeItem(item)) => { span_err!(tcx.sess, item.span, E0120, "the Drop trait may only be implemented on structures"); } _ => { tcx.sess.bug("didn't find impl in ast \ map"); } } } } else { tcx.sess.bug("found external impl of Drop trait on \ something other than a struct"); } } } } } /// Ensures that implementations of the built-in trait `Copy` are legal. fn check_implementations_of_copy(&self) { let tcx = self.crate_context.tcx; let copy_trait = match tcx.lang_items.copy_trait() { Some(id) => id, None => return, }; let trait_impls = match tcx.trait_impls .borrow() .get(&copy_trait) .cloned() { None => { debug!("check_implementations_of_copy(): no types with \ implementations of `Copy` found"); return } Some(found_impls) => found_impls }; // Clone first to avoid a double borrow error. let trait_impls = trait_impls.borrow().clone(); for &impl_did in &trait_impls { debug!("check_implementations_of_copy: impl_did={}", impl_did.repr(tcx)); if impl_did.krate!= ast::LOCAL_CRATE {
{ None }
conditional_block
mod.rs
match ty.sty { ty_enum(def_id, _) | ty_struct(def_id, _) => { Some(def_id) } ty_trait(ref t) => { Some(t.principal_def_id()) } ty_uniq(_) => { inference_context.tcx.lang_items.owned_box() } ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) | ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_tup(..) | ty_param(..) | ty_err | ty_open(..) | ty_ptr(_) | ty_rptr(_, _) | ty_projection(..) => { None } ty_infer(..) | ty_closure(..) => { // `ty` comes from a user declaration so we should only expect types // that the user can type inference_context.tcx.sess.span_bug( span, &format!("coherence encountered unexpected type searching for base type: {}", ty.repr(inference_context.tcx))[]); } } } struct CoherenceChecker<'a, 'tcx: 'a> { crate_context: &'a CrateCtxt<'a, 'tcx>, inference_context: InferCtxt<'a, 'tcx>, inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>, } struct CoherenceCheckVisitor<'a, 'tcx: 'a> { cc: &'a CoherenceChecker<'a, 'tcx> } impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &Item) { //debug!("(checking coherence) item '{}'", token::get_ident(item.ident)); match item.node { ItemImpl(_, _, _, ref opt_trait, _, _) => { match opt_trait.clone() { Some(opt_trait) => { self.cc.check_implementation(item, &[opt_trait]); } None => self.cc.check_implementation(item, &[]) } } _ => { // Nothing to do. } }; visit::walk_item(self, item); } } impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { fn check(&self, krate: &Crate) { // Check implementations and traits. This populates the tables // containing the inherent methods and extension methods. It also // builds up the trait inheritance table. let mut visitor = CoherenceCheckVisitor { cc: self }; visit::walk_crate(&mut visitor, krate); // Copy over the inherent impls we gathered up during the walk into // the tcx. let mut tcx_inherent_impls = self.crate_context.tcx.inherent_impls.borrow_mut(); for (k, v) in &*self.inherent_impls.borrow() { tcx_inherent_impls.insert((*k).clone(), Rc::new((*v.borrow()).clone())); } // Bring in external crates. It's fine for this to happen after the // coherence checks, because we ensure by construction that no errors // can happen at link time. self.add_external_crates(); // Populate the table of destructors. It might seem a bit strange to // do this here, but it's actually the most convenient place, since // the coherence tables contain the trait -> type mappings. self.populate_destructor_table(); // Check to make sure implementations of `Copy` are legal. self.check_implementations_of_copy(); } fn check_implementation(&self, item: &Item, associated_traits: &[TraitRef]) { let tcx = self.crate_context.tcx; let impl_did = local_def(item.id); let self_type = ty::lookup_item_type(tcx, impl_did); // If there are no traits, then this implementation must have a // base type. let impl_items = self.create_impl_from_item(item); for associated_trait in associated_traits { let trait_ref = ty::node_id_to_trait_ref(self.crate_context.tcx, associated_trait.ref_id); debug!("(checking implementation) adding impl for trait '{}', item '{}'", trait_ref.repr(self.crate_context.tcx), token::get_ident(item.ident)); enforce_trait_manually_implementable(self.crate_context.tcx, item.span, trait_ref.def_id); self.add_trait_impl(trait_ref.def_id, impl_did); } // Add the implementation to the mapping from implementation to base // type def ID, if there is a base type for this implementation and // the implementation does not have any associated traits. match get_base_type_def_id(&self.inference_context, item.span, self_type.ty) { None => { // Nothing to do. } Some(base_type_def_id) => { // FIXME: Gather up default methods? if associated_traits.len() == 0 { self.add_inherent_impl(base_type_def_id, impl_did); } } } tcx.impl_items.borrow_mut().insert(impl_did, impl_items); } // Creates default method IDs and performs type substitutions for an impl // and trait pair. Then, for each provided method in the trait, inserts a // `ProvidedMethodInfo` instance into the `provided_method_sources` map. fn instantiate_default_methods( &self, impl_id: DefId, trait_ref: &ty::TraitRef<'tcx>, all_impl_items: &mut Vec<ImplOrTraitItemId>) { let tcx = self.crate_context.tcx; debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})", impl_id, trait_ref.repr(tcx)); let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); let prov = ty::provided_trait_methods(tcx, trait_ref.def_id); for trait_method in &prov { // Synthesize an ID. let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx)); // Create substitutions for the various trait parameters. let new_method_ty = Rc::new(subst_receiver_types_in_method_ty( tcx, impl_id, &impl_type_scheme, trait_ref, new_did, &**trait_method, Some(trait_method.def_id))); debug!("new_method_ty={}", new_method_ty.repr(tcx)); all_impl_items.push(MethodTraitItemId(new_did)); // construct the polytype for the method based on the // method_ty. it will have all the generics from the // impl, plus its own. let new_polytype = ty::TypeScheme { generics: new_method_ty.generics.clone(), ty: ty::mk_bare_fn(tcx, Some(new_did), tcx.mk_bare_fn(new_method_ty.fty.clone())) }; debug!("new_polytype={}", new_polytype.repr(tcx)); tcx.tcache.borrow_mut().insert(new_did, new_polytype); tcx.impl_or_trait_items .borrow_mut() .insert(new_did, ty::MethodTraitItem(new_method_ty)); // Pair the new synthesized ID up with the // ID of the method. self.crate_context.tcx.provided_method_sources.borrow_mut() .insert(new_did, trait_method.def_id); } } fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) { match self.inherent_impls.borrow().get(&base_def_id) { Some(implementation_list) => { implementation_list.borrow_mut().push(impl_def_id); return; } None => {} } self.inherent_impls.borrow_mut().insert( base_def_id, Rc::new(RefCell::new(vec!(impl_def_id)))); } fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) { debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}", base_def_id, impl_def_id); ty::record_trait_implementation(self.crate_context.tcx, base_def_id, impl_def_id); } fn get_self_type_for_implementation(&self, impl_did: DefId) -> TypeScheme<'tcx> { self.crate_context.tcx.tcache.borrow()[impl_did].clone() } // Converts an implementation in the AST to a vector of items. fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> { match item.node { ItemImpl(_, _, _, ref trait_refs, _, ref ast_items) => { let mut items: Vec<ImplOrTraitItemId> = ast_items.iter() .map(|ast_item| { match *ast_item { ast::MethodImplItem(ref ast_method) => { MethodTraitItemId( local_def(ast_method.id)) } ast::TypeImplItem(ref typedef) => { TypeTraitItemId(local_def(typedef.id)) } } }).collect(); if let Some(ref trait_ref) = *trait_refs { let ty_trait_ref = ty::node_id_to_trait_ref( self.crate_context.tcx, trait_ref.ref_id); self.instantiate_default_methods(local_def(item.id), &*ty_trait_ref, &mut items); } items } _ => { self.crate_context.tcx.sess.span_bug(item.span, "can't convert a non-impl to an impl"); } } } // External crate handling fn add_external_impl(&self, impls_seen: &mut HashSet<DefId>, impl_def_id: DefId) { let tcx = self.crate_context.tcx; let impl_items = csearch::get_impl_items(&tcx.sess.cstore, impl_def_id); // Make sure we don't visit the same implementation multiple times. if!impls_seen.insert(impl_def_id) { // Skip this one. return } // Good. Continue. let _ = lookup_item_type(tcx, impl_def_id); let associated_traits = get_impl_trait(tcx, impl_def_id); // Do a sanity check. assert!(associated_traits.is_some()); // Record all the trait items. if let Some(trait_ref) = associated_traits { self.add_trait_impl(trait_ref.def_id, impl_def_id); } // For any methods that use a default implementation, add them to // the map. This is a bit unfortunate. for item_def_id in &impl_items { let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id()); match impl_item { ty::MethodTraitItem(ref method) => { if let Some(source) = method.provided_source { tcx.provided_method_sources .borrow_mut() .insert(item_def_id.def_id(), source); } } ty::TypeTraitItem(_) => {} } } tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items); } // Adds implementations and traits from external crates to the coherence // info. fn add_external_crates(&self) { let mut impls_seen = HashSet::new(); let crate_store = &self.crate_context.tcx.sess.cstore; crate_store.iter_crate_data(|crate_number, _crate_metadata| { each_impl(crate_store, crate_number, |def_id| { assert_eq!(crate_number, def_id.krate); self.add_external_impl(&mut impls_seen, def_id) }) }) } // // Destructors // fn populate_destructor_table(&self) { let tcx = self.crate_context.tcx; let drop_trait = match tcx.lang_items.drop_trait() { Some(id) => id, None => { return } }; let impl_items = tcx.impl_items.borrow(); let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() { None => return, // No types with (new-style) dtors present. Some(found_impls) => found_impls }; for &impl_did in &*trait_impls.borrow() { let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; } let method_def_id = items[0]; let self_type = self.get_self_type_for_implementation(impl_did); match self_type.ty.sty { ty::ty_enum(type_def_id, _) | ty::ty_struct(type_def_id, _) | ty::ty_closure(type_def_id, _, _) => { tcx.destructor_for_type .borrow_mut() .insert(type_def_id, method_def_id.def_id()); tcx.destructors .borrow_mut() .insert(method_def_id.def_id()); } _ => { // Destructors only work on nominal types. if impl_did.krate == ast::LOCAL_CRATE { { match tcx.map.find(impl_did.node) { Some(ast_map::NodeItem(item)) => { span_err!(tcx.sess, item.span, E0120, "the Drop trait may only be implemented on structures"); } _ => { tcx.sess.bug("didn't find impl in ast \ map"); } } } } else { tcx.sess.bug("found external impl of Drop trait on \ something other than a struct"); } } } } } /// Ensures that implementations of the built-in trait `Copy` are legal. fn check_implementations_of_copy(&self) { let tcx = self.crate_context.tcx; let copy_trait = match tcx.lang_items.copy_trait() { Some(id) => id,
// Returns the def ID of the base type, if there is one. fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>, span: Span, ty: Ty<'tcx>) -> Option<DefId> {
random_line_split
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use anyhow::Result; use libimagrt::runtime::Runtime; use crate::reference::Config as RefConfig; pub fn
(rt: &Runtime, app_name: &'static str) -> Result<RefConfig> { use toml_query::read::TomlValueReadExt; let setting_name = "ref.basepathes"; rt.config() .ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))? .read_deserialized::<RefConfig>(setting_name)? .ok_or_else(|| anyhow!("Setting missing: {}", setting_name)) }
get_ref_config
identifier_name
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version // 2.1 of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // use anyhow::Result; use libimagrt::runtime::Runtime; use crate::reference::Config as RefConfig; pub fn get_ref_config(rt: &Runtime, app_name: &'static str) -> Result<RefConfig> { use toml_query::read::TomlValueReadExt; let setting_name = "ref.basepathes";
.ok_or_else(|| anyhow!("Setting missing: {}", setting_name)) }
rt.config() .ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))? .read_deserialized::<RefConfig>(setting_name)?
random_line_split