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
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/service_account pub 'Hello oh wonderful world' & //! $ target/debug/service_account sub //! Published message #95491011619126 //! message <95491011619126> 'Hello oh wonderful world' at 2016-09-21T20:04:47.040Z //! Published message #95491011620879 //! message <95491011620879> 'Hello oh wonderful world' at 2016-09-21T20:04:49.086Z //! Published message #95491011622600 //! message <95491011622600> 'Hello oh wonderful world' at 2016-09-21T20:04:51.132Z //! Published message #95491011624393 //! message <95491011624393> 'Hello oh wonderful world' at 2016-09-21T20:04:53.187Z //! Published message #95491011626206 //! message <95491011626206> 'Hello oh wonderful world' at 2016-09-21T20:04:55.233Z //! //! Copyright (c) 2016 Google, Inc. (Lewin Bormann <[email protected]>) //! extern crate base64; extern crate yup_oauth2 as oauth; extern crate google_pubsub1 as pubsub; extern crate hyper; extern crate hyper_rustls; use std::env; use std::time; use std::thread; use hyper::net::HttpsConnector; use pubsub::{Topic, Subscription}; // The prefixes are important! const SUBSCRIPTION_NAME: &'static str = "projects/sanguine-rhythm-105020/subscriptions/rust_authd_sub_1"; const TOPIC_NAME: &'static str = "projects/sanguine-rhythm-105020/topics/topic-01"; type PubsubMethods<'a> = pubsub::ProjectMethods<'a, hyper::Client, oauth::ServiceAccountAccess<hyper::Client>>; // Verifies that the topic TOPIC_NAME exists, or creates it. fn check_or_create_topic(methods: &PubsubMethods) -> Topic { let result = methods.topics_get(TOPIC_NAME).doit(); if result.is_err() { println!("Assuming topic doesn't exist; creating topic"); let topic = pubsub::Topic { name: Some(TOPIC_NAME.to_string()) }; let result = methods.topics_create(topic, TOPIC_NAME).doit().unwrap(); result.1 } else { result.unwrap().1 } } fn check_or_create_subscription(methods: &PubsubMethods) -> Subscription { // check if subscription exists let result = methods.subscriptions_get(SUBSCRIPTION_NAME).doit(); if result.is_err() { println!("Assuming subscription doesn't exist; creating subscription"); let sub = pubsub::Subscription { topic: Some(TOPIC_NAME.to_string()), ack_deadline_seconds: Some(30), push_config: None, name: Some(SUBSCRIPTION_NAME.to_string()), }; let (_resp, sub) = methods.subscriptions_create(sub, SUBSCRIPTION_NAME).doit().unwrap(); sub } else { result.unwrap().1 } } fn ack_message(methods: &PubsubMethods, id: String) { let request = pubsub::AcknowledgeRequest { ack_ids: Some(vec![id]) }; let result = methods.subscriptions_acknowledge(request, SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Ack error: {:?}", e); } Ok(_) => (), } } // Wait for new messages. Print and ack any new messages. fn subscribe_wait(methods: &PubsubMethods)
println!("message <{}> '{}' at {}", message.message_id.unwrap_or(String::new()), String::from_utf8(base64::decode(&message.data .unwrap_or(String::new())) .unwrap()) .unwrap(), message.publish_time.unwrap_or(String::new())); if ack_id!= "" { ack_message(methods, ack_id); } } } } } } // Publish some message every 2 seconds. fn publish_stuff(methods: &PubsubMethods, message: &str) { check_or_create_topic(&methods); let message = pubsub::PubsubMessage { // Base64 encoded! data: Some(base64::encode(message.as_bytes())), ..Default::default() }; let request = pubsub::PublishRequest { messages: Some(vec![message]) }; loop { let result = methods.topics_publish(request.clone(), TOPIC_NAME).doit(); match result { Err(e) => { println!("Publish error: {}", e); } Ok((_response, pubresponse)) => { for msg in pubresponse.message_ids.unwrap_or(Vec::new()) { println!("Published message #{}", msg); } } } thread::sleep(time::Duration::new(2, 0)); } } // If called as '.../service_account pub', act as publisher; if called as '.../service_account // sub', act as subscriber. fn main() { let client_secret = oauth::service_account_key_from_file(&"pubsub-auth.json".to_string()) .unwrap(); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let mut access = oauth::ServiceAccountAccess::new(client_secret, client); use oauth::GetToken; println!("{:?}", access.token(&vec!["https://www.googleapis.com/auth/pubsub"]).unwrap()); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let hub = pubsub::Pubsub::new(client, access); let methods = hub.projects(); let mode = env::args().nth(1).unwrap_or(String::new()); if mode == "pub" { let message = env::args().nth(2).unwrap_or("Hello World!".to_string()); publish_stuff(&methods, &message); } else if mode == "sub" { subscribe_wait(&methods); } else { println!("Please use either of 'pub' or'sub' as first argument to this binary!"); } }
{ check_or_create_subscription(&methods); let request = pubsub::PullRequest { return_immediately: Some(false), max_messages: Some(1), }; loop { let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Pull error: {}", e); } Ok((_response, pullresponse)) => { for msg in pullresponse.received_messages.unwrap_or(Vec::new()) { let ack_id = msg.ack_id.unwrap_or(String::new()); let message = msg.message.unwrap_or(Default::default());
identifier_body
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/service_account pub 'Hello oh wonderful world' & //! $ target/debug/service_account sub //! Published message #95491011619126 //! message <95491011619126> 'Hello oh wonderful world' at 2016-09-21T20:04:47.040Z //! Published message #95491011620879 //! message <95491011620879> 'Hello oh wonderful world' at 2016-09-21T20:04:49.086Z //! Published message #95491011622600 //! message <95491011622600> 'Hello oh wonderful world' at 2016-09-21T20:04:51.132Z //! Published message #95491011624393 //! message <95491011624393> 'Hello oh wonderful world' at 2016-09-21T20:04:53.187Z //! Published message #95491011626206 //! message <95491011626206> 'Hello oh wonderful world' at 2016-09-21T20:04:55.233Z //! //! Copyright (c) 2016 Google, Inc. (Lewin Bormann <[email protected]>) //! extern crate base64; extern crate yup_oauth2 as oauth; extern crate google_pubsub1 as pubsub; extern crate hyper; extern crate hyper_rustls; use std::env; use std::time; use std::thread; use hyper::net::HttpsConnector; use pubsub::{Topic, Subscription}; // The prefixes are important! const SUBSCRIPTION_NAME: &'static str = "projects/sanguine-rhythm-105020/subscriptions/rust_authd_sub_1"; const TOPIC_NAME: &'static str = "projects/sanguine-rhythm-105020/topics/topic-01"; type PubsubMethods<'a> = pubsub::ProjectMethods<'a, hyper::Client, oauth::ServiceAccountAccess<hyper::Client>>; // Verifies that the topic TOPIC_NAME exists, or creates it. fn check_or_create_topic(methods: &PubsubMethods) -> Topic { let result = methods.topics_get(TOPIC_NAME).doit(); if result.is_err() { println!("Assuming topic doesn't exist; creating topic"); let topic = pubsub::Topic { name: Some(TOPIC_NAME.to_string()) }; let result = methods.topics_create(topic, TOPIC_NAME).doit().unwrap(); result.1 } else { result.unwrap().1 } } fn check_or_create_subscription(methods: &PubsubMethods) -> Subscription { // check if subscription exists let result = methods.subscriptions_get(SUBSCRIPTION_NAME).doit(); if result.is_err() { println!("Assuming subscription doesn't exist; creating subscription"); let sub = pubsub::Subscription { topic: Some(TOPIC_NAME.to_string()), ack_deadline_seconds: Some(30), push_config: None, name: Some(SUBSCRIPTION_NAME.to_string()), }; let (_resp, sub) = methods.subscriptions_create(sub, SUBSCRIPTION_NAME).doit().unwrap(); sub } else { result.unwrap().1 } } fn ack_message(methods: &PubsubMethods, id: String) { let request = pubsub::AcknowledgeRequest { ack_ids: Some(vec![id]) }; let result = methods.subscriptions_acknowledge(request, SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Ack error: {:?}", e); } Ok(_) => (), } } // Wait for new messages. Print and ack any new messages. fn subscribe_wait(methods: &PubsubMethods) { check_or_create_subscription(&methods); let request = pubsub::PullRequest { return_immediately: Some(false), max_messages: Some(1), };
let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Pull error: {}", e); } Ok((_response, pullresponse)) => { for msg in pullresponse.received_messages.unwrap_or(Vec::new()) { let ack_id = msg.ack_id.unwrap_or(String::new()); let message = msg.message.unwrap_or(Default::default()); println!("message <{}> '{}' at {}", message.message_id.unwrap_or(String::new()), String::from_utf8(base64::decode(&message.data .unwrap_or(String::new())) .unwrap()) .unwrap(), message.publish_time.unwrap_or(String::new())); if ack_id!= "" { ack_message(methods, ack_id); } } } } } } // Publish some message every 2 seconds. fn publish_stuff(methods: &PubsubMethods, message: &str) { check_or_create_topic(&methods); let message = pubsub::PubsubMessage { // Base64 encoded! data: Some(base64::encode(message.as_bytes())), ..Default::default() }; let request = pubsub::PublishRequest { messages: Some(vec![message]) }; loop { let result = methods.topics_publish(request.clone(), TOPIC_NAME).doit(); match result { Err(e) => { println!("Publish error: {}", e); } Ok((_response, pubresponse)) => { for msg in pubresponse.message_ids.unwrap_or(Vec::new()) { println!("Published message #{}", msg); } } } thread::sleep(time::Duration::new(2, 0)); } } // If called as '.../service_account pub', act as publisher; if called as '.../service_account // sub', act as subscriber. fn main() { let client_secret = oauth::service_account_key_from_file(&"pubsub-auth.json".to_string()) .unwrap(); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let mut access = oauth::ServiceAccountAccess::new(client_secret, client); use oauth::GetToken; println!("{:?}", access.token(&vec!["https://www.googleapis.com/auth/pubsub"]).unwrap()); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let hub = pubsub::Pubsub::new(client, access); let methods = hub.projects(); let mode = env::args().nth(1).unwrap_or(String::new()); if mode == "pub" { let message = env::args().nth(2).unwrap_or("Hello World!".to_string()); publish_stuff(&methods, &message); } else if mode == "sub" { subscribe_wait(&methods); } else { println!("Please use either of 'pub' or'sub' as first argument to this binary!"); } }
loop {
random_line_split
main.rs
//! Demonstrates the use of service accounts and the Google Cloud Pubsub API. //! //! Run this binary as.../service_account pub 'your message' in order to publish messages, //! and as.../service_account sub in order to subscribe to those messages. This will look like the //! following: //! //! ``` //! $ target/debug/service_account pub 'Hello oh wonderful world' & //! $ target/debug/service_account sub //! Published message #95491011619126 //! message <95491011619126> 'Hello oh wonderful world' at 2016-09-21T20:04:47.040Z //! Published message #95491011620879 //! message <95491011620879> 'Hello oh wonderful world' at 2016-09-21T20:04:49.086Z //! Published message #95491011622600 //! message <95491011622600> 'Hello oh wonderful world' at 2016-09-21T20:04:51.132Z //! Published message #95491011624393 //! message <95491011624393> 'Hello oh wonderful world' at 2016-09-21T20:04:53.187Z //! Published message #95491011626206 //! message <95491011626206> 'Hello oh wonderful world' at 2016-09-21T20:04:55.233Z //! //! Copyright (c) 2016 Google, Inc. (Lewin Bormann <[email protected]>) //! extern crate base64; extern crate yup_oauth2 as oauth; extern crate google_pubsub1 as pubsub; extern crate hyper; extern crate hyper_rustls; use std::env; use std::time; use std::thread; use hyper::net::HttpsConnector; use pubsub::{Topic, Subscription}; // The prefixes are important! const SUBSCRIPTION_NAME: &'static str = "projects/sanguine-rhythm-105020/subscriptions/rust_authd_sub_1"; const TOPIC_NAME: &'static str = "projects/sanguine-rhythm-105020/topics/topic-01"; type PubsubMethods<'a> = pubsub::ProjectMethods<'a, hyper::Client, oauth::ServiceAccountAccess<hyper::Client>>; // Verifies that the topic TOPIC_NAME exists, or creates it. fn
(methods: &PubsubMethods) -> Topic { let result = methods.topics_get(TOPIC_NAME).doit(); if result.is_err() { println!("Assuming topic doesn't exist; creating topic"); let topic = pubsub::Topic { name: Some(TOPIC_NAME.to_string()) }; let result = methods.topics_create(topic, TOPIC_NAME).doit().unwrap(); result.1 } else { result.unwrap().1 } } fn check_or_create_subscription(methods: &PubsubMethods) -> Subscription { // check if subscription exists let result = methods.subscriptions_get(SUBSCRIPTION_NAME).doit(); if result.is_err() { println!("Assuming subscription doesn't exist; creating subscription"); let sub = pubsub::Subscription { topic: Some(TOPIC_NAME.to_string()), ack_deadline_seconds: Some(30), push_config: None, name: Some(SUBSCRIPTION_NAME.to_string()), }; let (_resp, sub) = methods.subscriptions_create(sub, SUBSCRIPTION_NAME).doit().unwrap(); sub } else { result.unwrap().1 } } fn ack_message(methods: &PubsubMethods, id: String) { let request = pubsub::AcknowledgeRequest { ack_ids: Some(vec![id]) }; let result = methods.subscriptions_acknowledge(request, SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Ack error: {:?}", e); } Ok(_) => (), } } // Wait for new messages. Print and ack any new messages. fn subscribe_wait(methods: &PubsubMethods) { check_or_create_subscription(&methods); let request = pubsub::PullRequest { return_immediately: Some(false), max_messages: Some(1), }; loop { let result = methods.subscriptions_pull(request.clone(), SUBSCRIPTION_NAME).doit(); match result { Err(e) => { println!("Pull error: {}", e); } Ok((_response, pullresponse)) => { for msg in pullresponse.received_messages.unwrap_or(Vec::new()) { let ack_id = msg.ack_id.unwrap_or(String::new()); let message = msg.message.unwrap_or(Default::default()); println!("message <{}> '{}' at {}", message.message_id.unwrap_or(String::new()), String::from_utf8(base64::decode(&message.data .unwrap_or(String::new())) .unwrap()) .unwrap(), message.publish_time.unwrap_or(String::new())); if ack_id!= "" { ack_message(methods, ack_id); } } } } } } // Publish some message every 2 seconds. fn publish_stuff(methods: &PubsubMethods, message: &str) { check_or_create_topic(&methods); let message = pubsub::PubsubMessage { // Base64 encoded! data: Some(base64::encode(message.as_bytes())), ..Default::default() }; let request = pubsub::PublishRequest { messages: Some(vec![message]) }; loop { let result = methods.topics_publish(request.clone(), TOPIC_NAME).doit(); match result { Err(e) => { println!("Publish error: {}", e); } Ok((_response, pubresponse)) => { for msg in pubresponse.message_ids.unwrap_or(Vec::new()) { println!("Published message #{}", msg); } } } thread::sleep(time::Duration::new(2, 0)); } } // If called as '.../service_account pub', act as publisher; if called as '.../service_account // sub', act as subscriber. fn main() { let client_secret = oauth::service_account_key_from_file(&"pubsub-auth.json".to_string()) .unwrap(); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let mut access = oauth::ServiceAccountAccess::new(client_secret, client); use oauth::GetToken; println!("{:?}", access.token(&vec!["https://www.googleapis.com/auth/pubsub"]).unwrap()); let client = hyper::Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())); let hub = pubsub::Pubsub::new(client, access); let methods = hub.projects(); let mode = env::args().nth(1).unwrap_or(String::new()); if mode == "pub" { let message = env::args().nth(2).unwrap_or("Hello World!".to_string()); publish_stuff(&methods, &message); } else if mode == "sub" { subscribe_wait(&methods); } else { println!("Please use either of 'pub' or'sub' as first argument to this binary!"); } }
check_or_create_topic
identifier_name
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; use url::{Origin, Url}; impl RobotsTxtClient for Client { type Result = Result<ParseResult<FetchedRobotsTxt>, Error>; fn fetch_robots_txt(&self, origin: Origin) -> Self::Result
}
{ let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let _ = request .headers_mut() .insert(USER_AGENT, HeaderValue::from_static(DEFAULT_USER_AGENT)); let response = self.execute(request).map_err(|err| Error { kind: ErrorKind::Http(err), })?; let status_code = response.status().as_u16(); let text = response.text().map_err(|err| Error { kind: ErrorKind::Http(err), })?; let robots_txt = parse_fetched_robots_txt(origin, status_code, &text); Ok(robots_txt) }
identifier_body
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; use url::{Origin, Url};
fn fetch_robots_txt(&self, origin: Origin) -> Self::Result { let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let _ = request .headers_mut() .insert(USER_AGENT, HeaderValue::from_static(DEFAULT_USER_AGENT)); let response = self.execute(request).map_err(|err| Error { kind: ErrorKind::Http(err), })?; let status_code = response.status().as_u16(); let text = response.text().map_err(|err| Error { kind: ErrorKind::Http(err), })?; let robots_txt = parse_fetched_robots_txt(origin, status_code, &text); Ok(robots_txt) } }
impl RobotsTxtClient for Client { type Result = Result<ParseResult<FetchedRobotsTxt>, Error>;
random_line_split
sync_reqwest.rs
use crate::http::{RobotsTxtClient, DEFAULT_USER_AGENT}; use crate::model::FetchedRobotsTxt; use crate::model::{Error, ErrorKind}; use crate::parser::{parse_fetched_robots_txt, ParseResult}; use reqwest::blocking::{Client, Request}; use reqwest::header::HeaderValue; use reqwest::header::USER_AGENT; use reqwest::Method; use url::{Origin, Url}; impl RobotsTxtClient for Client { type Result = Result<ParseResult<FetchedRobotsTxt>, Error>; fn
(&self, origin: Origin) -> Self::Result { let url = format!("{}/robots.txt", origin.unicode_serialization()); let url = Url::parse(&url).map_err(|err| Error { kind: ErrorKind::Url(err), })?; let mut request = Request::new(Method::GET, url); let _ = request .headers_mut() .insert(USER_AGENT, HeaderValue::from_static(DEFAULT_USER_AGENT)); let response = self.execute(request).map_err(|err| Error { kind: ErrorKind::Http(err), })?; let status_code = response.status().as_u16(); let text = response.text().map_err(|err| Error { kind: ErrorKind::Http(err), })?; let robots_txt = parse_fetched_robots_txt(origin, status_code, &text); Ok(robots_txt) } }
fetch_robots_txt
identifier_name
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader; use http_loader; use cookie_storage::CookieStorage; use cookie; use mime_classifier::MIMEClassifier; use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource}; use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction}; use net_traits::ProgressMsg::Done; use util::opts; use util::task::spawn_named; use url::Url; use hsts::{HSTSList, HSTSEntry, preload_hsts_domains}; use devtools_traits::{DevtoolsControlMsg}; use hyper::header::{ContentType, Header, SetCookie, UserAgent}; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { Channel(IpcSender<ProgressMsg>), Listener(AsyncResponseTarget), } impl ProgressSender { //XXXjdm return actual error pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> { match *self { ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; b.invoke_with_listener(action); Ok(()) } } } } /// For use by loaders in responding to a Load message. pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender { start_sending_opt(start_chan, metadata).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> ProgressSender { start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> Result<ProgressSender, ()> { if opts::get().sniff_mime_types { // TODO: should be calculated in the resource loader, from pull requeset #4094 let mut nosniff = false; let mut check_for_apache_bug = false; if let Some(ref headers) = metadata.headers
let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, &partial_body).map(|(toplevel, sublevel)| { let mime_tp: TopLevel = toplevel.parse().unwrap(); let mime_sb: SubLevel = sublevel.parse().unwrap(); ContentType(Mime(mime_tp, mime_sb, vec!())) }); } start_sending_opt(start_chan, metadata) } /// For use by loaders in responding to a Load message. pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> { match start_chan { LoadConsumer::Channel(start_chan) => { let (progress_chan, progress_port) = ipc::channel().unwrap(); let result = start_chan.send(LoadResponse { metadata: metadata, progress_port: progress_port, }); match result { Ok(_) => Ok(ProgressSender::Channel(progress_chan)), Err(_) => Err(()) } } LoadConsumer::Listener(target) => { target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata)); Ok(ProgressSender::Listener(target)) } } } /// Create a ResourceTask pub fn new_resource_task(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clone = setup_chan.clone(); spawn_named("ResourceManager".to_owned(), move || { let resource_manager = ResourceManager::new( user_agent, setup_chan_clone, hsts_preload, devtools_chan ); let mut channel_manager = ResourceChannelManager { from_client: setup_port, resource_manager: resource_manager }; channel_manager.start(); }); setup_chan } struct ResourceChannelManager { from_client: IpcReceiver<ControlMsg>, resource_manager: ResourceManager } impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { ControlMsg::Load(load_data, consumer) => { self.resource_manager.load(load_data, consumer) } ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { self.resource_manager.set_cookies_for_url(request, cookie_list, source) } ControlMsg::GetCookiesForUrl(url, consumer, source) => { consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); } ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { self.resource_manager.add_hsts_entry(entry) } } ControlMsg::Exit => { break } } } } } pub struct ResourceManager { user_agent: String, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: Arc<Mutex<HSTSList>> } impl ResourceManager { pub fn new(user_agent: String, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { ResourceManager { user_agent: user_agent, cookie_storage: CookieStorage::new(), resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, hsts_list: Arc::new(Mutex::new(hsts_list)) } } } impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) { let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); } } } } pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { load_data.preserved_headers.set(UserAgent(self.user_agent.clone())); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { box move |load_data, senders, classifier| { factory(load_data, senders, classifier) } } let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(consumer, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap(); return } }; debug!("resource_task: loading url: {}", load_data.url.serialize()); loader.call_box((load_data, consumer, self.mime_classifier.clone())); } }
{ if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" || last_raw_content_type == b"text/plain; charset=ISO-8859-1" || last_raw_content_type == b"text/plain; charset=iso-8859-1" || last_raw_content_type == b"text/plain; charset=UTF-8"; } } if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") { nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff"); } }
conditional_block
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader; use http_loader; use cookie_storage::CookieStorage; use cookie; use mime_classifier::MIMEClassifier; use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource}; use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction}; use net_traits::ProgressMsg::Done; use util::opts; use util::task::spawn_named; use url::Url; use hsts::{HSTSList, HSTSEntry, preload_hsts_domains}; use devtools_traits::{DevtoolsControlMsg}; use hyper::header::{ContentType, Header, SetCookie, UserAgent}; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { Channel(IpcSender<ProgressMsg>), Listener(AsyncResponseTarget), } impl ProgressSender { //XXXjdm return actual error pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> { match *self { ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; b.invoke_with_listener(action); Ok(()) } } } } /// For use by loaders in responding to a Load message. pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender { start_sending_opt(start_chan, metadata).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> ProgressSender { start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> Result<ProgressSender, ()> { if opts::get().sniff_mime_types { // TODO: should be calculated in the resource loader, from pull requeset #4094 let mut nosniff = false; let mut check_for_apache_bug = false; if let Some(ref headers) = metadata.headers { if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" || last_raw_content_type == b"text/plain; charset=ISO-8859-1" || last_raw_content_type == b"text/plain; charset=iso-8859-1" || last_raw_content_type == b"text/plain; charset=UTF-8"; } } if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") { nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff"); } } let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, &partial_body).map(|(toplevel, sublevel)| { let mime_tp: TopLevel = toplevel.parse().unwrap(); let mime_sb: SubLevel = sublevel.parse().unwrap(); ContentType(Mime(mime_tp, mime_sb, vec!())) }); } start_sending_opt(start_chan, metadata) } /// For use by loaders in responding to a Load message. pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> { match start_chan { LoadConsumer::Channel(start_chan) => { let (progress_chan, progress_port) = ipc::channel().unwrap(); let result = start_chan.send(LoadResponse { metadata: metadata, progress_port: progress_port, }); match result { Ok(_) => Ok(ProgressSender::Channel(progress_chan)), Err(_) => Err(()) } } LoadConsumer::Listener(target) => { target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata)); Ok(ProgressSender::Listener(target)) } } } /// Create a ResourceTask pub fn new_resource_task(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clone = setup_chan.clone(); spawn_named("ResourceManager".to_owned(), move || { let resource_manager = ResourceManager::new( user_agent, setup_chan_clone, hsts_preload, devtools_chan ); let mut channel_manager = ResourceChannelManager { from_client: setup_port, resource_manager: resource_manager }; channel_manager.start(); }); setup_chan } struct ResourceChannelManager { from_client: IpcReceiver<ControlMsg>, resource_manager: ResourceManager } impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { ControlMsg::Load(load_data, consumer) => { self.resource_manager.load(load_data, consumer) } ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { self.resource_manager.set_cookies_for_url(request, cookie_list, source) } ControlMsg::GetCookiesForUrl(url, consumer, source) => { consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); } ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { self.resource_manager.add_hsts_entry(entry) } } ControlMsg::Exit => { break } } } } } pub struct ResourceManager { user_agent: String, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: Arc<Mutex<HSTSList>> } impl ResourceManager { pub fn new(user_agent: String, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { ResourceManager { user_agent: user_agent, cookie_storage: CookieStorage::new(), resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, hsts_list: Arc::new(Mutex::new(hsts_list)) } } } impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource)
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { load_data.preserved_headers.set(UserAgent(self.user_agent.clone())); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { box move |load_data, senders, classifier| { factory(load_data, senders, classifier) } } let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(consumer, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap(); return } }; debug!("resource_task: loading url: {}", load_data.url.serialize()); loader.call_box((load_data, consumer, self.mime_classifier.clone())); } }
{ let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); } } } }
identifier_body
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader; use http_loader; use cookie_storage::CookieStorage; use cookie; use mime_classifier::MIMEClassifier; use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource}; use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction}; use net_traits::ProgressMsg::Done; use util::opts; use util::task::spawn_named; use url::Url; use hsts::{HSTSList, HSTSEntry, preload_hsts_domains}; use devtools_traits::{DevtoolsControlMsg}; use hyper::header::{ContentType, Header, SetCookie, UserAgent}; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { Channel(IpcSender<ProgressMsg>), Listener(AsyncResponseTarget), } impl ProgressSender { //XXXjdm return actual error pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> { match *self { ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; b.invoke_with_listener(action); Ok(()) } } } } /// For use by loaders in responding to a Load message. pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender { start_sending_opt(start_chan, metadata).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> ProgressSender { start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> Result<ProgressSender, ()> { if opts::get().sniff_mime_types { // TODO: should be calculated in the resource loader, from pull requeset #4094 let mut nosniff = false; let mut check_for_apache_bug = false; if let Some(ref headers) = metadata.headers { if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" || last_raw_content_type == b"text/plain; charset=ISO-8859-1" || last_raw_content_type == b"text/plain; charset=iso-8859-1" || last_raw_content_type == b"text/plain; charset=UTF-8"; } } if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") { nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff"); } } let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, &partial_body).map(|(toplevel, sublevel)| { let mime_tp: TopLevel = toplevel.parse().unwrap(); let mime_sb: SubLevel = sublevel.parse().unwrap(); ContentType(Mime(mime_tp, mime_sb, vec!())) }); } start_sending_opt(start_chan, metadata) } /// For use by loaders in responding to a Load message. pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> { match start_chan { LoadConsumer::Channel(start_chan) => { let (progress_chan, progress_port) = ipc::channel().unwrap(); let result = start_chan.send(LoadResponse { metadata: metadata, progress_port: progress_port, }); match result { Ok(_) => Ok(ProgressSender::Channel(progress_chan)), Err(_) => Err(()) } } LoadConsumer::Listener(target) => { target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata)); Ok(ProgressSender::Listener(target)) } } } /// Create a ResourceTask pub fn new_resource_task(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clone = setup_chan.clone(); spawn_named("ResourceManager".to_owned(), move || { let resource_manager = ResourceManager::new( user_agent, setup_chan_clone, hsts_preload, devtools_chan ); let mut channel_manager = ResourceChannelManager { from_client: setup_port, resource_manager: resource_manager }; channel_manager.start(); }); setup_chan } struct ResourceChannelManager { from_client: IpcReceiver<ControlMsg>, resource_manager: ResourceManager } impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { ControlMsg::Load(load_data, consumer) => { self.resource_manager.load(load_data, consumer) } ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { self.resource_manager.set_cookies_for_url(request, cookie_list, source) } ControlMsg::GetCookiesForUrl(url, consumer, source) => { consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); } ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { self.resource_manager.add_hsts_entry(entry) } } ControlMsg::Exit => { break } } } } } pub struct ResourceManager { user_agent: String, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: Arc<Mutex<HSTSList>> } impl ResourceManager { pub fn new(user_agent: String, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { ResourceManager { user_agent: user_agent, cookie_storage: CookieStorage::new(), resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, hsts_list: Arc::new(Mutex::new(hsts_list)) } } } impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) { let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); }
pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { load_data.preserved_headers.set(UserAgent(self.user_agent.clone())); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { box move |load_data, senders, classifier| { factory(load_data, senders, classifier) } } let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(consumer, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap(); return } }; debug!("resource_task: loading url: {}", load_data.url.serialize()); loader.call_box((load_data, consumer, self.mime_classifier.clone())); } }
} } }
random_line_split
resource_task.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/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader; use http_loader; use cookie_storage::CookieStorage; use cookie; use mime_classifier::MIMEClassifier; use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource}; use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction}; use net_traits::ProgressMsg::Done; use util::opts; use util::task::spawn_named; use url::Url; use hsts::{HSTSList, HSTSEntry, preload_hsts_domains}; use devtools_traits::{DevtoolsControlMsg}; use hyper::header::{ContentType, Header, SetCookie, UserAgent}; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { Channel(IpcSender<ProgressMsg>), Listener(AsyncResponseTarget), } impl ProgressSender { //XXXjdm return actual error pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> { match *self { ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; b.invoke_with_listener(action); Ok(()) } } } } /// For use by loaders in responding to a Load message. pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender { start_sending_opt(start_chan, metadata).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> ProgressSender { start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> Result<ProgressSender, ()> { if opts::get().sniff_mime_types { // TODO: should be calculated in the resource loader, from pull requeset #4094 let mut nosniff = false; let mut check_for_apache_bug = false; if let Some(ref headers) = metadata.headers { if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" || last_raw_content_type == b"text/plain; charset=ISO-8859-1" || last_raw_content_type == b"text/plain; charset=iso-8859-1" || last_raw_content_type == b"text/plain; charset=UTF-8"; } } if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") { nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff"); } } let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, &partial_body).map(|(toplevel, sublevel)| { let mime_tp: TopLevel = toplevel.parse().unwrap(); let mime_sb: SubLevel = sublevel.parse().unwrap(); ContentType(Mime(mime_tp, mime_sb, vec!())) }); } start_sending_opt(start_chan, metadata) } /// For use by loaders in responding to a Load message. pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> { match start_chan { LoadConsumer::Channel(start_chan) => { let (progress_chan, progress_port) = ipc::channel().unwrap(); let result = start_chan.send(LoadResponse { metadata: metadata, progress_port: progress_port, }); match result { Ok(_) => Ok(ProgressSender::Channel(progress_chan)), Err(_) => Err(()) } } LoadConsumer::Listener(target) => { target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata)); Ok(ProgressSender::Listener(target)) } } } /// Create a ResourceTask pub fn
(user_agent: String, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clone = setup_chan.clone(); spawn_named("ResourceManager".to_owned(), move || { let resource_manager = ResourceManager::new( user_agent, setup_chan_clone, hsts_preload, devtools_chan ); let mut channel_manager = ResourceChannelManager { from_client: setup_port, resource_manager: resource_manager }; channel_manager.start(); }); setup_chan } struct ResourceChannelManager { from_client: IpcReceiver<ControlMsg>, resource_manager: ResourceManager } impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { ControlMsg::Load(load_data, consumer) => { self.resource_manager.load(load_data, consumer) } ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { self.resource_manager.set_cookies_for_url(request, cookie_list, source) } ControlMsg::GetCookiesForUrl(url, consumer, source) => { consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); } ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { self.resource_manager.add_hsts_entry(entry) } } ControlMsg::Exit => { break } } } } } pub struct ResourceManager { user_agent: String, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: Arc<Mutex<HSTSList>> } impl ResourceManager { pub fn new(user_agent: String, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { ResourceManager { user_agent: user_agent, cookie_storage: CookieStorage::new(), resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, hsts_list: Arc::new(Mutex::new(hsts_list)) } } } impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) { let header = Header::parse_header(&[cookie_list.into_bytes()]); if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); } } } } pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { load_data.preserved_headers.set(UserAgent(self.user_agent.clone())); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { box move |load_data, senders, classifier| { factory(load_data, senders, classifier) } } let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(consumer, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap(); return } }; debug!("resource_task: loading url: {}", load_data.url.serialize()); loader.call_box((load_data, consumer, self.mime_classifier.clone())); } }
new_resource_task
identifier_name
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destination adress to a socket inode of a process. conn_to_inode_map: ConnToInodeMap, /// Matches a socket inode to its process. inode_to_pid_map: InodeToPidMap, } /// `PacketMatcher` provides a function which allows matching /// source/destination adresses for packet to a process. #[derive(Debug)] pub struct PacketMatcher { /// conn->inode->pid Tables tables: PacketMatcherTables, /// Store all already-handled connections in HashMap so we can look them up /// without having to refresh the other maps (less cpu intensive/caching) /// /// If the resulting value is None, the connection could not be associated with /// process and it is in most cases pointless to try again. known_connections: HashMap<(TransportType, Connection), Option<(Inode, Pid)>>, /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. min_refresh_interval: Option<Duration>, last_refresh: Option<Instant>, } impl PacketMatcherTables { /// Constructor for `PacketMatcherTables`. pub fn new() -> PacketMatcherTables { PacketMatcherTables { conn_to_inode_map: ConnToInodeMap::new(), inode_to_pid_map: InodeToPidMap::new(), } } /// This function updates the tables that are used for the matching. pub fn refresh(&mut self) -> Result<()> { self.conn_to_inode_map.refresh()?; self.inode_to_pid_map.refresh()?; Ok(()) } /// Maps connection from conn->inode->pid with internal tables. fn map_connection(&self, tt: TransportType, c: Connection) -> Option<(Inode, Pid)> { self.conn_to_inode_map .find_inode(tt, c) .and_then(|inode| self.inode_to_pid_map.find_pid(inode) .map(|pid| (inode, pid))) } } impl PacketMatcher { /// Constructor for `PacketMatcher`. pub fn new() -> PacketMatcher { PacketMatcher { tables: PacketMatcherTables::new(), known_connections: HashMap::new(), min_refresh_interval: None, last_refresh: None, } } /// This function updates the tables that are used for the matching. fn refresh(&mut self) -> Result<()> { if let Some(min_refresh_interval) = self.min_refresh_interval { let now = Instant::now(); if let Some(last_refresh) = self.last_refresh { if now - last_refresh < min_refresh_interval { return Ok(()); } } self.last_refresh = Some(now); } self.tables.refresh()?; self.update_known_connections()?; Ok(()) } /// A process might end a connection and another might open the same connection. /// To prevent wrong assignment we have to update/purge the "self.known_connections" /// when connection is closed/reopened. fn
(&mut self) -> Result<()> { self.known_connections = self.known_connections.iter() .filter_map(|(&(tt, c), &old)| { let new = self.tables.map_connection(tt, c); match (old, new) { // Connection used to exist, but not anymore -> remove/drop so // if reopened it will be assinged to a new program (Some(_), None) => { None } // in these cases the connection was changed/did not change/was created (_, new) => { Some(((tt, c), new)) } } }) .collect(); Ok(()) } /// Find the process to which a packet belongs. pub fn find_pid(&mut self, packet_info: PacketInfo) -> Result<Option<Pid>> { let tt = packet_info.transport_type; let mut c = Connection::from(packet_info.clone()); match packet_info.inout_type { // Incoming packets have a their address ordered as "remote addr -> local addr" but // our connection-to-inode table only contains "local addr -> remote addr" entries. // So we have to reverse the connection. Some(InoutType::Incoming) => { c = c.get_reverse(); } Some(InoutType::Outgoing) => {} // TODO: use heuristics to guess whether packet is incoming or outgoing - this is just a corner case though None => { return Ok(None); } } self.find_pid_cached(tt, c) } /// Find the process by transport type and connection. The connection has to be /// already reversed for incoming packets. /// This functions uses the "self.known_connections"-HashMap or adds the new connection /// to it. fn find_pid_cached(&mut self, tt: TransportType, c: Connection) -> Result<Option<Pid>> { if let Some(&res) = self.known_connections.get(&(tt, c)) { // Known connection! Does this connection have a process? Ok(res.map(|(_, pid)| pid)) } else { // Unknown connection! self.refresh()?; let inode_pid_opt = self.tables.map_connection(tt, c); self.known_connections.insert((tt, c), inode_pid_opt); Ok(inode_pid_opt.map(|(_, pid)| pid)) } } /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. /// /// With None, you can deactivate time measurements. pub fn set_min_refresh_interval(&mut self, t: Option<Duration>) { self.min_refresh_interval = t; } }
update_known_connections
identifier_name
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destination adress to a socket inode of a process. conn_to_inode_map: ConnToInodeMap, /// Matches a socket inode to its process. inode_to_pid_map: InodeToPidMap, }
tables: PacketMatcherTables, /// Store all already-handled connections in HashMap so we can look them up /// without having to refresh the other maps (less cpu intensive/caching) /// /// If the resulting value is None, the connection could not be associated with /// process and it is in most cases pointless to try again. known_connections: HashMap<(TransportType, Connection), Option<(Inode, Pid)>>, /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. min_refresh_interval: Option<Duration>, last_refresh: Option<Instant>, } impl PacketMatcherTables { /// Constructor for `PacketMatcherTables`. pub fn new() -> PacketMatcherTables { PacketMatcherTables { conn_to_inode_map: ConnToInodeMap::new(), inode_to_pid_map: InodeToPidMap::new(), } } /// This function updates the tables that are used for the matching. pub fn refresh(&mut self) -> Result<()> { self.conn_to_inode_map.refresh()?; self.inode_to_pid_map.refresh()?; Ok(()) } /// Maps connection from conn->inode->pid with internal tables. fn map_connection(&self, tt: TransportType, c: Connection) -> Option<(Inode, Pid)> { self.conn_to_inode_map .find_inode(tt, c) .and_then(|inode| self.inode_to_pid_map.find_pid(inode) .map(|pid| (inode, pid))) } } impl PacketMatcher { /// Constructor for `PacketMatcher`. pub fn new() -> PacketMatcher { PacketMatcher { tables: PacketMatcherTables::new(), known_connections: HashMap::new(), min_refresh_interval: None, last_refresh: None, } } /// This function updates the tables that are used for the matching. fn refresh(&mut self) -> Result<()> { if let Some(min_refresh_interval) = self.min_refresh_interval { let now = Instant::now(); if let Some(last_refresh) = self.last_refresh { if now - last_refresh < min_refresh_interval { return Ok(()); } } self.last_refresh = Some(now); } self.tables.refresh()?; self.update_known_connections()?; Ok(()) } /// A process might end a connection and another might open the same connection. /// To prevent wrong assignment we have to update/purge the "self.known_connections" /// when connection is closed/reopened. fn update_known_connections(&mut self) -> Result<()> { self.known_connections = self.known_connections.iter() .filter_map(|(&(tt, c), &old)| { let new = self.tables.map_connection(tt, c); match (old, new) { // Connection used to exist, but not anymore -> remove/drop so // if reopened it will be assinged to a new program (Some(_), None) => { None } // in these cases the connection was changed/did not change/was created (_, new) => { Some(((tt, c), new)) } } }) .collect(); Ok(()) } /// Find the process to which a packet belongs. pub fn find_pid(&mut self, packet_info: PacketInfo) -> Result<Option<Pid>> { let tt = packet_info.transport_type; let mut c = Connection::from(packet_info.clone()); match packet_info.inout_type { // Incoming packets have a their address ordered as "remote addr -> local addr" but // our connection-to-inode table only contains "local addr -> remote addr" entries. // So we have to reverse the connection. Some(InoutType::Incoming) => { c = c.get_reverse(); } Some(InoutType::Outgoing) => {} // TODO: use heuristics to guess whether packet is incoming or outgoing - this is just a corner case though None => { return Ok(None); } } self.find_pid_cached(tt, c) } /// Find the process by transport type and connection. The connection has to be /// already reversed for incoming packets. /// This functions uses the "self.known_connections"-HashMap or adds the new connection /// to it. fn find_pid_cached(&mut self, tt: TransportType, c: Connection) -> Result<Option<Pid>> { if let Some(&res) = self.known_connections.get(&(tt, c)) { // Known connection! Does this connection have a process? Ok(res.map(|(_, pid)| pid)) } else { // Unknown connection! self.refresh()?; let inode_pid_opt = self.tables.map_connection(tt, c); self.known_connections.insert((tt, c), inode_pid_opt); Ok(inode_pid_opt.map(|(_, pid)| pid)) } } /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. /// /// With None, you can deactivate time measurements. pub fn set_min_refresh_interval(&mut self, t: Option<Duration>) { self.min_refresh_interval = t; } }
/// `PacketMatcher` provides a function which allows matching /// source/destination adresses for packet to a process. #[derive(Debug)] pub struct PacketMatcher { /// conn->inode->pid Tables
random_line_split
packet_matcher.rs
use netinfo::{ConnToInodeMap, InodeToPidMap, Inode, Pid, Connection, InoutType, TransportType, PacketInfo}; use netinfo::error::*; use std::collections::HashMap; use std::time::{Instant, Duration}; /// Provides the tables for PacketMatcher. #[derive(Debug)] struct PacketMatcherTables { /// Matches a source/destination adress to a socket inode of a process. conn_to_inode_map: ConnToInodeMap, /// Matches a socket inode to its process. inode_to_pid_map: InodeToPidMap, } /// `PacketMatcher` provides a function which allows matching /// source/destination adresses for packet to a process. #[derive(Debug)] pub struct PacketMatcher { /// conn->inode->pid Tables tables: PacketMatcherTables, /// Store all already-handled connections in HashMap so we can look them up /// without having to refresh the other maps (less cpu intensive/caching) /// /// If the resulting value is None, the connection could not be associated with /// process and it is in most cases pointless to try again. known_connections: HashMap<(TransportType, Connection), Option<(Inode, Pid)>>, /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. min_refresh_interval: Option<Duration>, last_refresh: Option<Instant>, } impl PacketMatcherTables { /// Constructor for `PacketMatcherTables`. pub fn new() -> PacketMatcherTables { PacketMatcherTables { conn_to_inode_map: ConnToInodeMap::new(), inode_to_pid_map: InodeToPidMap::new(), } } /// This function updates the tables that are used for the matching. pub fn refresh(&mut self) -> Result<()> { self.conn_to_inode_map.refresh()?; self.inode_to_pid_map.refresh()?; Ok(()) } /// Maps connection from conn->inode->pid with internal tables. fn map_connection(&self, tt: TransportType, c: Connection) -> Option<(Inode, Pid)> { self.conn_to_inode_map .find_inode(tt, c) .and_then(|inode| self.inode_to_pid_map.find_pid(inode) .map(|pid| (inode, pid))) } } impl PacketMatcher { /// Constructor for `PacketMatcher`. pub fn new() -> PacketMatcher { PacketMatcher { tables: PacketMatcherTables::new(), known_connections: HashMap::new(), min_refresh_interval: None, last_refresh: None, } } /// This function updates the tables that are used for the matching. fn refresh(&mut self) -> Result<()> { if let Some(min_refresh_interval) = self.min_refresh_interval { let now = Instant::now(); if let Some(last_refresh) = self.last_refresh { if now - last_refresh < min_refresh_interval { return Ok(()); } } self.last_refresh = Some(now); } self.tables.refresh()?; self.update_known_connections()?; Ok(()) } /// A process might end a connection and another might open the same connection. /// To prevent wrong assignment we have to update/purge the "self.known_connections" /// when connection is closed/reopened. fn update_known_connections(&mut self) -> Result<()> { self.known_connections = self.known_connections.iter() .filter_map(|(&(tt, c), &old)| { let new = self.tables.map_connection(tt, c); match (old, new) { // Connection used to exist, but not anymore -> remove/drop so // if reopened it will be assinged to a new program (Some(_), None) =>
// in these cases the connection was changed/did not change/was created (_, new) => { Some(((tt, c), new)) } } }) .collect(); Ok(()) } /// Find the process to which a packet belongs. pub fn find_pid(&mut self, packet_info: PacketInfo) -> Result<Option<Pid>> { let tt = packet_info.transport_type; let mut c = Connection::from(packet_info.clone()); match packet_info.inout_type { // Incoming packets have a their address ordered as "remote addr -> local addr" but // our connection-to-inode table only contains "local addr -> remote addr" entries. // So we have to reverse the connection. Some(InoutType::Incoming) => { c = c.get_reverse(); } Some(InoutType::Outgoing) => {} // TODO: use heuristics to guess whether packet is incoming or outgoing - this is just a corner case though None => { return Ok(None); } } self.find_pid_cached(tt, c) } /// Find the process by transport type and connection. The connection has to be /// already reversed for incoming packets. /// This functions uses the "self.known_connections"-HashMap or adds the new connection /// to it. fn find_pid_cached(&mut self, tt: TransportType, c: Connection) -> Result<Option<Pid>> { if let Some(&res) = self.known_connections.get(&(tt, c)) { // Known connection! Does this connection have a process? Ok(res.map(|(_, pid)| pid)) } else { // Unknown connection! self.refresh()?; let inode_pid_opt = self.tables.map_connection(tt, c); self.known_connections.insert((tt, c), inode_pid_opt); Ok(inode_pid_opt.map(|(_, pid)| pid)) } } /// By default a table refresh is done for every new connection - these can be quite a lot! To /// avoid 100% CPU usage, this value can be used to set a minimimum time interval for refreshes. /// /// With None, you can deactivate time measurements. pub fn set_min_refresh_interval(&mut self, t: Option<Duration>) { self.min_refresh_interval = t; } }
{ None }
conditional_block
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<PathBuf> { #[cfg(unix)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push(".cache"); dir }) } #[cfg(windows)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push("Local Settings"); dir.push("Cache"); dir }) } _cache_home() } #[test] #[cfg(test)] fn tests() { #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) =>
None => assert!(false, "Couldn't get homedir!") } } _tests() }
{ dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_str, cache_str); }
conditional_block
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<PathBuf> { #[cfg(unix)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push(".cache"); dir }) } #[cfg(windows)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push("Local Settings"); dir.push("Cache"); dir }) } _cache_home() } #[test] #[cfg(test)] fn tests()
{ #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_str, cache_str); } None => assert!(false, "Couldn't get homedir!") } } _tests() }
identifier_body
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<PathBuf> { #[cfg(unix)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push(".cache"); dir }) } #[cfg(windows)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push("Local Settings"); dir.push("Cache"); dir }) } _cache_home() } #[test] #[cfg(test)] fn
() { #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_str, cache_str); } None => assert!(false, "Couldn't get homedir!") } } _tests() }
tests
identifier_name
appdirs.rs
use std::path::PathBuf; use dirs; /// OS specific path to the application cache directory. pub fn cache(app_name: &str) -> Option<PathBuf> { if app_name.is_empty() { return None; } cache_home().map(|mut dir| { dir.push(app_name); dir }) } /// OS specific path for caches. pub fn cache_home() -> Option<PathBuf> { #[cfg(unix)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push(".cache"); dir }) } #[cfg(windows)] fn _cache_home() -> Option<PathBuf> { dirs::home_dir().map(|mut dir| { dir.push("Local Settings"); dir.push("Cache"); dir
}) } _cache_home() } #[test] #[cfg(test)] fn tests() { #[cfg(unix)] fn _tests() { match dirs::home_dir() { Some(mut dir) => { dir.push(".cache"); dir.push("blub"); let dir_str = format!("{}", dir.display()); let cache_str = format!("{}", cache("blub").unwrap().display()); assert_eq!(dir_str, cache_str); } None => assert!(false, "Couldn't get homedir!") } } _tests() }
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct
{ htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { Node::reflect_node(box HTMLDataListElement::new_inherited(local_name, prefix, document), document, HTMLDataListElementBinding::Wrap) } } impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
HTMLDataListElement
identifier_name
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { Node::reflect_node(box HTMLDataListElement::new_inherited(local_name, prefix, document), document, HTMLDataListElementBinding::Wrap) } } impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement>
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
{ Node::reflect_node(box HTMLDataListElement::new_inherited(local_name, prefix, document), document, HTMLDataListElementBinding::Wrap) }
identifier_body
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move this to the `narrow_phase` module. /// Collision detector dispatcher for collision objects. pub struct CollisionObjectsDispatcher<P, M, T> { signal: ContactSignal<T>, shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>, pairs: HashMap<Pair, CollisionAlgorithm<P, M>, PairTWHash> } impl<P: Point, M, T> CollisionObjectsDispatcher<P, M, T> { /// Creates a new `CollisionObjectsDispatcher`. pub fn new(shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>) -> CollisionObjectsDispatcher<P, M, T> { CollisionObjectsDispatcher { signal: ContactSignal::new(), pairs: HashMap::new(PairTWHash::new()), shape_dispatcher: shape_dispatcher } } /// Updates the contact pairs. pub fn update(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, timestamp: usize) { for e in self.pairs.elements_mut().iter_mut() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; if co1.timestamp == timestamp || co2.timestamp == timestamp { let had_colls = e.value.num_colls()!= 0; e.value.update(&*self.shape_dispatcher, &co1.position, &**co1.shape, &co2.position, &**co2.shape); if e.value.num_colls() == 0 { if had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } } else { if!had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, true) } } } } } /// Iterates through all the contact pairs. #[inline(always)] pub fn contact_pairs<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &CollisionAlgorithm<P, M>) { for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; f(&co1.data, &co2.data, &e.value) } } /// Calls a closures on each contact between two objects. #[inline(always)] pub fn contacts<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &Contact<P>) { // FIXME: avoid allocation. let mut collector = Vec::new(); for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; e.value.colls(&mut collector); for c in collector[..].iter() { f(&co1.data, &co2.data, c) } collector.clear(); } } /// Registers a handler for contact start/stop events. pub fn register_contact_signal_handler(&mut self, name: &str, handler: Box<ContactSignalHandler<T> +'static>) { self.signal.register_contact_signal_handler(name, handler) } /// Unregisters a handler for contact start/stop events. pub fn unregister_contact_signal_handler(&mut self, name: &str) { self.signal.unregister_contact_signal_handler(name) } /// Creates/removes the persistant collision detector associated to a given pair of objects. pub fn handle_proximity(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey, started: bool) { let key = Pair::new(*fk1, *fk2); if started { let cd; { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; cd = self.shape_dispatcher.get_collision_algorithm(&co1.shape.repr(), &co2.shape.repr()); } if let Some(cd) = cd { let _ = self.pairs.insert(key, cd); } } else { // Proximity stopped. match self.pairs.get_and_remove(&key) { Some(detector) => { // Trigger the collision lost signal if there was a contact. if detector.value.num_colls()!= 0 { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } }, None => { } } } } /// Tests if two objects can be tested for mutual collision. pub fn is_proximity_allowed(objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey) -> bool { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; let can_move_ok = true; // XXX: ba.can_move() || bb.can_move(); let groups_ok = co1.collision_groups.can_collide_with_groups(&co2.collision_groups); if *fk1 == *fk2 { can_move_ok && co1.collision_groups.can_collide_with_self() } else
} }
{ can_move_ok && groups_ok }
conditional_block
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move this to the `narrow_phase` module. /// Collision detector dispatcher for collision objects. pub struct CollisionObjectsDispatcher<P, M, T> { signal: ContactSignal<T>, shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>, pairs: HashMap<Pair, CollisionAlgorithm<P, M>, PairTWHash> } impl<P: Point, M, T> CollisionObjectsDispatcher<P, M, T> { /// Creates a new `CollisionObjectsDispatcher`. pub fn
(shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>) -> CollisionObjectsDispatcher<P, M, T> { CollisionObjectsDispatcher { signal: ContactSignal::new(), pairs: HashMap::new(PairTWHash::new()), shape_dispatcher: shape_dispatcher } } /// Updates the contact pairs. pub fn update(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, timestamp: usize) { for e in self.pairs.elements_mut().iter_mut() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; if co1.timestamp == timestamp || co2.timestamp == timestamp { let had_colls = e.value.num_colls()!= 0; e.value.update(&*self.shape_dispatcher, &co1.position, &**co1.shape, &co2.position, &**co2.shape); if e.value.num_colls() == 0 { if had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } } else { if!had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, true) } } } } } /// Iterates through all the contact pairs. #[inline(always)] pub fn contact_pairs<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &CollisionAlgorithm<P, M>) { for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; f(&co1.data, &co2.data, &e.value) } } /// Calls a closures on each contact between two objects. #[inline(always)] pub fn contacts<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &Contact<P>) { // FIXME: avoid allocation. let mut collector = Vec::new(); for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; e.value.colls(&mut collector); for c in collector[..].iter() { f(&co1.data, &co2.data, c) } collector.clear(); } } /// Registers a handler for contact start/stop events. pub fn register_contact_signal_handler(&mut self, name: &str, handler: Box<ContactSignalHandler<T> +'static>) { self.signal.register_contact_signal_handler(name, handler) } /// Unregisters a handler for contact start/stop events. pub fn unregister_contact_signal_handler(&mut self, name: &str) { self.signal.unregister_contact_signal_handler(name) } /// Creates/removes the persistant collision detector associated to a given pair of objects. pub fn handle_proximity(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey, started: bool) { let key = Pair::new(*fk1, *fk2); if started { let cd; { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; cd = self.shape_dispatcher.get_collision_algorithm(&co1.shape.repr(), &co2.shape.repr()); } if let Some(cd) = cd { let _ = self.pairs.insert(key, cd); } } else { // Proximity stopped. match self.pairs.get_and_remove(&key) { Some(detector) => { // Trigger the collision lost signal if there was a contact. if detector.value.num_colls()!= 0 { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } }, None => { } } } } /// Tests if two objects can be tested for mutual collision. pub fn is_proximity_allowed(objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey) -> bool { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; let can_move_ok = true; // XXX: ba.can_move() || bb.can_move(); let groups_ok = co1.collision_groups.can_collide_with_groups(&co2.collision_groups); if *fk1 == *fk2 { can_move_ok && co1.collision_groups.can_collide_with_self() } else { can_move_ok && groups_ok } } }
new
identifier_name
collision_objects_dispatcher.rs
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; use math::Point; // FIXME: move this to the `narrow_phase` module. /// Collision detector dispatcher for collision objects. pub struct CollisionObjectsDispatcher<P, M, T> { signal: ContactSignal<T>, shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>, pairs: HashMap<Pair, CollisionAlgorithm<P, M>, PairTWHash> } impl<P: Point, M, T> CollisionObjectsDispatcher<P, M, T> { /// Creates a new `CollisionObjectsDispatcher`. pub fn new(shape_dispatcher: Box<CollisionDispatcher<P, M> +'static>) -> CollisionObjectsDispatcher<P, M, T> { CollisionObjectsDispatcher { signal: ContactSignal::new(), pairs: HashMap::new(PairTWHash::new()), shape_dispatcher: shape_dispatcher } } /// Updates the contact pairs. pub fn update(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, timestamp: usize) { for e in self.pairs.elements_mut().iter_mut() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; if co1.timestamp == timestamp || co2.timestamp == timestamp { let had_colls = e.value.num_colls()!= 0; e.value.update(&*self.shape_dispatcher, &co1.position, &**co1.shape, &co2.position, &**co2.shape); if e.value.num_colls() == 0 { if had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } } else { if!had_colls { self.signal.trigger_contact_signal(&co1.data, &co2.data, true) } } } } } /// Iterates through all the contact pairs. #[inline(always)] pub fn contact_pairs<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &CollisionAlgorithm<P, M>) { for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; f(&co1.data, &co2.data, &e.value) } } /// Calls a closures on each contact between two objects. #[inline(always)] pub fn contacts<F>(&self, objects: &UidRemap<CollisionObject<P, M, T>>, mut f: F) where F: FnMut(&T, &T, &Contact<P>) { // FIXME: avoid allocation. let mut collector = Vec::new(); for e in self.pairs.elements().iter() { let co1 = &objects[e.key.first]; let co2 = &objects[e.key.second]; e.value.colls(&mut collector); for c in collector[..].iter() { f(&co1.data, &co2.data, c) } collector.clear(); } } /// Registers a handler for contact start/stop events. pub fn register_contact_signal_handler(&mut self, name: &str, handler: Box<ContactSignalHandler<T> +'static>) { self.signal.register_contact_signal_handler(name, handler) } /// Unregisters a handler for contact start/stop events. pub fn unregister_contact_signal_handler(&mut self, name: &str) { self.signal.unregister_contact_signal_handler(name) } /// Creates/removes the persistant collision detector associated to a given pair of objects. pub fn handle_proximity(&mut self, objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey, started: bool) { let key = Pair::new(*fk1, *fk2); if started { let cd; { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; cd = self.shape_dispatcher.get_collision_algorithm(&co1.shape.repr(), &co2.shape.repr());
if let Some(cd) = cd { let _ = self.pairs.insert(key, cd); } } else { // Proximity stopped. match self.pairs.get_and_remove(&key) { Some(detector) => { // Trigger the collision lost signal if there was a contact. if detector.value.num_colls()!= 0 { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; self.signal.trigger_contact_signal(&co1.data, &co2.data, false); } }, None => { } } } } /// Tests if two objects can be tested for mutual collision. pub fn is_proximity_allowed(objects: &UidRemap<CollisionObject<P, M, T>>, fk1: &FastKey, fk2: &FastKey) -> bool { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; let can_move_ok = true; // XXX: ba.can_move() || bb.can_move(); let groups_ok = co1.collision_groups.can_collide_with_groups(&co2.collision_groups); if *fk1 == *fk2 { can_move_ok && co1.collision_groups.can_collide_with_self() } else { can_move_ok && groups_ok } } }
}
random_line_split
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll;
use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold { Optional::new( DisallowReExportAllInPage, is_page_file ) } struct DisallowReExportAllInPage; impl Fold for DisallowReExportAllInPage { noop_fold_type!(); fn fold_export_all(&mut self, e: ExportAll) -> ExportAll { HANDLER.with(|handler| { handler .struct_span_err( e.span, "Using `export * from '...'` in a page is disallowed. Please use `export { default } from '...'` instead.\nRead more: https://nextjs.org/docs/messages/export-all-in-page", ) .emit() }); e } }
random_line_split
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll; use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold { Optional::new( DisallowReExportAllInPage, is_page_file ) } struct
; impl Fold for DisallowReExportAllInPage { noop_fold_type!(); fn fold_export_all(&mut self, e: ExportAll) -> ExportAll { HANDLER.with(|handler| { handler .struct_span_err( e.span, "Using `export * from '...'` in a page is disallowed. Please use `export { default } from '...'` instead.\nRead more: https://nextjs.org/docs/messages/export-all-in-page", ) .emit() }); e } }
DisallowReExportAllInPage
identifier_name
disallow_re_export_all_in_page.rs
use swc_common::pass::Optional; use swc_ecmascript::ast::ExportAll; use swc_ecmascript::utils::HANDLER; use swc_ecmascript::visit::{noop_fold_type, Fold}; pub fn disallow_re_export_all_in_page(is_page_file: bool) -> impl Fold
struct DisallowReExportAllInPage; impl Fold for DisallowReExportAllInPage { noop_fold_type!(); fn fold_export_all(&mut self, e: ExportAll) -> ExportAll { HANDLER.with(|handler| { handler .struct_span_err( e.span, "Using `export * from '...'` in a page is disallowed. Please use `export { default } from '...'` instead.\nRead more: https://nextjs.org/docs/messages/export-all-in-page", ) .emit() }); e } }
{ Optional::new( DisallowReExportAllInPage, is_page_file ) }
identifier_body
escape_uri.rs
// Copyright 2019 Google LLC // // 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 // // https://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 core::fmt::Write; use std::fmt::Display; use std::iter::FusedIterator; use std::str::from_utf8_unchecked; #[cfg(feature = "std")] use std::borrow::Cow; fn is_char_uri_unreserved(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' || c == '~' } fn is_char_uri_sub_delim(c: char) -> bool { c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '+' || c == ',' || c == ';' || c == '=' } fn is_char_uri_pchar(c: char) -> bool { is_char_uri_unreserved(c) || is_char_uri_sub_delim(c) || c == ':' || c == '@' } fn is_char_uri_quote(c: char) -> bool { c!= '+' && (is_char_uri_pchar(c) || c == '/' || c == '?') } fn is_char_uri_fragment(c: char) -> bool { is_char_uri_pchar(c) || c == '/' || c == '?' || c == '#' } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub(super) enum EscapeUriState { Normal, OutputHighNibble(u8), OutputLowNibble(u8), } /// An internal, unstable trait that is used to adjust the behavior of [`EscapeUri`]. /// /// It is subject to change and is not considered stable. #[doc(hidden)] pub trait NeedsEscape: Clone { fn byte_needs_escape(b: u8) -> bool { Self::char_needs_escape(b as char) || (b & 0x80)!= 0 } fn char_needs_escape(c: char) -> bool; fn escape_space_as_plus() -> bool { false } } /// A zero-sized implementor of [`NeedsEscape`] that escapes all reserved characters. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriFull; impl NeedsEscape for EscapeUriFull { fn char_needs_escape(c: char) -> bool { !is_char_uri_unreserved(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping path segments. /// /// This used for the default behavior of [`escape_uri()`](trait.StrExt.html#tymethod.escape_uri). /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriSegment; impl NeedsEscape for EscapeUriSegment { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the entire authority component. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriAuthority; impl NeedsEscape for EscapeUriAuthority { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) && c!= '[' && c!= ']' } } /// A zero-sized implementor of [`NeedsEscape`] for escaping query items. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriQuery; impl NeedsEscape for EscapeUriQuery { fn char_needs_escape(c: char) -> bool { !is_char_uri_quote(c) } fn escape_space_as_plus() -> bool { true } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the fragment. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriFragment; impl NeedsEscape for EscapeUriFragment { fn char_needs_escape(c: char) -> bool { !is_char_uri_fragment(c) } } /// An iterator used to apply URI percent encoding to strings. /// /// It is constructed via the method [`escape_uri()`]. /// See the documentation for [`StrExt`] for more information. /// /// [`StrExt`]: trait.StrExt.html /// [`escape_uri()`]: trait.StrExt.html#tymethod.escape_uri #[derive(Debug, Clone)] pub struct EscapeUri<'a, X: NeedsEscape = EscapeUriSegment> { pub(super) iter: std::slice::Iter<'a, u8>, pub(super) state: EscapeUriState, pub(super) needs_escape: X, } #[cfg(feature = "std")] impl<'a, X: NeedsEscape> From<EscapeUri<'a, X>> for Cow<'a, str> { fn from(iter: EscapeUri<'a, X>) -> Self { iter.to_cow() } } impl<'a, X: NeedsEscape> EscapeUri<'a, X> { /// Determines if this iterator will actually escape anything. pub fn is_needed(&self) -> bool { for b in self.iter.clone() { if X::byte_needs_escape(*b) { return true; } } false } /// Converts this iterator into a [`std::borrow::Cow<str>`]. #[cfg(feature = "std")] pub fn to_cow(&self) -> Cow<'a, str> { if self.is_needed() { Cow::from(self.to_string()) } else { Cow::from(unsafe { from_utf8_unchecked(self.iter.as_slice()) }) } } /// Converts this iterator into one that escapes all except unreserved characters. pub fn full(self) -> EscapeUri<'a, EscapeUriFull> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFull, } } /// Converts this iterator into one optimized for escaping query components. pub fn for_query(self) -> EscapeUri<'a, EscapeUriQuery> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriQuery, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_fragment(self) -> EscapeUri<'a, EscapeUriFragment> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFragment, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_authority(self) -> EscapeUri<'a, EscapeUriAuthority> { EscapeUri {
iter: self.iter, state: self.state, needs_escape: EscapeUriAuthority, } } } impl<'a, X: NeedsEscape> Display for EscapeUri<'a, X> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.clone().try_for_each(|c| f.write_char(c)) } } impl<'a, X: NeedsEscape> FusedIterator for EscapeUri<'a, X> {} impl<'a, X: NeedsEscape> Iterator for EscapeUri<'a, X> { type Item = char; #[inline] fn next(&mut self) -> Option<char> { match self.state { EscapeUriState::Normal => match self.iter.next().copied() { Some(b) if X::escape_space_as_plus() && b == b''=> Some('+'), Some(b) if X::byte_needs_escape(b) => { self.state = EscapeUriState::OutputHighNibble(b); Some('%') } Some(b) => Some(b as char), None => None, }, EscapeUriState::OutputHighNibble(b) => { self.state = EscapeUriState::OutputLowNibble(b); let nibble = b >> 4; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } EscapeUriState::OutputLowNibble(b) => { self.state = EscapeUriState::Normal; let nibble = b & 0b1111; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let n = self.iter.size_hint().0; (n, Some(n * 3)) } }
random_line_split
escape_uri.rs
// Copyright 2019 Google LLC // // 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 // // https://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 core::fmt::Write; use std::fmt::Display; use std::iter::FusedIterator; use std::str::from_utf8_unchecked; #[cfg(feature = "std")] use std::borrow::Cow; fn is_char_uri_unreserved(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' || c == '~' } fn is_char_uri_sub_delim(c: char) -> bool { c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '+' || c == ',' || c == ';' || c == '=' } fn is_char_uri_pchar(c: char) -> bool { is_char_uri_unreserved(c) || is_char_uri_sub_delim(c) || c == ':' || c == '@' } fn is_char_uri_quote(c: char) -> bool { c!= '+' && (is_char_uri_pchar(c) || c == '/' || c == '?') } fn is_char_uri_fragment(c: char) -> bool { is_char_uri_pchar(c) || c == '/' || c == '?' || c == '#' } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub(super) enum EscapeUriState { Normal, OutputHighNibble(u8), OutputLowNibble(u8), } /// An internal, unstable trait that is used to adjust the behavior of [`EscapeUri`]. /// /// It is subject to change and is not considered stable. #[doc(hidden)] pub trait NeedsEscape: Clone { fn byte_needs_escape(b: u8) -> bool { Self::char_needs_escape(b as char) || (b & 0x80)!= 0 } fn char_needs_escape(c: char) -> bool; fn escape_space_as_plus() -> bool { false } } /// A zero-sized implementor of [`NeedsEscape`] that escapes all reserved characters. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriFull; impl NeedsEscape for EscapeUriFull { fn char_needs_escape(c: char) -> bool { !is_char_uri_unreserved(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping path segments. /// /// This used for the default behavior of [`escape_uri()`](trait.StrExt.html#tymethod.escape_uri). /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriSegment; impl NeedsEscape for EscapeUriSegment { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the entire authority component. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriAuthority; impl NeedsEscape for EscapeUriAuthority { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) && c!= '[' && c!= ']' } } /// A zero-sized implementor of [`NeedsEscape`] for escaping query items. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriQuery; impl NeedsEscape for EscapeUriQuery { fn char_needs_escape(c: char) -> bool { !is_char_uri_quote(c) } fn escape_space_as_plus() -> bool { true } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the fragment. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct
; impl NeedsEscape for EscapeUriFragment { fn char_needs_escape(c: char) -> bool { !is_char_uri_fragment(c) } } /// An iterator used to apply URI percent encoding to strings. /// /// It is constructed via the method [`escape_uri()`]. /// See the documentation for [`StrExt`] for more information. /// /// [`StrExt`]: trait.StrExt.html /// [`escape_uri()`]: trait.StrExt.html#tymethod.escape_uri #[derive(Debug, Clone)] pub struct EscapeUri<'a, X: NeedsEscape = EscapeUriSegment> { pub(super) iter: std::slice::Iter<'a, u8>, pub(super) state: EscapeUriState, pub(super) needs_escape: X, } #[cfg(feature = "std")] impl<'a, X: NeedsEscape> From<EscapeUri<'a, X>> for Cow<'a, str> { fn from(iter: EscapeUri<'a, X>) -> Self { iter.to_cow() } } impl<'a, X: NeedsEscape> EscapeUri<'a, X> { /// Determines if this iterator will actually escape anything. pub fn is_needed(&self) -> bool { for b in self.iter.clone() { if X::byte_needs_escape(*b) { return true; } } false } /// Converts this iterator into a [`std::borrow::Cow<str>`]. #[cfg(feature = "std")] pub fn to_cow(&self) -> Cow<'a, str> { if self.is_needed() { Cow::from(self.to_string()) } else { Cow::from(unsafe { from_utf8_unchecked(self.iter.as_slice()) }) } } /// Converts this iterator into one that escapes all except unreserved characters. pub fn full(self) -> EscapeUri<'a, EscapeUriFull> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFull, } } /// Converts this iterator into one optimized for escaping query components. pub fn for_query(self) -> EscapeUri<'a, EscapeUriQuery> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriQuery, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_fragment(self) -> EscapeUri<'a, EscapeUriFragment> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFragment, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_authority(self) -> EscapeUri<'a, EscapeUriAuthority> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriAuthority, } } } impl<'a, X: NeedsEscape> Display for EscapeUri<'a, X> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.clone().try_for_each(|c| f.write_char(c)) } } impl<'a, X: NeedsEscape> FusedIterator for EscapeUri<'a, X> {} impl<'a, X: NeedsEscape> Iterator for EscapeUri<'a, X> { type Item = char; #[inline] fn next(&mut self) -> Option<char> { match self.state { EscapeUriState::Normal => match self.iter.next().copied() { Some(b) if X::escape_space_as_plus() && b == b''=> Some('+'), Some(b) if X::byte_needs_escape(b) => { self.state = EscapeUriState::OutputHighNibble(b); Some('%') } Some(b) => Some(b as char), None => None, }, EscapeUriState::OutputHighNibble(b) => { self.state = EscapeUriState::OutputLowNibble(b); let nibble = b >> 4; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } EscapeUriState::OutputLowNibble(b) => { self.state = EscapeUriState::Normal; let nibble = b & 0b1111; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let n = self.iter.size_hint().0; (n, Some(n * 3)) } }
EscapeUriFragment
identifier_name
escape_uri.rs
// Copyright 2019 Google LLC // // 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 // // https://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 core::fmt::Write; use std::fmt::Display; use std::iter::FusedIterator; use std::str::from_utf8_unchecked; #[cfg(feature = "std")] use std::borrow::Cow; fn is_char_uri_unreserved(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' || c == '~' } fn is_char_uri_sub_delim(c: char) -> bool { c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '+' || c == ',' || c == ';' || c == '=' } fn is_char_uri_pchar(c: char) -> bool { is_char_uri_unreserved(c) || is_char_uri_sub_delim(c) || c == ':' || c == '@' } fn is_char_uri_quote(c: char) -> bool { c!= '+' && (is_char_uri_pchar(c) || c == '/' || c == '?') } fn is_char_uri_fragment(c: char) -> bool { is_char_uri_pchar(c) || c == '/' || c == '?' || c == '#' } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub(super) enum EscapeUriState { Normal, OutputHighNibble(u8), OutputLowNibble(u8), } /// An internal, unstable trait that is used to adjust the behavior of [`EscapeUri`]. /// /// It is subject to change and is not considered stable. #[doc(hidden)] pub trait NeedsEscape: Clone { fn byte_needs_escape(b: u8) -> bool { Self::char_needs_escape(b as char) || (b & 0x80)!= 0 } fn char_needs_escape(c: char) -> bool; fn escape_space_as_plus() -> bool { false } } /// A zero-sized implementor of [`NeedsEscape`] that escapes all reserved characters. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriFull; impl NeedsEscape for EscapeUriFull { fn char_needs_escape(c: char) -> bool { !is_char_uri_unreserved(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping path segments. /// /// This used for the default behavior of [`escape_uri()`](trait.StrExt.html#tymethod.escape_uri). /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriSegment; impl NeedsEscape for EscapeUriSegment { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the entire authority component. /// /// Its behavior is subject to change and is not considered stable. #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriAuthority; impl NeedsEscape for EscapeUriAuthority { fn char_needs_escape(c: char) -> bool { !is_char_uri_pchar(c) && c!= '[' && c!= ']' } } /// A zero-sized implementor of [`NeedsEscape`] for escaping query items. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriQuery; impl NeedsEscape for EscapeUriQuery { fn char_needs_escape(c: char) -> bool { !is_char_uri_quote(c) } fn escape_space_as_plus() -> bool { true } } /// A zero-sized implementor of [`NeedsEscape`] for escaping the fragment. /// /// Its behavior is subject to change and is not considered stable. /// #[doc(hidden)] #[derive(Default, Copy, Clone, Debug)] pub struct EscapeUriFragment; impl NeedsEscape for EscapeUriFragment { fn char_needs_escape(c: char) -> bool { !is_char_uri_fragment(c) } } /// An iterator used to apply URI percent encoding to strings. /// /// It is constructed via the method [`escape_uri()`]. /// See the documentation for [`StrExt`] for more information. /// /// [`StrExt`]: trait.StrExt.html /// [`escape_uri()`]: trait.StrExt.html#tymethod.escape_uri #[derive(Debug, Clone)] pub struct EscapeUri<'a, X: NeedsEscape = EscapeUriSegment> { pub(super) iter: std::slice::Iter<'a, u8>, pub(super) state: EscapeUriState, pub(super) needs_escape: X, } #[cfg(feature = "std")] impl<'a, X: NeedsEscape> From<EscapeUri<'a, X>> for Cow<'a, str> { fn from(iter: EscapeUri<'a, X>) -> Self { iter.to_cow() } } impl<'a, X: NeedsEscape> EscapeUri<'a, X> { /// Determines if this iterator will actually escape anything. pub fn is_needed(&self) -> bool { for b in self.iter.clone() { if X::byte_needs_escape(*b) { return true; } } false } /// Converts this iterator into a [`std::borrow::Cow<str>`]. #[cfg(feature = "std")] pub fn to_cow(&self) -> Cow<'a, str> { if self.is_needed() { Cow::from(self.to_string()) } else
} /// Converts this iterator into one that escapes all except unreserved characters. pub fn full(self) -> EscapeUri<'a, EscapeUriFull> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFull, } } /// Converts this iterator into one optimized for escaping query components. pub fn for_query(self) -> EscapeUri<'a, EscapeUriQuery> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriQuery, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_fragment(self) -> EscapeUri<'a, EscapeUriFragment> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriFragment, } } /// Converts this iterator into one optimized for escaping fragment components. pub fn for_authority(self) -> EscapeUri<'a, EscapeUriAuthority> { EscapeUri { iter: self.iter, state: self.state, needs_escape: EscapeUriAuthority, } } } impl<'a, X: NeedsEscape> Display for EscapeUri<'a, X> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.clone().try_for_each(|c| f.write_char(c)) } } impl<'a, X: NeedsEscape> FusedIterator for EscapeUri<'a, X> {} impl<'a, X: NeedsEscape> Iterator for EscapeUri<'a, X> { type Item = char; #[inline] fn next(&mut self) -> Option<char> { match self.state { EscapeUriState::Normal => match self.iter.next().copied() { Some(b) if X::escape_space_as_plus() && b == b''=> Some('+'), Some(b) if X::byte_needs_escape(b) => { self.state = EscapeUriState::OutputHighNibble(b); Some('%') } Some(b) => Some(b as char), None => None, }, EscapeUriState::OutputHighNibble(b) => { self.state = EscapeUriState::OutputLowNibble(b); let nibble = b >> 4; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } EscapeUriState::OutputLowNibble(b) => { self.state = EscapeUriState::Normal; let nibble = b & 0b1111; if nibble < 9 { Some((b'0' + nibble) as char) } else { Some((b'A' + nibble - 10) as char) } } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let n = self.iter.size_hint().0; (n, Some(n * 3)) } }
{ Cow::from(unsafe { from_utf8_unchecked(self.iter.as_slice()) }) }
conditional_block
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self { let mut server = xml_rpc::Server::default();
Server { server } } } impl Server { #[inline] pub fn register_value<T>(&mut self, name: impl Into<String>, msg: &'static str, handler: T) where T: Fn(xml_rpc::Params) -> Response<Value> + Send + Sync +'static, { self.server.register_value(name, move |args| { let response = handler(args); let response_info = ResponseInfo::from_response(response, msg); response_info.into() }) } #[inline] pub fn bind( self, uri: &SocketAddr, ) -> xml_rpc::error::Result< xml_rpc::server::BoundServer< impl Fn(&rouille::Request) -> rouille::Response + Send + Sync +'static, >, > { self.server.bind(uri) } } #[allow(clippy::needless_pass_by_value)] #[inline] fn on_missing(_params: xml_rpc::Params) -> xml_rpc::Response { let error_message = ResponseError::Client("Bad method requested".into()); let info = ResponseInfo::from_response_error(error_message); info.into() }
server.set_on_missing(on_missing);
random_line_split
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self { let mut server = xml_rpc::Server::default(); server.set_on_missing(on_missing); Server { server } } } impl Server { #[inline] pub fn register_value<T>(&mut self, name: impl Into<String>, msg: &'static str, handler: T) where T: Fn(xml_rpc::Params) -> Response<Value> + Send + Sync +'static, { self.server.register_value(name, move |args| { let response = handler(args); let response_info = ResponseInfo::from_response(response, msg); response_info.into() }) } #[inline] pub fn
( self, uri: &SocketAddr, ) -> xml_rpc::error::Result< xml_rpc::server::BoundServer< impl Fn(&rouille::Request) -> rouille::Response + Send + Sync +'static, >, > { self.server.bind(uri) } } #[allow(clippy::needless_pass_by_value)] #[inline] fn on_missing(_params: xml_rpc::Params) -> xml_rpc::Response { let error_message = ResponseError::Client("Bad method requested".into()); let info = ResponseInfo::from_response_error(error_message); info.into() }
bind
identifier_name
server.rs
use super::ResponseInfo; use std::net::SocketAddr; use xml_rpc::{self, rouille, Value}; use super::{Response, ResponseError}; pub struct Server { server: xml_rpc::Server, } impl Default for Server { fn default() -> Self
} impl Server { #[inline] pub fn register_value<T>(&mut self, name: impl Into<String>, msg: &'static str, handler: T) where T: Fn(xml_rpc::Params) -> Response<Value> + Send + Sync +'static, { self.server.register_value(name, move |args| { let response = handler(args); let response_info = ResponseInfo::from_response(response, msg); response_info.into() }) } #[inline] pub fn bind( self, uri: &SocketAddr, ) -> xml_rpc::error::Result< xml_rpc::server::BoundServer< impl Fn(&rouille::Request) -> rouille::Response + Send + Sync +'static, >, > { self.server.bind(uri) } } #[allow(clippy::needless_pass_by_value)] #[inline] fn on_missing(_params: xml_rpc::Params) -> xml_rpc::Response { let error_message = ResponseError::Client("Bad method requested".into()); let info = ResponseInfo::from_response_error(error_message); info.into() }
{ let mut server = xml_rpc::Server::default(); server.set_on_missing(on_missing); Server { server } }
identifier_body
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * 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 3 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, see <http://www.gnu.org/licenses/>. */ use std::cell::RefCell; use ncurses::*; use ui::color::COLOR_DEFAULT; use ui::rendered_line::MatchedLine; static WINDOW_HEIGHT: i32 = 2500; pub struct Content { pub window: WINDOW, pub state: RefCell<State>, } impl Content { pub fn new(width: i32) -> Content { Content { window: newpad(WINDOW_HEIGHT, width), state: RefCell::new(State::default()), } } pub fn clear(&self) { wclear(self.window); } pub fn
(&self, width: i32) { wresize(self.window, WINDOW_HEIGHT, width); wrefresh(self.window); } pub fn height(&self) -> i32 { let mut current_x: i32 = 0; let mut current_y: i32 = 0; getyx(self.window, &mut current_y, &mut current_x); current_y } pub fn calculate_height_change<F>(&self, callback: F) -> i32 where F: Fn() { let initial_height = self.height(); callback(); self.height() - initial_height } pub fn highlighted_line(&self) -> MatchedLine { let state = self.state.borrow(); MatchedLine::new(state.highlighted_line, state.highlighted_match) } } pub struct State { pub attributes: Vec<(usize, fn() -> attr_t)>, pub foreground: i16, pub background: i16, pub highlighted_line: usize, pub highlighted_match: usize, } impl State { pub fn default() -> State { State { attributes: vec![], foreground: COLOR_DEFAULT, background: COLOR_DEFAULT, highlighted_line: 0, highlighted_match: 0, } } pub fn remove_attribute(&mut self, attr_id: usize) { let index_option = self.attributes.iter().position(|cur| cur.0 == attr_id); if let Some(index) = index_option { self.attributes.remove(index); } } }
resize
identifier_name
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * 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 3 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, see <http://www.gnu.org/licenses/>. */ use std::cell::RefCell; use ncurses::*; use ui::color::COLOR_DEFAULT; use ui::rendered_line::MatchedLine; static WINDOW_HEIGHT: i32 = 2500; pub struct Content { pub window: WINDOW, pub state: RefCell<State>, } impl Content { pub fn new(width: i32) -> Content { Content { window: newpad(WINDOW_HEIGHT, width), state: RefCell::new(State::default()), } } pub fn clear(&self) { wclear(self.window); } pub fn resize(&self, width: i32) { wresize(self.window, WINDOW_HEIGHT, width); wrefresh(self.window); } pub fn height(&self) -> i32 { let mut current_x: i32 = 0; let mut current_y: i32 = 0; getyx(self.window, &mut current_y, &mut current_x); current_y } pub fn calculate_height_change<F>(&self, callback: F) -> i32 where F: Fn() { let initial_height = self.height(); callback(); self.height() - initial_height } pub fn highlighted_line(&self) -> MatchedLine { let state = self.state.borrow(); MatchedLine::new(state.highlighted_line, state.highlighted_match) } } pub struct State { pub attributes: Vec<(usize, fn() -> attr_t)>, pub foreground: i16, pub background: i16, pub highlighted_line: usize, pub highlighted_match: usize, } impl State { pub fn default() -> State { State { attributes: vec![], foreground: COLOR_DEFAULT, background: COLOR_DEFAULT, highlighted_line: 0, highlighted_match: 0, } } pub fn remove_attribute(&mut self, attr_id: usize) { let index_option = self.attributes.iter().position(|cur| cur.0 == attr_id); if let Some(index) = index_option
} }
{ self.attributes.remove(index); }
conditional_block
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * 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 3 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, see <http://www.gnu.org/licenses/>. */ use std::cell::RefCell; use ncurses::*; use ui::color::COLOR_DEFAULT; use ui::rendered_line::MatchedLine; static WINDOW_HEIGHT: i32 = 2500; pub struct Content { pub window: WINDOW, pub state: RefCell<State>, } impl Content { pub fn new(width: i32) -> Content { Content { window: newpad(WINDOW_HEIGHT, width), state: RefCell::new(State::default()), } } pub fn clear(&self) { wclear(self.window); } pub fn resize(&self, width: i32) { wresize(self.window, WINDOW_HEIGHT, width); wrefresh(self.window); } pub fn height(&self) -> i32 { let mut current_x: i32 = 0; let mut current_y: i32 = 0; getyx(self.window, &mut current_y, &mut current_x); current_y } pub fn calculate_height_change<F>(&self, callback: F) -> i32 where F: Fn() { let initial_height = self.height(); callback(); self.height() - initial_height } pub fn highlighted_line(&self) -> MatchedLine { let state = self.state.borrow(); MatchedLine::new(state.highlighted_line, state.highlighted_match) } } pub struct State { pub attributes: Vec<(usize, fn() -> attr_t)>, pub foreground: i16, pub background: i16, pub highlighted_line: usize, pub highlighted_match: usize, } impl State { pub fn default() -> State
pub fn remove_attribute(&mut self, attr_id: usize) { let index_option = self.attributes.iter().position(|cur| cur.0 == attr_id); if let Some(index) = index_option { self.attributes.remove(index); } } }
{ State { attributes: vec![], foreground: COLOR_DEFAULT, background: COLOR_DEFAULT, highlighted_line: 0, highlighted_match: 0, } }
identifier_body
content.rs
/** * Flow - Realtime log analyzer * Copyright (C) 2016 Daniel Mircea * * 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 3 of the License, or * (at your option) any later version.
* 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, see <http://www.gnu.org/licenses/>. */ use std::cell::RefCell; use ncurses::*; use ui::color::COLOR_DEFAULT; use ui::rendered_line::MatchedLine; static WINDOW_HEIGHT: i32 = 2500; pub struct Content { pub window: WINDOW, pub state: RefCell<State>, } impl Content { pub fn new(width: i32) -> Content { Content { window: newpad(WINDOW_HEIGHT, width), state: RefCell::new(State::default()), } } pub fn clear(&self) { wclear(self.window); } pub fn resize(&self, width: i32) { wresize(self.window, WINDOW_HEIGHT, width); wrefresh(self.window); } pub fn height(&self) -> i32 { let mut current_x: i32 = 0; let mut current_y: i32 = 0; getyx(self.window, &mut current_y, &mut current_x); current_y } pub fn calculate_height_change<F>(&self, callback: F) -> i32 where F: Fn() { let initial_height = self.height(); callback(); self.height() - initial_height } pub fn highlighted_line(&self) -> MatchedLine { let state = self.state.borrow(); MatchedLine::new(state.highlighted_line, state.highlighted_match) } } pub struct State { pub attributes: Vec<(usize, fn() -> attr_t)>, pub foreground: i16, pub background: i16, pub highlighted_line: usize, pub highlighted_match: usize, } impl State { pub fn default() -> State { State { attributes: vec![], foreground: COLOR_DEFAULT, background: COLOR_DEFAULT, highlighted_line: 0, highlighted_match: 0, } } pub fn remove_attribute(&mut self, attr_id: usize) { let index_option = self.attributes.iter().position(|cur| cur.0 == attr_id); if let Some(index) = index_option { self.attributes.remove(index); } } }
* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
output-slot-variants.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. #![allow(dead_code)] #![allow(unused_assignments)] #![allow(unknown_lints)] // pretty-expanded FIXME #23616 #![allow(dead_assignment)] #![allow(unused_variables)] #![feature(box_syntax)] struct A { a: isize, b: isize } struct Abox { a: Box<isize>, b: Box<isize> } fn ret_int_i() -> isize { 10 } fn ret_ext_i() -> Box<isize> { box 10 } fn ret_int_rec() -> A { A {a: 10, b: 10} } fn ret_ext_rec() -> Box<A> { box A {a: 10, b: 10} } fn ret_ext_mem() -> Abox { Abox {a: box 10, b: box 10} } fn ret_ext_ext_mem() -> Box<Abox> { box Abox{a: box 10, b: box 10} } pub fn main()
int_rec = ret_int_rec(); // non-initializing int_rec = ret_int_rec(); // non-initializing ext_rec = ret_ext_rec(); // initializing ext_rec = ret_ext_rec(); // non-initializing ext_rec = ret_ext_rec(); // non-initializing ext_mem = ret_ext_mem(); // initializing ext_mem = ret_ext_mem(); // non-initializing ext_mem = ret_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing }
{ let mut int_i: isize; let mut ext_i: Box<isize>; let mut int_rec: A; let mut ext_rec: Box<A>; let mut ext_mem: Abox; let mut ext_ext_mem: Box<Abox>; int_i = ret_int_i(); // initializing int_i = ret_int_i(); // non-initializing int_i = ret_int_i(); // non-initializing ext_i = ret_ext_i(); // initializing ext_i = ret_ext_i(); // non-initializing ext_i = ret_ext_i(); // non-initializing int_rec = ret_int_rec(); // initializing
identifier_body
output-slot-variants.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. #![allow(dead_code)] #![allow(unused_assignments)] #![allow(unknown_lints)] // pretty-expanded FIXME #23616 #![allow(dead_assignment)] #![allow(unused_variables)] #![feature(box_syntax)] struct A { a: isize, b: isize } struct Abox { a: Box<isize>, b: Box<isize> } fn ret_int_i() -> isize { 10 } fn ret_ext_i() -> Box<isize> { box 10 } fn ret_int_rec() -> A { A {a: 10, b: 10} } fn
() -> Box<A> { box A {a: 10, b: 10} } fn ret_ext_mem() -> Abox { Abox {a: box 10, b: box 10} } fn ret_ext_ext_mem() -> Box<Abox> { box Abox{a: box 10, b: box 10} } pub fn main() { let mut int_i: isize; let mut ext_i: Box<isize>; let mut int_rec: A; let mut ext_rec: Box<A>; let mut ext_mem: Abox; let mut ext_ext_mem: Box<Abox>; int_i = ret_int_i(); // initializing int_i = ret_int_i(); // non-initializing int_i = ret_int_i(); // non-initializing ext_i = ret_ext_i(); // initializing ext_i = ret_ext_i(); // non-initializing ext_i = ret_ext_i(); // non-initializing int_rec = ret_int_rec(); // initializing int_rec = ret_int_rec(); // non-initializing int_rec = ret_int_rec(); // non-initializing ext_rec = ret_ext_rec(); // initializing ext_rec = ret_ext_rec(); // non-initializing ext_rec = ret_ext_rec(); // non-initializing ext_mem = ret_ext_mem(); // initializing ext_mem = ret_ext_mem(); // non-initializing ext_mem = ret_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing }
ret_ext_rec
identifier_name
output-slot-variants.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. #![allow(dead_code)] #![allow(unused_assignments)] #![allow(unknown_lints)] // pretty-expanded FIXME #23616 #![allow(dead_assignment)] #![allow(unused_variables)] #![feature(box_syntax)] struct A { a: isize, b: isize } struct Abox { a: Box<isize>, b: Box<isize> } fn ret_int_i() -> isize { 10 } fn ret_ext_i() -> Box<isize> { box 10 } fn ret_int_rec() -> A { A {a: 10, b: 10} } fn ret_ext_rec() -> Box<A> { box A {a: 10, b: 10} } fn ret_ext_mem() -> Abox { Abox {a: box 10, b: box 10} } fn ret_ext_ext_mem() -> Box<Abox> { box Abox{a: box 10, b: box 10} } pub fn main() { let mut int_i: isize; let mut ext_i: Box<isize>; let mut int_rec: A; let mut ext_rec: Box<A>; let mut ext_mem: Abox;
int_i = ret_int_i(); // non-initializing int_i = ret_int_i(); // non-initializing ext_i = ret_ext_i(); // initializing ext_i = ret_ext_i(); // non-initializing ext_i = ret_ext_i(); // non-initializing int_rec = ret_int_rec(); // initializing int_rec = ret_int_rec(); // non-initializing int_rec = ret_int_rec(); // non-initializing ext_rec = ret_ext_rec(); // initializing ext_rec = ret_ext_rec(); // non-initializing ext_rec = ret_ext_rec(); // non-initializing ext_mem = ret_ext_mem(); // initializing ext_mem = ret_ext_mem(); // non-initializing ext_mem = ret_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing ext_ext_mem = ret_ext_ext_mem(); // non-initializing }
let mut ext_ext_mem: Box<Abox>; int_i = ret_int_i(); // initializing
random_line_split
snapshot_service.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
// 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/>. use ethcore::snapshot::{ManifestData, RestorationStatus, SnapshotService}; use bytes::Bytes; use bigint::hash::H256; use parking_lot::Mutex; /// Mocked snapshot service (used for sync info extensions). pub struct TestSnapshotService { status: Mutex<RestorationStatus>, } impl TestSnapshotService { /// Create a test snapshot service. Only the `status` function matters -- it'll /// return `Inactive` by default. pub fn new() -> Self { TestSnapshotService { status: Mutex::new(RestorationStatus::Inactive), } } /// Set the restoration status. pub fn set_status(&self, status: RestorationStatus) { *self.status.lock() = status; } } impl SnapshotService for TestSnapshotService { fn manifest(&self) -> Option<ManifestData> { None } fn supported_versions(&self) -> Option<(u64, u64)> { None } fn chunk(&self, _hash: H256) -> Option<Bytes> { None } fn status(&self) -> RestorationStatus { self.status.lock().clone() } fn begin_restore(&self, _manifest: ManifestData) { } fn abort_restore(&self) { } fn restore_state_chunk(&self, _hash: H256, _chunk: Bytes) { } fn restore_block_chunk(&self, _hash: H256, _chunk: Bytes) { } }
// (at your option) any later version.
random_line_split
snapshot_service.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/>. use ethcore::snapshot::{ManifestData, RestorationStatus, SnapshotService}; use bytes::Bytes; use bigint::hash::H256; use parking_lot::Mutex; /// Mocked snapshot service (used for sync info extensions). pub struct TestSnapshotService { status: Mutex<RestorationStatus>, } impl TestSnapshotService { /// Create a test snapshot service. Only the `status` function matters -- it'll /// return `Inactive` by default. pub fn new() -> Self { TestSnapshotService { status: Mutex::new(RestorationStatus::Inactive), } } /// Set the restoration status. pub fn set_status(&self, status: RestorationStatus) { *self.status.lock() = status; } } impl SnapshotService for TestSnapshotService { fn manifest(&self) -> Option<ManifestData> { None } fn supported_versions(&self) -> Option<(u64, u64)>
fn chunk(&self, _hash: H256) -> Option<Bytes> { None } fn status(&self) -> RestorationStatus { self.status.lock().clone() } fn begin_restore(&self, _manifest: ManifestData) { } fn abort_restore(&self) { } fn restore_state_chunk(&self, _hash: H256, _chunk: Bytes) { } fn restore_block_chunk(&self, _hash: H256, _chunk: Bytes) { } }
{ None }
identifier_body
snapshot_service.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/>. use ethcore::snapshot::{ManifestData, RestorationStatus, SnapshotService}; use bytes::Bytes; use bigint::hash::H256; use parking_lot::Mutex; /// Mocked snapshot service (used for sync info extensions). pub struct TestSnapshotService { status: Mutex<RestorationStatus>, } impl TestSnapshotService { /// Create a test snapshot service. Only the `status` function matters -- it'll /// return `Inactive` by default. pub fn new() -> Self { TestSnapshotService { status: Mutex::new(RestorationStatus::Inactive), } } /// Set the restoration status. pub fn set_status(&self, status: RestorationStatus) { *self.status.lock() = status; } } impl SnapshotService for TestSnapshotService { fn manifest(&self) -> Option<ManifestData> { None } fn supported_versions(&self) -> Option<(u64, u64)> { None } fn chunk(&self, _hash: H256) -> Option<Bytes> { None } fn status(&self) -> RestorationStatus { self.status.lock().clone() } fn begin_restore(&self, _manifest: ManifestData) { } fn
(&self) { } fn restore_state_chunk(&self, _hash: H256, _chunk: Bytes) { } fn restore_block_chunk(&self, _hash: H256, _chunk: Bytes) { } }
abort_restore
identifier_name
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); let mut moves = vec![]; board.generate_moves(&mut moves); for mv in moves { let reverse_move = board.do_move(mv.clone()); board.reverse_move(reverse_move); hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_eq!(start_hash, new_hash, "\nHash was not preserved after undoing move {} on \n{:?}", board.move_to_lan(&mv), board); } } #[test] fn
() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8"].iter() { let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_ne!(start_hash, new_hash); } #[test] fn repetitions_are_drawn() { let mut board = SjadamBoard::start_board(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8", "c1c3", "c8c6", "c3c1", "c6c8"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan("g1e3").unwrap(); board.do_move(mv); assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); } #[test] fn pawn_moves_can_repeat() { let mut board = SjadamBoard::start_board(); // There is no repetition from move 1, because of en passant for mv_str in ["e2e4", "e7e5", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); } #[test] fn san_lan_test() { for _ in 0..10 { tools::test_san_lan_with_random_game(SjadamBoard::start_board()); } }
repetitions_do_not_preserve_hash
identifier_name
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); let mut moves = vec![]; board.generate_moves(&mut moves); for mv in moves { let reverse_move = board.do_move(mv.clone()); board.reverse_move(reverse_move); hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_eq!(start_hash, new_hash, "\nHash was not preserved after undoing move {} on \n{:?}", board.move_to_lan(&mv), board); } } #[test] fn repetitions_do_not_preserve_hash() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8"].iter() { let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_ne!(start_hash, new_hash); } #[test] fn repetitions_are_drawn() { let mut board = SjadamBoard::start_board(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8", "c1c3", "c8c6", "c3c1", "c6c8"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan("g1e3").unwrap(); board.do_move(mv); assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); } #[test] fn pawn_moves_can_repeat() { let mut board = SjadamBoard::start_board();
for mv_str in ["e2e4", "e7e5", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); } #[test] fn san_lan_test() { for _ in 0..10 { tools::test_san_lan_with_random_game(SjadamBoard::start_board()); } }
// There is no repetition from move 1, because of en passant
random_line_split
sjadam_board_tests.rs
use board::sjadam::board::SjadamBoard; use board_game_traits::board::{GameResult, Board}; use pgn_traits::pgn::PgnBoard; use tests::tools; use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; #[test] fn hash_stays_equal() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); let mut moves = vec![]; board.generate_moves(&mut moves); for mv in moves { let reverse_move = board.do_move(mv.clone()); board.reverse_move(reverse_move); hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_eq!(start_hash, new_hash, "\nHash was not preserved after undoing move {} on \n{:?}", board.move_to_lan(&mv), board); } } #[test] fn repetitions_do_not_preserve_hash() { let mut board = SjadamBoard::start_board(); let mut hasher = DefaultHasher::new(); board.hash(&mut hasher); let start_hash = hasher.finish(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8"].iter() { let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } hasher = DefaultHasher::new(); board.hash(&mut hasher); let new_hash = hasher.finish(); assert_ne!(start_hash, new_hash); } #[test] fn repetitions_are_drawn()
#[test] fn pawn_moves_can_repeat() { let mut board = SjadamBoard::start_board(); // There is no repetition from move 1, because of en passant for mv_str in ["e2e4", "e7e5", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2", "c7e7", "e2c2", "e7c7", "c2e2"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); } #[test] fn san_lan_test() { for _ in 0..10 { tools::test_san_lan_with_random_game(SjadamBoard::start_board()); } }
{ let mut board = SjadamBoard::start_board(); for mv_str in ["c1c3", "c8c6", "c3c1", "c6c8", "c1c3", "c8c6", "c3c1", "c6c8"].iter() { assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan(mv_str).unwrap(); board.do_move(mv); } assert_eq!(board.game_result(), Some(GameResult::Draw), "Wrong game result for board:\n{:?}", board); let mv = board.move_from_lan("g1e3").unwrap(); board.do_move(mv); assert_eq!(board.game_result(), None, "Wrong game result for board:\n{:?}", board); }
identifier_body
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, CustomEventTypeId}; use js::jsapi::JSContext; use js::jsval::{JSVal, NullValue}; use servo_util::str::DOMString; use std::cell::Cell; #[dom_struct] pub struct CustomEvent { event: Event, detail: Cell<JSVal>, } impl CustomEventDerived for Event { fn is_customevent(&self) -> bool { *self.type_id() == CustomEventTypeId } } impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { event: Event::new_inherited(type_id), detail: Cell::new(NullValue()), } } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { reflect_dom_object(box CustomEvent::new_inherited(CustomEventTypeId), global, CustomEventBinding::Wrap) } pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> { let ev = CustomEvent::new_uninitialized(*global).root(); ev.InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{ Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail)) } } impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> { fn Detail(self, _cx: *mut JSContext) -> JSVal { self.detail.get() } fn InitCustomEvent(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool,
return; } self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching() {
random_line_split
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, CustomEventTypeId}; use js::jsapi::JSContext; use js::jsval::{JSVal, NullValue}; use servo_util::str::DOMString; use std::cell::Cell; #[dom_struct] pub struct CustomEvent { event: Event, detail: Cell<JSVal>, } impl CustomEventDerived for Event { fn is_customevent(&self) -> bool
} impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { event: Event::new_inherited(type_id), detail: Cell::new(NullValue()), } } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { reflect_dom_object(box CustomEvent::new_inherited(CustomEventTypeId), global, CustomEventBinding::Wrap) } pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> { let ev = CustomEvent::new_uninitialized(*global).root(); ev.InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{ Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail)) } } impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> { fn Detail(self, _cx: *mut JSContext) -> JSVal { self.detail.get() } fn InitCustomEvent(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching() { return; } self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
{ *self.type_id() == CustomEventTypeId }
identifier_body
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, CustomEventTypeId}; use js::jsapi::JSContext; use js::jsval::{JSVal, NullValue}; use servo_util::str::DOMString; use std::cell::Cell; #[dom_struct] pub struct CustomEvent { event: Event, detail: Cell<JSVal>, } impl CustomEventDerived for Event { fn is_customevent(&self) -> bool { *self.type_id() == CustomEventTypeId } } impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { event: Event::new_inherited(type_id), detail: Cell::new(NullValue()), } } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { reflect_dom_object(box CustomEvent::new_inherited(CustomEventTypeId), global, CustomEventBinding::Wrap) } pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> { let ev = CustomEvent::new_uninitialized(*global).root(); ev.InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{ Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail)) } } impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> { fn Detail(self, _cx: *mut JSContext) -> JSVal { self.detail.get() } fn
(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching() { return; } self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
InitCustomEvent
identifier_name
customevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived}; use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::event::{Event, EventTypeId, CustomEventTypeId}; use js::jsapi::JSContext; use js::jsval::{JSVal, NullValue}; use servo_util::str::DOMString; use std::cell::Cell; #[dom_struct] pub struct CustomEvent { event: Event, detail: Cell<JSVal>, } impl CustomEventDerived for Event { fn is_customevent(&self) -> bool { *self.type_id() == CustomEventTypeId } } impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { event: Event::new_inherited(type_id), detail: Cell::new(NullValue()), } } pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> { reflect_dom_object(box CustomEvent::new_inherited(CustomEventTypeId), global, CustomEventBinding::Wrap) } pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> { let ev = CustomEvent::new_uninitialized(*global).root(); ev.InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail); Temporary::from_rooted(*ev) } pub fn Constructor(global: &GlobalRef, type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{ Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail)) } } impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> { fn Detail(self, _cx: *mut JSContext) -> JSVal { self.detail.get() } fn InitCustomEvent(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.dispatching()
self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } } impl Reflectable for CustomEvent { fn reflector<'a>(&'a self) -> &'a Reflector { self.event.reflector() } }
{ return; }
conditional_block
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Symbol; use crate::utils::conf::Rename; declare_clippy_lint! { /// ### What it does /// Checks for imports that do not rename the item as specified /// in the `enforce-import-renames` config option. ///
/// /// ### Example /// An example clippy.toml configuration: /// ```toml /// # clippy.toml /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] /// ``` /// /// ```rust,ignore /// use serde_json::Value; /// ``` /// Use instead: /// ```rust,ignore /// use serde_json::Value as JsonValue; /// ``` pub MISSING_ENFORCED_IMPORT_RENAMES, restriction, "enforce import renames" } pub struct ImportRename { conf_renames: Vec<Rename>, renames: FxHashMap<DefId, Symbol>, } impl ImportRename { pub fn new(conf_renames: Vec<Rename>) -> Self { Self { conf_renames, renames: FxHashMap::default(), } } } impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]); impl LateLintPass<'_> for ImportRename { fn check_crate(&mut self, cx: &LateContext<'_>) { for Rename { path, rename } in &self.conf_renames { if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) { self.renames.insert(id, Symbol::intern(rename)); } } } fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present for nested imports let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';'); if let Some(snip) = snippet_opt(cx, span_without_semi); if let Some(import) = match snip.split_once(" as ") { None => Some(snip.as_str()), Some((import, rename)) => { if rename.trim() == &*name.as_str() { None } else { Some(import.trim()) } }, }; then { span_lint_and_sugg( cx, MISSING_ENFORCED_IMPORT_RENAMES, span_without_semi, "this import should be renamed", "try", format!( "{} as {}", import, name, ), Applicability::MachineApplicable, ); } } } }
/// ### Why is this bad? /// Consistency is important, if a project has defined import /// renames they should be followed. More practically, some item names are too /// vague outside of their defining scope this can enforce a more meaningful naming.
random_line_split
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Symbol; use crate::utils::conf::Rename; declare_clippy_lint! { /// ### What it does /// Checks for imports that do not rename the item as specified /// in the `enforce-import-renames` config option. /// /// ### Why is this bad? /// Consistency is important, if a project has defined import /// renames they should be followed. More practically, some item names are too /// vague outside of their defining scope this can enforce a more meaningful naming. /// /// ### Example /// An example clippy.toml configuration: /// ```toml /// # clippy.toml /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] /// ``` /// /// ```rust,ignore /// use serde_json::Value; /// ``` /// Use instead: /// ```rust,ignore /// use serde_json::Value as JsonValue; /// ``` pub MISSING_ENFORCED_IMPORT_RENAMES, restriction, "enforce import renames" } pub struct ImportRename { conf_renames: Vec<Rename>, renames: FxHashMap<DefId, Symbol>, } impl ImportRename { pub fn new(conf_renames: Vec<Rename>) -> Self { Self { conf_renames, renames: FxHashMap::default(), } } } impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]); impl LateLintPass<'_> for ImportRename { fn check_crate(&mut self, cx: &LateContext<'_>) { for Rename { path, rename } in &self.conf_renames { if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) { self.renames.insert(id, Symbol::intern(rename)); } } } fn
(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present for nested imports let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';'); if let Some(snip) = snippet_opt(cx, span_without_semi); if let Some(import) = match snip.split_once(" as ") { None => Some(snip.as_str()), Some((import, rename)) => { if rename.trim() == &*name.as_str() { None } else { Some(import.trim()) } }, }; then { span_lint_and_sugg( cx, MISSING_ENFORCED_IMPORT_RENAMES, span_without_semi, "this import should be renamed", "try", format!( "{} as {}", import, name, ), Applicability::MachineApplicable, ); } } } }
check_item
identifier_name
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Symbol; use crate::utils::conf::Rename; declare_clippy_lint! { /// ### What it does /// Checks for imports that do not rename the item as specified /// in the `enforce-import-renames` config option. /// /// ### Why is this bad? /// Consistency is important, if a project has defined import /// renames they should be followed. More practically, some item names are too /// vague outside of their defining scope this can enforce a more meaningful naming. /// /// ### Example /// An example clippy.toml configuration: /// ```toml /// # clippy.toml /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] /// ``` /// /// ```rust,ignore /// use serde_json::Value; /// ``` /// Use instead: /// ```rust,ignore /// use serde_json::Value as JsonValue; /// ``` pub MISSING_ENFORCED_IMPORT_RENAMES, restriction, "enforce import renames" } pub struct ImportRename { conf_renames: Vec<Rename>, renames: FxHashMap<DefId, Symbol>, } impl ImportRename { pub fn new(conf_renames: Vec<Rename>) -> Self { Self { conf_renames, renames: FxHashMap::default(), } } } impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]); impl LateLintPass<'_> for ImportRename { fn check_crate(&mut self, cx: &LateContext<'_>) { for Rename { path, rename } in &self.conf_renames { if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>())
} } fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present for nested imports let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';'); if let Some(snip) = snippet_opt(cx, span_without_semi); if let Some(import) = match snip.split_once(" as ") { None => Some(snip.as_str()), Some((import, rename)) => { if rename.trim() == &*name.as_str() { None } else { Some(import.trim()) } }, }; then { span_lint_and_sugg( cx, MISSING_ENFORCED_IMPORT_RENAMES, span_without_semi, "this import should be renamed", "try", format!( "{} as {}", import, name, ), Applicability::MachineApplicable, ); } } } }
{ self.renames.insert(id, Symbol::intern(rename)); }
conditional_block
missing_enforced_import_rename.rs
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::Applicability; use rustc_hir::{def::Res, def_id::DefId, Item, ItemKind, UseKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::Symbol; use crate::utils::conf::Rename; declare_clippy_lint! { /// ### What it does /// Checks for imports that do not rename the item as specified /// in the `enforce-import-renames` config option. /// /// ### Why is this bad? /// Consistency is important, if a project has defined import /// renames they should be followed. More practically, some item names are too /// vague outside of their defining scope this can enforce a more meaningful naming. /// /// ### Example /// An example clippy.toml configuration: /// ```toml /// # clippy.toml /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }] /// ``` /// /// ```rust,ignore /// use serde_json::Value; /// ``` /// Use instead: /// ```rust,ignore /// use serde_json::Value as JsonValue; /// ``` pub MISSING_ENFORCED_IMPORT_RENAMES, restriction, "enforce import renames" } pub struct ImportRename { conf_renames: Vec<Rename>, renames: FxHashMap<DefId, Symbol>, } impl ImportRename { pub fn new(conf_renames: Vec<Rename>) -> Self { Self { conf_renames, renames: FxHashMap::default(), } } } impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]); impl LateLintPass<'_> for ImportRename { fn check_crate(&mut self, cx: &LateContext<'_>)
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { if_chain! { if let ItemKind::Use(path, UseKind::Single) = &item.kind; if let Res::Def(_, id) = path.res; if let Some(name) = self.renames.get(&id); // Remove semicolon since it is not present for nested imports let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';'); if let Some(snip) = snippet_opt(cx, span_without_semi); if let Some(import) = match snip.split_once(" as ") { None => Some(snip.as_str()), Some((import, rename)) => { if rename.trim() == &*name.as_str() { None } else { Some(import.trim()) } }, }; then { span_lint_and_sugg( cx, MISSING_ENFORCED_IMPORT_RENAMES, span_without_semi, "this import should be renamed", "try", format!( "{} as {}", import, name, ), Applicability::MachineApplicable, ); } } } }
{ for Rename { path, rename } in &self.conf_renames { if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) { self.renames.insert(id, Symbol::intern(rename)); } } }
identifier_body
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib_wrapper! { pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass, SpinnerClass>) @extends Widget, @implements Buildable; match fn { get_type => || ffi::gtk_spinner_get_type(), } } impl Spinner { pub fn new() -> Spinner { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_spinner_new()).unsafe_cast() } } } impl Default for Spinner { fn default() -> Self { Self::new() } } pub const NONE_SPINNER: Option<&Spinner> = None; pub trait SpinnerExt:'static { fn start(&self); fn stop(&self); fn get_property_active(&self) -> bool; fn set_property_active(&self, active: bool); fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Spinner>> SpinnerExt for O { fn start(&self) { unsafe { ffi::gtk_spinner_start(self.as_ref().to_glib_none().0); } } fn stop(&self) { unsafe { ffi::gtk_spinner_stop(self.as_ref().to_glib_none().0); } } fn get_property_active(&self) -> bool { unsafe { let mut value = Value::from_type(<bool as StaticType>::static_type()); gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().unwrap() } } fn set_property_active(&self, active: bool) { unsafe { gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, Value::from(&active).to_glib_none().0); } } fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _, Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } } unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Spinner> { let f: &F = transmute(f); f(&Spinner::from_glib_borrow(this).unsafe_cast()) } impl fmt::Display for Spinner { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Spinner") } }
fmt
identifier_name
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib_wrapper! { pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass, SpinnerClass>) @extends Widget, @implements Buildable; match fn { get_type => || ffi::gtk_spinner_get_type(), } } impl Spinner { pub fn new() -> Spinner { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_spinner_new()).unsafe_cast() } } } impl Default for Spinner { fn default() -> Self { Self::new() } } pub const NONE_SPINNER: Option<&Spinner> = None; pub trait SpinnerExt:'static { fn start(&self); fn stop(&self); fn get_property_active(&self) -> bool; fn set_property_active(&self, active: bool); fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Spinner>> SpinnerExt for O { fn start(&self) { unsafe { ffi::gtk_spinner_start(self.as_ref().to_glib_none().0); } } fn stop(&self) { unsafe { ffi::gtk_spinner_stop(self.as_ref().to_glib_none().0); } } fn get_property_active(&self) -> bool { unsafe { let mut value = Value::from_type(<bool as StaticType>::static_type()); gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().unwrap() } } fn set_property_active(&self, active: bool) { unsafe { gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, Value::from(&active).to_glib_none().0); } } fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId
} unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Spinner> { let f: &F = transmute(f); f(&Spinner::from_glib_borrow(this).unsafe_cast()) } impl fmt::Display for Spinner { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Spinner") } }
{ unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _, Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } }
identifier_body
spinner.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Buildable; use Widget; use ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib_wrapper! { pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass, SpinnerClass>) @extends Widget, @implements Buildable; match fn { get_type => || ffi::gtk_spinner_get_type(), } } impl Spinner { pub fn new() -> Spinner { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_spinner_new()).unsafe_cast() } } }
} pub const NONE_SPINNER: Option<&Spinner> = None; pub trait SpinnerExt:'static { fn start(&self); fn stop(&self); fn get_property_active(&self) -> bool; fn set_property_active(&self, active: bool); fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Spinner>> SpinnerExt for O { fn start(&self) { unsafe { ffi::gtk_spinner_start(self.as_ref().to_glib_none().0); } } fn stop(&self) { unsafe { ffi::gtk_spinner_stop(self.as_ref().to_glib_none().0); } } fn get_property_active(&self) -> bool { unsafe { let mut value = Value::from_type(<bool as StaticType>::static_type()); gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().unwrap() } } fn set_property_active(&self, active: bool) { unsafe { gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, Value::from(&active).to_glib_none().0); } } fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _, Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } } unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Spinner> { let f: &F = transmute(f); f(&Spinner::from_glib_borrow(this).unsafe_cast()) } impl fmt::Display for Spinner { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Spinner") } }
impl Default for Spinner { fn default() -> Self { Self::new() }
random_line_split
method-argument-inference-associated-type.rs
// Copyright 2017 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. // run-pass pub struct
; pub struct ClientMap2; pub trait Service { type Request; fn call(&self, _req: Self::Request); } pub struct S<T>(T); impl Service for ClientMap { type Request = S<Box<Fn(i32)>>; fn call(&self, _req: Self::Request) {} } impl Service for ClientMap2 { type Request = (Box<Fn(i32)>,); fn call(&self, _req: Self::Request) {} } fn main() { ClientMap.call(S { 0: Box::new(|_msgid| ()) }); ClientMap.call(S(Box::new(|_msgid| ()))); ClientMap2.call((Box::new(|_msgid| ()),)); }
ClientMap
identifier_name
method-argument-inference-associated-type.rs
// Copyright 2017 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. // run-pass pub struct ClientMap; pub struct ClientMap2; pub trait Service { type Request; fn call(&self, _req: Self::Request); } pub struct S<T>(T); impl Service for ClientMap { type Request = S<Box<Fn(i32)>>; fn call(&self, _req: Self::Request) {} } impl Service for ClientMap2 { type Request = (Box<Fn(i32)>,); fn call(&self, _req: Self::Request) {} }
ClientMap.call(S(Box::new(|_msgid| ()))); ClientMap2.call((Box::new(|_msgid| ()),)); }
fn main() { ClientMap.call(S { 0: Box::new(|_msgid| ()) });
random_line_split
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, } impl Mover { fn new(m: f32, x: f32, y: f32) -> Self { let mass = m; let position = pt2(x, y); let velocity = vec2(0.0, 0.0); let acceleration = vec2(0.0, 0.0); Mover { position, velocity, acceleration, mass,
self.acceleration += f; } fn update(&mut self) { self.velocity += self.acceleration; self.position += self.velocity; self.acceleration *= 0.0; } fn attract(&self, m: &Mover) -> Vector2 { let mut force = self.position - m.position; // Calculate direction of force let mut distance = force.magnitude(); // Distance between objects distance = distance.max(5.0).min(25.0); // Limiting the distance to eliminate "extreme" results for very cose or very far object force = force.normalize(); // Normalize vector (distance doesn't matter, we just want this vector for direction) let g = 0.4; let strength = (g * self.mass * m.mass) / (distance * distance); // Calculate gravitational force magnitude force * strength // Get force vector --> magnitude * direction } fn display(&self, draw: &Draw) { draw.ellipse() .xy(self.position) .w_h(self.mass * 24.0, self.mass * 24.0) .rgba(0.0, 0.0, 0.0, 0.5) .stroke(BLACK) .stroke_weight(2.0); } } fn model(app: &App) -> Model { let rect = Rect::from_w_h(640.0, 360.0); app.new_window() .size(rect.w() as u32, rect.h() as u32) .view(view) .build() .unwrap(); let movers = (0..1000) .map(|_| { Mover::new( random_range(0.1f32, 2.0), random_range(rect.left(), rect.right()), random_range(rect.bottom(), rect.top()), ) }) .collect(); Model { movers } } fn update(_app: &App, m: &mut Model, _update: Update) { for i in 0..m.movers.len() { for j in 0..m.movers.len() { if i!= j { let force = m.movers[j].attract(&m.movers[i]); m.movers[i].apply_force(force); } } m.movers[i].update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); // Draw movers for mover in &m.movers { mover.display(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
} } fn apply_force(&mut self, force: Vector2) { let f = force / self.mass;
random_line_split
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, } impl Mover { fn new(m: f32, x: f32, y: f32) -> Self { let mass = m; let position = pt2(x, y); let velocity = vec2(0.0, 0.0); let acceleration = vec2(0.0, 0.0); Mover { position, velocity, acceleration, mass, } } fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn update(&mut self) { self.velocity += self.acceleration; self.position += self.velocity; self.acceleration *= 0.0; } fn attract(&self, m: &Mover) -> Vector2 { let mut force = self.position - m.position; // Calculate direction of force let mut distance = force.magnitude(); // Distance between objects distance = distance.max(5.0).min(25.0); // Limiting the distance to eliminate "extreme" results for very cose or very far object force = force.normalize(); // Normalize vector (distance doesn't matter, we just want this vector for direction) let g = 0.4; let strength = (g * self.mass * m.mass) / (distance * distance); // Calculate gravitational force magnitude force * strength // Get force vector --> magnitude * direction } fn display(&self, draw: &Draw) { draw.ellipse() .xy(self.position) .w_h(self.mass * 24.0, self.mass * 24.0) .rgba(0.0, 0.0, 0.0, 0.5) .stroke(BLACK) .stroke_weight(2.0); } } fn model(app: &App) -> Model { let rect = Rect::from_w_h(640.0, 360.0); app.new_window() .size(rect.w() as u32, rect.h() as u32) .view(view) .build() .unwrap(); let movers = (0..1000) .map(|_| { Mover::new( random_range(0.1f32, 2.0), random_range(rect.left(), rect.right()), random_range(rect.bottom(), rect.top()), ) }) .collect(); Model { movers } } fn update(_app: &App, m: &mut Model, _update: Update) { for i in 0..m.movers.len() { for j in 0..m.movers.len() { if i!= j
} m.movers[i].update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); // Draw movers for mover in &m.movers { mover.display(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
{ let force = m.movers[j].attract(&m.movers[i]); m.movers[i].apply_force(force); }
conditional_block
2_8_mutual_attraction.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 2-8: Mutual Attraction use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { movers: Vec<Mover>, } struct Mover { position: Point2, velocity: Vector2, acceleration: Vector2, mass: f32, } impl Mover { fn new(m: f32, x: f32, y: f32) -> Self { let mass = m; let position = pt2(x, y); let velocity = vec2(0.0, 0.0); let acceleration = vec2(0.0, 0.0); Mover { position, velocity, acceleration, mass, } } fn apply_force(&mut self, force: Vector2) { let f = force / self.mass; self.acceleration += f; } fn update(&mut self) { self.velocity += self.acceleration; self.position += self.velocity; self.acceleration *= 0.0; } fn attract(&self, m: &Mover) -> Vector2 { let mut force = self.position - m.position; // Calculate direction of force let mut distance = force.magnitude(); // Distance between objects distance = distance.max(5.0).min(25.0); // Limiting the distance to eliminate "extreme" results for very cose or very far object force = force.normalize(); // Normalize vector (distance doesn't matter, we just want this vector for direction) let g = 0.4; let strength = (g * self.mass * m.mass) / (distance * distance); // Calculate gravitational force magnitude force * strength // Get force vector --> magnitude * direction } fn display(&self, draw: &Draw) { draw.ellipse() .xy(self.position) .w_h(self.mass * 24.0, self.mass * 24.0) .rgba(0.0, 0.0, 0.0, 0.5) .stroke(BLACK) .stroke_weight(2.0); } } fn
(app: &App) -> Model { let rect = Rect::from_w_h(640.0, 360.0); app.new_window() .size(rect.w() as u32, rect.h() as u32) .view(view) .build() .unwrap(); let movers = (0..1000) .map(|_| { Mover::new( random_range(0.1f32, 2.0), random_range(rect.left(), rect.right()), random_range(rect.bottom(), rect.top()), ) }) .collect(); Model { movers } } fn update(_app: &App, m: &mut Model, _update: Update) { for i in 0..m.movers.len() { for j in 0..m.movers.len() { if i!= j { let force = m.movers[j].attract(&m.movers[i]); m.movers[i].apply_force(force); } } m.movers[i].update(); } } fn view(app: &App, m: &Model, frame: Frame) { // Begin drawing let draw = app.draw(); draw.background().color(WHITE); // Draw movers for mover in &m.movers { mover.display(&draw); } // Write the result of our drawing to the window's frame. draw.to_frame(app, &frame).unwrap(); }
model
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html #![cfg_attr(feature = "servo", feature(proc_macro))] #![deny(warnings)] // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate cfg_if; extern crate core; #[macro_use] extern crate cssparser; extern crate encoding; extern crate euclid; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever_atoms; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] extern crate nsstring_vendor as nsstring; extern crate num_integer; extern crate num_traits; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate phf; extern crate quickersort; extern crate rayon; extern crate rustc_serialize; extern crate selectors; #[cfg(feature = "servo")] extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; extern crate servo_config; extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_traits; extern crate time; #[allow(unused_extern_crates)] extern crate unicode_segmentation; pub mod animation; pub mod atomic_refcell; pub mod attr; pub mod bezier;
pub mod bloom; pub mod cache; pub mod cascade_info; pub mod context; pub mod custom_properties; pub mod data; pub mod dom; pub mod element_state; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod keyframes; pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod owning_handle; pub mod parallel; pub mod parser; pub mod restyle_hints; pub mod rule_tree; pub mod scoped_tls; pub mod selector_parser; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod sequential; pub mod sink; pub mod str; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; #[macro_use] #[allow(non_camel_case_types)] pub mod values; pub mod viewport; use std::fmt; use std::sync::Arc; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever_atoms::Prefix; #[cfg(feature = "servo")] pub use html5ever_atoms::LocalName; #[cfg(feature = "servo")] pub use html5ever_atoms::Namespace; /// The CSS properties supported by the style system. // Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( $name: ident )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Returns whether the two arguments point to the same value. #[inline] pub fn arc_ptr_eq<T:'static>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) } /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
random_line_split
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html #![cfg_attr(feature = "servo", feature(proc_macro))] #![deny(warnings)] // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate cfg_if; extern crate core; #[macro_use] extern crate cssparser; extern crate encoding; extern crate euclid; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever_atoms; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] extern crate nsstring_vendor as nsstring; extern crate num_integer; extern crate num_traits; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate phf; extern crate quickersort; extern crate rayon; extern crate rustc_serialize; extern crate selectors; #[cfg(feature = "servo")] extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; extern crate servo_config; extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_traits; extern crate time; #[allow(unused_extern_crates)] extern crate unicode_segmentation; pub mod animation; pub mod atomic_refcell; pub mod attr; pub mod bezier; pub mod bloom; pub mod cache; pub mod cascade_info; pub mod context; pub mod custom_properties; pub mod data; pub mod dom; pub mod element_state; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod keyframes; pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod owning_handle; pub mod parallel; pub mod parser; pub mod restyle_hints; pub mod rule_tree; pub mod scoped_tls; pub mod selector_parser; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod sequential; pub mod sink; pub mod str; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; #[macro_use] #[allow(non_camel_case_types)] pub mod values; pub mod viewport; use std::fmt; use std::sync::Arc; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever_atoms::Prefix; #[cfg(feature = "servo")] pub use html5ever_atoms::LocalName; #[cfg(feature = "servo")] pub use html5ever_atoms::Namespace; /// The CSS properties supported by the style system. // Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( $name: ident )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Returns whether the two arguments point to the same value. #[inline] pub fn arc_ptr_eq<T:'static>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) } /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty()
try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
{ return Ok(()); }
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html #![cfg_attr(feature = "servo", feature(proc_macro))] #![deny(warnings)] // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate cfg_if; extern crate core; #[macro_use] extern crate cssparser; extern crate encoding; extern crate euclid; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever_atoms; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] extern crate nsstring_vendor as nsstring; extern crate num_integer; extern crate num_traits; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate phf; extern crate quickersort; extern crate rayon; extern crate rustc_serialize; extern crate selectors; #[cfg(feature = "servo")] extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; extern crate servo_config; extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_traits; extern crate time; #[allow(unused_extern_crates)] extern crate unicode_segmentation; pub mod animation; pub mod atomic_refcell; pub mod attr; pub mod bezier; pub mod bloom; pub mod cache; pub mod cascade_info; pub mod context; pub mod custom_properties; pub mod data; pub mod dom; pub mod element_state; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod keyframes; pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod owning_handle; pub mod parallel; pub mod parser; pub mod restyle_hints; pub mod rule_tree; pub mod scoped_tls; pub mod selector_parser; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod sequential; pub mod sink; pub mod str; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; #[macro_use] #[allow(non_camel_case_types)] pub mod values; pub mod viewport; use std::fmt; use std::sync::Arc; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever_atoms::Prefix; #[cfg(feature = "servo")] pub use html5ever_atoms::LocalName; #[cfg(feature = "servo")] pub use html5ever_atoms::Namespace; /// The CSS properties supported by the style system. // Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( $name: ident )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Returns whether the two arguments point to the same value. #[inline] pub fn arc_ptr_eq<T:'static>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) } /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn
<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
serialize_comma_separated_list
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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html #![cfg_attr(feature = "servo", feature(proc_macro))] #![deny(warnings)] // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; #[allow(unused_extern_crates)] #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate cfg_if; extern crate core; #[macro_use] extern crate cssparser; extern crate encoding; extern crate euclid; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever_atoms; #[allow(unused_extern_crates)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] extern crate nsstring_vendor as nsstring; extern crate num_integer; extern crate num_traits; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate phf; extern crate quickersort; extern crate rayon; extern crate rustc_serialize; extern crate selectors; #[cfg(feature = "servo")] extern crate serde; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; extern crate servo_config; extern crate servo_url; extern crate smallvec; #[macro_use] extern crate style_traits; extern crate time; #[allow(unused_extern_crates)] extern crate unicode_segmentation; pub mod animation; pub mod atomic_refcell; pub mod attr; pub mod bezier; pub mod bloom; pub mod cache; pub mod cascade_info; pub mod context; pub mod custom_properties; pub mod data; pub mod dom; pub mod element_state; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod keyframes; pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod owning_handle; pub mod parallel; pub mod parser; pub mod restyle_hints; pub mod rule_tree; pub mod scoped_tls; pub mod selector_parser; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod sequential; pub mod sink; pub mod str; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; #[macro_use] #[allow(non_camel_case_types)] pub mod values; pub mod viewport; use std::fmt; use std::sync::Arc; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever_atoms::Prefix; #[cfg(feature = "servo")] pub use html5ever_atoms::LocalName; #[cfg(feature = "servo")] pub use html5ever_atoms::Namespace; /// The CSS properties supported by the style system. // Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( $name: ident )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Returns whether the two arguments point to the same value. #[inline] pub fn arc_ptr_eq<T:'static>(a: &Arc<T>, b: &Arc<T>) -> bool
/// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } try!(list[0].to_css(dest)); for item in list.iter().skip(1) { try!(write!(dest, ", ")); try!(item.to_css(dest)); } Ok(()) }
{ let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
identifier_body
htmlmapelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLMapElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct] pub struct HTMLMapElement { htmlelement: HTMLElement } impl HTMLMapElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLMapElement { HTMLMapElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLMapElement> { Node::reflect_node(box HTMLMapElement::new_inherited(localName, prefix, document), document, HTMLMapElementBinding::Wrap) } }
new
identifier_name
htmlmapelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLMapElementBinding; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use string_cache::Atom; #[dom_struct]
htmlelement: HTMLElement } impl HTMLMapElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLMapElement { HTMLMapElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLMapElement> { Node::reflect_node(box HTMLMapElement::new_inherited(localName, prefix, document), document, HTMLMapElementBinding::Wrap) } }
pub struct HTMLMapElement {
random_line_split
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are invoked by the server (when running a _flow_), should gather //! requested information and report back to the server. //! //! In RRG each action consists of three components: a request type, a response //! type and an action handler. Request and response types wrap lower-level //! Protocol Buffer messages sent by and to the GRR server. Handlers accept one //! instance of the corresponding request type and send some (zero or more) //! instances of the corresponding response type. #[cfg(target_os = "linux")] pub mod filesystems; #[cfg(target_family = "unix")] pub mod interfaces; pub mod metadata; pub mod startup; pub mod listdir; pub mod timeline; pub mod network; pub mod stat; pub mod insttime; pub mod memsize; pub mod finder; use crate::session::{self, Session, Task}; /// Abstraction for action-specific requests. /// /// Protocol Buffer messages received from the GRR server are not necessarily /// easy to work with and are hardly idiomatic to Rust. For this reason, actions /// should define more structured data types to represent their input and should /// be able to parse raw messages into them. pub trait Request: Sized { /// A type of the corresponding raw proto message. type Proto: prost::Message + Default; /// A method for converting raw proto messages into structured requests. fn from_proto(proto: Self::Proto) -> Result<Self, session::ParseError>; } /// Abstraction for action-specific responses. /// /// Like with the [`Request`] type, Protocol Buffer messages sent to the GRR /// server are very idiomatic to Rust. For this reason, actions should define /// more structured data types to represent responses and provide a way to /// convert them into the wire format. /// /// Note that because of the design flaws in the protocol, actions also need to /// specify a name of the wrapper RDF class from the Python implementation. /// Hopefully, one day this issue would be fixed and class names will not leak /// into the specification. /// /// [`Request`]: trait.Request.html pub trait Response: Sized { /// A name of the corresponding RDF class. const RDF_NAME: Option<&'static str>; /// A type of the corresponding raw proto message. type Proto: prost::Message + Default; /// A method for converting structured responses into raw proto messages. fn into_proto(self) -> Self::Proto; } impl Request for () { type Proto = (); fn
(unit: ()) -> Result<(), session::ParseError> { Ok(unit) } } impl Response for () { const RDF_NAME: Option<&'static str> = None; type Proto = (); fn into_proto(self) { } } /// Dispatches `task` to a handler appropriate for the given `action`. /// /// This method is a mapping between action names (as specified in the protocol) /// and action handlers (implemented on the agent). /// /// If the given action is unknown (or not yet implemented), this function will /// return an error. pub fn dispatch<'s, S>(action: &str, task: Task<'s, S>) -> session::Result<()> where S: Session, { match action { "SendStartupInfo" => task.execute(self::startup::handle), "GetClientInfo" => task.execute(self::metadata::handle), "ListDirectory" => task.execute(self::listdir::handle), "Timeline" => task.execute(self::timeline::handle), "ListNetworkConnections" => task.execute(self::network::handle), "GetFileStat" => task.execute(self::stat::handle), "GetInstallDate" => task.execute(self::insttime::handle), #[cfg(target_family = "unix")] "EnumerateInterfaces" => task.execute(self::interfaces::handle), #[cfg(target_os = "linux")] "EnumerateFilesystems" => task.execute(self::filesystems::handle), "GetMemorySize" => task.execute(self::memsize::handle), action => return Err(session::Error::Dispatch(String::from(action))), } }
from_proto
identifier_name
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are invoked by the server (when running a _flow_), should gather //! requested information and report back to the server. //! //! In RRG each action consists of three components: a request type, a response //! type and an action handler. Request and response types wrap lower-level //! Protocol Buffer messages sent by and to the GRR server. Handlers accept one //! instance of the corresponding request type and send some (zero or more) //! instances of the corresponding response type. #[cfg(target_os = "linux")] pub mod filesystems; #[cfg(target_family = "unix")] pub mod interfaces; pub mod metadata; pub mod startup; pub mod listdir; pub mod timeline; pub mod network; pub mod stat; pub mod insttime; pub mod memsize; pub mod finder; use crate::session::{self, Session, Task}; /// Abstraction for action-specific requests. /// /// Protocol Buffer messages received from the GRR server are not necessarily /// easy to work with and are hardly idiomatic to Rust. For this reason, actions /// should define more structured data types to represent their input and should /// be able to parse raw messages into them. pub trait Request: Sized { /// A type of the corresponding raw proto message. type Proto: prost::Message + Default; /// A method for converting raw proto messages into structured requests. fn from_proto(proto: Self::Proto) -> Result<Self, session::ParseError>; } /// Abstraction for action-specific responses. /// /// Like with the [`Request`] type, Protocol Buffer messages sent to the GRR /// server are very idiomatic to Rust. For this reason, actions should define /// more structured data types to represent responses and provide a way to /// convert them into the wire format. /// /// Note that because of the design flaws in the protocol, actions also need to /// specify a name of the wrapper RDF class from the Python implementation. /// Hopefully, one day this issue would be fixed and class names will not leak /// into the specification. /// /// [`Request`]: trait.Request.html pub trait Response: Sized { /// A name of the corresponding RDF class. const RDF_NAME: Option<&'static str>; /// A type of the corresponding raw proto message. type Proto: prost::Message + Default;
/// A method for converting structured responses into raw proto messages. fn into_proto(self) -> Self::Proto; } impl Request for () { type Proto = (); fn from_proto(unit: ()) -> Result<(), session::ParseError> { Ok(unit) } } impl Response for () { const RDF_NAME: Option<&'static str> = None; type Proto = (); fn into_proto(self) { } } /// Dispatches `task` to a handler appropriate for the given `action`. /// /// This method is a mapping between action names (as specified in the protocol) /// and action handlers (implemented on the agent). /// /// If the given action is unknown (or not yet implemented), this function will /// return an error. pub fn dispatch<'s, S>(action: &str, task: Task<'s, S>) -> session::Result<()> where S: Session, { match action { "SendStartupInfo" => task.execute(self::startup::handle), "GetClientInfo" => task.execute(self::metadata::handle), "ListDirectory" => task.execute(self::listdir::handle), "Timeline" => task.execute(self::timeline::handle), "ListNetworkConnections" => task.execute(self::network::handle), "GetFileStat" => task.execute(self::stat::handle), "GetInstallDate" => task.execute(self::insttime::handle), #[cfg(target_family = "unix")] "EnumerateInterfaces" => task.execute(self::interfaces::handle), #[cfg(target_os = "linux")] "EnumerateFilesystems" => task.execute(self::filesystems::handle), "GetMemorySize" => task.execute(self::memsize::handle), action => return Err(session::Error::Dispatch(String::from(action))), } }
random_line_split
mod.rs
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. //! Handlers and types for agent's actions. //! //! The basic functionality that a GRR agent exposes is called an _action_. //! Actions are invoked by the server (when running a _flow_), should gather //! requested information and report back to the server. //! //! In RRG each action consists of three components: a request type, a response //! type and an action handler. Request and response types wrap lower-level //! Protocol Buffer messages sent by and to the GRR server. Handlers accept one //! instance of the corresponding request type and send some (zero or more) //! instances of the corresponding response type. #[cfg(target_os = "linux")] pub mod filesystems; #[cfg(target_family = "unix")] pub mod interfaces; pub mod metadata; pub mod startup; pub mod listdir; pub mod timeline; pub mod network; pub mod stat; pub mod insttime; pub mod memsize; pub mod finder; use crate::session::{self, Session, Task}; /// Abstraction for action-specific requests. /// /// Protocol Buffer messages received from the GRR server are not necessarily /// easy to work with and are hardly idiomatic to Rust. For this reason, actions /// should define more structured data types to represent their input and should /// be able to parse raw messages into them. pub trait Request: Sized { /// A type of the corresponding raw proto message. type Proto: prost::Message + Default; /// A method for converting raw proto messages into structured requests. fn from_proto(proto: Self::Proto) -> Result<Self, session::ParseError>; } /// Abstraction for action-specific responses. /// /// Like with the [`Request`] type, Protocol Buffer messages sent to the GRR /// server are very idiomatic to Rust. For this reason, actions should define /// more structured data types to represent responses and provide a way to /// convert them into the wire format. /// /// Note that because of the design flaws in the protocol, actions also need to /// specify a name of the wrapper RDF class from the Python implementation. /// Hopefully, one day this issue would be fixed and class names will not leak /// into the specification. /// /// [`Request`]: trait.Request.html pub trait Response: Sized { /// A name of the corresponding RDF class. const RDF_NAME: Option<&'static str>; /// A type of the corresponding raw proto message. type Proto: prost::Message + Default; /// A method for converting structured responses into raw proto messages. fn into_proto(self) -> Self::Proto; } impl Request for () { type Proto = (); fn from_proto(unit: ()) -> Result<(), session::ParseError>
} impl Response for () { const RDF_NAME: Option<&'static str> = None; type Proto = (); fn into_proto(self) { } } /// Dispatches `task` to a handler appropriate for the given `action`. /// /// This method is a mapping between action names (as specified in the protocol) /// and action handlers (implemented on the agent). /// /// If the given action is unknown (or not yet implemented), this function will /// return an error. pub fn dispatch<'s, S>(action: &str, task: Task<'s, S>) -> session::Result<()> where S: Session, { match action { "SendStartupInfo" => task.execute(self::startup::handle), "GetClientInfo" => task.execute(self::metadata::handle), "ListDirectory" => task.execute(self::listdir::handle), "Timeline" => task.execute(self::timeline::handle), "ListNetworkConnections" => task.execute(self::network::handle), "GetFileStat" => task.execute(self::stat::handle), "GetInstallDate" => task.execute(self::insttime::handle), #[cfg(target_family = "unix")] "EnumerateInterfaces" => task.execute(self::interfaces::handle), #[cfg(target_os = "linux")] "EnumerateFilesystems" => task.execute(self::filesystems::handle), "GetMemorySize" => task.execute(self::memsize::handle), action => return Err(session::Error::Dispatch(String::from(action))), } }
{ Ok(unit) }
identifier_body
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { data: Box<[u8]>, } impl CString { /// Creates a new C style string /// /// This will ensure that no null byte is present in the string or return /// and error if that's the case. It will also add the final null byte. pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, ()> { let mut v = t.into(); for b in &v { if *b == 0 { return Err(()); } } v.push(0); Ok(CString { data: v.into_boxed_slice(), }) } /// Return the raw representation of the string without the trailing null /// byte pub fn as_bytes(&self) -> &[u8] { &self.data[..self.data.len() - 1] }
pub fn as_bytes_with_nul(&self) -> &[u8] { &*self.data } }
/// Return the raw representation of the string. /// /// This buffer is guaranteed without intermediate null bytes and includes /// the trailing null byte.
random_line_split
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { data: Box<[u8]>, } impl CString { /// Creates a new C style string /// /// This will ensure that no null byte is present in the string or return /// and error if that's the case. It will also add the final null byte. pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, ()> { let mut v = t.into(); for b in &v { if *b == 0 { return Err(()); } } v.push(0); Ok(CString { data: v.into_boxed_slice(), }) } /// Return the raw representation of the string without the trailing null /// byte pub fn as_bytes(&self) -> &[u8] { &self.data[..self.data.len() - 1] } /// Return the raw representation of the string. /// /// This buffer is guaranteed without intermediate null bytes and includes /// the trailing null byte. pub fn
(&self) -> &[u8] { &*self.data } }
as_bytes_with_nul
identifier_name
ffi.rs
//! Utilities related to FFI bindings. use vec::Vec; use boxed::Box; #[derive(Clone)] /// Represents an owned C style string /// /// This type generates compatible C-strings from Rust. It guarantees that /// there is no null bytes in the string and that the string is ended by a null /// byte. pub struct CString { data: Box<[u8]>, } impl CString { /// Creates a new C style string /// /// This will ensure that no null byte is present in the string or return /// and error if that's the case. It will also add the final null byte. pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, ()> { let mut v = t.into(); for b in &v { if *b == 0
} v.push(0); Ok(CString { data: v.into_boxed_slice(), }) } /// Return the raw representation of the string without the trailing null /// byte pub fn as_bytes(&self) -> &[u8] { &self.data[..self.data.len() - 1] } /// Return the raw representation of the string. /// /// This buffer is guaranteed without intermediate null bytes and includes /// the trailing null byte. pub fn as_bytes_with_nul(&self) -> &[u8] { &*self.data } }
{ return Err(()); }
conditional_block
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *self { Error::InvalidCommand(ref cmd) => write!(f, "invalid command: {}", cmd), Error::TooFewArguments(ref cmd, ref expected, ref actual) => write!(f, "command {} expects {} arguments, got {}", cmd, expected, actual), Error::NoCommand => write!(f, "no command given"), Error::UnknownError(ref msg) => write!(f, "unexpected error: {}", msg), } } } impl Error { pub fn
<S: ToString>(msg: S) -> Error { Error::UnknownError(msg.to_string()) } } type Result<V> = std::result::Result<V, Error>; #[derive(Debug, PartialEq, Eq)] pub enum Command { Init, ListKeys, PutString(String, String), Drop(String), CreateEmptyList(String), PushListValue(String, String), PopListValue(String), ClearList(String), Get(String), } fn assert_length(v: &Vec<String>, l: usize) -> Result<&Vec<String>> { if v.len() >= l { Ok(v) } else { Err(Error::TooFewArguments(v[0].clone(), l, v.len())) } } impl FromStr for Command { type Err = Error; fn from_str(s: &str) -> Result<Self> { let split = s.split(' ').map(|x| x.to_string()).collect(); Command::from_strings(split) } } impl Command { pub fn from_strings(strings: Vec<String>) -> Result<Self> { if strings.len() == 0 { return Err(Error::NoCommand); } match strings[0].as_str() { "init" => Ok(Command::Init), "put" => assert_length(&strings, 3).map(|v| Command::PutString(v[1].clone(), v[2..].join(" "))), "drop" => assert_length(&strings, 2).map(|v| Command::Drop(v[1].clone())), "emptyList" => assert_length(&strings, 2).map(|v| Command::CreateEmptyList(v[1].clone())), "push" => assert_length(&strings, 3).map(|v| Command::PushListValue(v[1].clone(), v[2..].join(" "))), "pop" => assert_length(&strings, 2).map(|v| Command::PopListValue(v[1].clone())), "clear" => assert_length(&strings, 2).map(|v| Command::ClearList(v[1].clone())), "get" => assert_length(&strings, 2).map(|v| Command::Get(v[1].clone())), "ls" => Ok(Command::ListKeys), cmd => Err(Error::InvalidCommand(cmd.to_string())) } } pub fn is_change(&self) -> bool { match *self { Command::Init | Command::PutString(..) | Command::Drop(..) | Command::CreateEmptyList(..) | Command::PushListValue(..) | Command::PopListValue(..) | Command::ClearList(..) => true, _ => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_init() { let cmd = Command::from_str("init").unwrap(); assert_eq!(cmd, Command::Init); } #[test] fn test_put_string() { let cmd = Command::from_str("put bla gna").unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] fn test_empty() { let err = Command::from_strings(Vec::new()).err().unwrap(); if let Error::NoCommand = err {} else { assert!(false); } } #[test] fn test_put_string_wrong_fmt() { let err = Command::from_str("put bla,gna").err().unwrap(); if let Error::TooFewArguments(_, expected, actual) = err { assert_eq!(expected, 3); assert_eq!(actual, 2); } else { assert!(false); } } #[test] fn test_invalid_command() { let err = Command::from_str("invalid test").err().unwrap(); if let Error::InvalidCommand(cmd) = err { assert_eq!(cmd, "invalid".to_string()); } else { assert!(false); } } #[test] fn test_from_vec() { let strings = "put bla gna".split(' ').map(|x| x.to_string()).collect(); let cmd = Command::from_strings(strings).unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] #[should_panic] fn test_fail() { Command::from_str("invalid test").unwrap(); } }
unknown
identifier_name
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *self { Error::InvalidCommand(ref cmd) => write!(f, "invalid command: {}", cmd), Error::TooFewArguments(ref cmd, ref expected, ref actual) => write!(f, "command {} expects {} arguments, got {}", cmd, expected, actual), Error::NoCommand => write!(f, "no command given"), Error::UnknownError(ref msg) => write!(f, "unexpected error: {}", msg), } } } impl Error { pub fn unknown<S: ToString>(msg: S) -> Error { Error::UnknownError(msg.to_string()) } } type Result<V> = std::result::Result<V, Error>; #[derive(Debug, PartialEq, Eq)] pub enum Command { Init, ListKeys, PutString(String, String), Drop(String), CreateEmptyList(String), PushListValue(String, String), PopListValue(String), ClearList(String), Get(String), } fn assert_length(v: &Vec<String>, l: usize) -> Result<&Vec<String>> { if v.len() >= l { Ok(v) } else { Err(Error::TooFewArguments(v[0].clone(), l, v.len())) } } impl FromStr for Command { type Err = Error; fn from_str(s: &str) -> Result<Self> { let split = s.split(' ').map(|x| x.to_string()).collect(); Command::from_strings(split) } } impl Command { pub fn from_strings(strings: Vec<String>) -> Result<Self> { if strings.len() == 0 { return Err(Error::NoCommand); } match strings[0].as_str() { "init" => Ok(Command::Init), "put" => assert_length(&strings, 3).map(|v| Command::PutString(v[1].clone(), v[2..].join(" "))), "drop" => assert_length(&strings, 2).map(|v| Command::Drop(v[1].clone())), "emptyList" => assert_length(&strings, 2).map(|v| Command::CreateEmptyList(v[1].clone())), "push" => assert_length(&strings, 3).map(|v| Command::PushListValue(v[1].clone(), v[2..].join(" "))), "pop" => assert_length(&strings, 2).map(|v| Command::PopListValue(v[1].clone())), "clear" => assert_length(&strings, 2).map(|v| Command::ClearList(v[1].clone())), "get" => assert_length(&strings, 2).map(|v| Command::Get(v[1].clone())), "ls" => Ok(Command::ListKeys), cmd => Err(Error::InvalidCommand(cmd.to_string())) } } pub fn is_change(&self) -> bool { match *self { Command::Init | Command::PutString(..) | Command::Drop(..) | Command::CreateEmptyList(..) | Command::PushListValue(..) | Command::PopListValue(..) | Command::ClearList(..) => true, _ => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_init() {
assert_eq!(cmd, Command::Init); } #[test] fn test_put_string() { let cmd = Command::from_str("put bla gna").unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] fn test_empty() { let err = Command::from_strings(Vec::new()).err().unwrap(); if let Error::NoCommand = err {} else { assert!(false); } } #[test] fn test_put_string_wrong_fmt() { let err = Command::from_str("put bla,gna").err().unwrap(); if let Error::TooFewArguments(_, expected, actual) = err { assert_eq!(expected, 3); assert_eq!(actual, 2); } else { assert!(false); } } #[test] fn test_invalid_command() { let err = Command::from_str("invalid test").err().unwrap(); if let Error::InvalidCommand(cmd) = err { assert_eq!(cmd, "invalid".to_string()); } else { assert!(false); } } #[test] fn test_from_vec() { let strings = "put bla gna".split(' ').map(|x| x.to_string()).collect(); let cmd = Command::from_strings(strings).unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] #[should_panic] fn test_fail() { Command::from_str("invalid test").unwrap(); } }
let cmd = Command::from_str("init").unwrap();
random_line_split
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *self { Error::InvalidCommand(ref cmd) => write!(f, "invalid command: {}", cmd), Error::TooFewArguments(ref cmd, ref expected, ref actual) => write!(f, "command {} expects {} arguments, got {}", cmd, expected, actual), Error::NoCommand => write!(f, "no command given"), Error::UnknownError(ref msg) => write!(f, "unexpected error: {}", msg), } } } impl Error { pub fn unknown<S: ToString>(msg: S) -> Error { Error::UnknownError(msg.to_string()) } } type Result<V> = std::result::Result<V, Error>; #[derive(Debug, PartialEq, Eq)] pub enum Command { Init, ListKeys, PutString(String, String), Drop(String), CreateEmptyList(String), PushListValue(String, String), PopListValue(String), ClearList(String), Get(String), } fn assert_length(v: &Vec<String>, l: usize) -> Result<&Vec<String>> { if v.len() >= l { Ok(v) } else { Err(Error::TooFewArguments(v[0].clone(), l, v.len())) } } impl FromStr for Command { type Err = Error; fn from_str(s: &str) -> Result<Self> { let split = s.split(' ').map(|x| x.to_string()).collect(); Command::from_strings(split) } } impl Command { pub fn from_strings(strings: Vec<String>) -> Result<Self> { if strings.len() == 0 { return Err(Error::NoCommand); } match strings[0].as_str() { "init" => Ok(Command::Init), "put" => assert_length(&strings, 3).map(|v| Command::PutString(v[1].clone(), v[2..].join(" "))), "drop" => assert_length(&strings, 2).map(|v| Command::Drop(v[1].clone())), "emptyList" => assert_length(&strings, 2).map(|v| Command::CreateEmptyList(v[1].clone())), "push" => assert_length(&strings, 3).map(|v| Command::PushListValue(v[1].clone(), v[2..].join(" "))), "pop" => assert_length(&strings, 2).map(|v| Command::PopListValue(v[1].clone())), "clear" => assert_length(&strings, 2).map(|v| Command::ClearList(v[1].clone())), "get" => assert_length(&strings, 2).map(|v| Command::Get(v[1].clone())), "ls" => Ok(Command::ListKeys), cmd => Err(Error::InvalidCommand(cmd.to_string())) } } pub fn is_change(&self) -> bool { match *self { Command::Init | Command::PutString(..) | Command::Drop(..) | Command::CreateEmptyList(..) | Command::PushListValue(..) | Command::PopListValue(..) | Command::ClearList(..) => true, _ => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_init() { let cmd = Command::from_str("init").unwrap(); assert_eq!(cmd, Command::Init); } #[test] fn test_put_string() { let cmd = Command::from_str("put bla gna").unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] fn test_empty() { let err = Command::from_strings(Vec::new()).err().unwrap(); if let Error::NoCommand = err {} else
} #[test] fn test_put_string_wrong_fmt() { let err = Command::from_str("put bla,gna").err().unwrap(); if let Error::TooFewArguments(_, expected, actual) = err { assert_eq!(expected, 3); assert_eq!(actual, 2); } else { assert!(false); } } #[test] fn test_invalid_command() { let err = Command::from_str("invalid test").err().unwrap(); if let Error::InvalidCommand(cmd) = err { assert_eq!(cmd, "invalid".to_string()); } else { assert!(false); } } #[test] fn test_from_vec() { let strings = "put bla gna".split(' ').map(|x| x.to_string()).collect(); let cmd = Command::from_strings(strings).unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] #[should_panic] fn test_fail() { Command::from_str("invalid test").unwrap(); } }
{ assert!(false); }
conditional_block
cmd.rs
use std; use std::fmt::Display; use std::fmt::Formatter; use std::str::FromStr; #[derive(Debug)] pub enum Error { InvalidCommand(String), TooFewArguments(String, usize, usize), NoCommand, UnknownError(String), } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match *self { Error::InvalidCommand(ref cmd) => write!(f, "invalid command: {}", cmd), Error::TooFewArguments(ref cmd, ref expected, ref actual) => write!(f, "command {} expects {} arguments, got {}", cmd, expected, actual), Error::NoCommand => write!(f, "no command given"), Error::UnknownError(ref msg) => write!(f, "unexpected error: {}", msg), } } } impl Error { pub fn unknown<S: ToString>(msg: S) -> Error { Error::UnknownError(msg.to_string()) } } type Result<V> = std::result::Result<V, Error>; #[derive(Debug, PartialEq, Eq)] pub enum Command { Init, ListKeys, PutString(String, String), Drop(String), CreateEmptyList(String), PushListValue(String, String), PopListValue(String), ClearList(String), Get(String), } fn assert_length(v: &Vec<String>, l: usize) -> Result<&Vec<String>> { if v.len() >= l { Ok(v) } else { Err(Error::TooFewArguments(v[0].clone(), l, v.len())) } } impl FromStr for Command { type Err = Error; fn from_str(s: &str) -> Result<Self> { let split = s.split(' ').map(|x| x.to_string()).collect(); Command::from_strings(split) } } impl Command { pub fn from_strings(strings: Vec<String>) -> Result<Self> { if strings.len() == 0 { return Err(Error::NoCommand); } match strings[0].as_str() { "init" => Ok(Command::Init), "put" => assert_length(&strings, 3).map(|v| Command::PutString(v[1].clone(), v[2..].join(" "))), "drop" => assert_length(&strings, 2).map(|v| Command::Drop(v[1].clone())), "emptyList" => assert_length(&strings, 2).map(|v| Command::CreateEmptyList(v[1].clone())), "push" => assert_length(&strings, 3).map(|v| Command::PushListValue(v[1].clone(), v[2..].join(" "))), "pop" => assert_length(&strings, 2).map(|v| Command::PopListValue(v[1].clone())), "clear" => assert_length(&strings, 2).map(|v| Command::ClearList(v[1].clone())), "get" => assert_length(&strings, 2).map(|v| Command::Get(v[1].clone())), "ls" => Ok(Command::ListKeys), cmd => Err(Error::InvalidCommand(cmd.to_string())) } } pub fn is_change(&self) -> bool { match *self { Command::Init | Command::PutString(..) | Command::Drop(..) | Command::CreateEmptyList(..) | Command::PushListValue(..) | Command::PopListValue(..) | Command::ClearList(..) => true, _ => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_init() { let cmd = Command::from_str("init").unwrap(); assert_eq!(cmd, Command::Init); } #[test] fn test_put_string() { let cmd = Command::from_str("put bla gna").unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] fn test_empty() { let err = Command::from_strings(Vec::new()).err().unwrap(); if let Error::NoCommand = err {} else { assert!(false); } } #[test] fn test_put_string_wrong_fmt() { let err = Command::from_str("put bla,gna").err().unwrap(); if let Error::TooFewArguments(_, expected, actual) = err { assert_eq!(expected, 3); assert_eq!(actual, 2); } else { assert!(false); } } #[test] fn test_invalid_command() { let err = Command::from_str("invalid test").err().unwrap(); if let Error::InvalidCommand(cmd) = err { assert_eq!(cmd, "invalid".to_string()); } else { assert!(false); } } #[test] fn test_from_vec() { let strings = "put bla gna".split(' ').map(|x| x.to_string()).collect(); let cmd = Command::from_strings(strings).unwrap(); assert_eq!(cmd, Command::PutString("bla".to_string(), "gna".to_string())); } #[test] #[should_panic] fn test_fail()
}
{ Command::from_str("invalid test").unwrap(); }
identifier_body
config.rs
extern crate serde; extern crate serde_json; use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct
{ pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Result<Config, io::Error> { // TEST SECTION let point = ConfigFile { file_path: "data".to_string(), auth_file: "auth_file".to_string() }; let serialized = serde_json::to_string(&point).unwrap(); println!("{}", serialized); let deserialized: ConfigFile = serde_json::from_str(&serialized).unwrap(); println!("{:?}", deserialized); // END TEST SECTION let mut file = try!(File::open(path)); let mut data = String::new(); try!(file.read_to_string(& mut data)); let deserialized: ConfigFile = try!( serde_json::from_str(&data).map_err(|err| { io::Error::new(io::ErrorKind::Other, err.description()) }) ); let mut auth_file = try!(File::open(deserialized.auth_file)); let mut auth_code = String::new(); try!(auth_file.read_to_string(& mut auth_code)); Ok(Config { file_path: deserialized.file_path, auth: auth_code, }) } }
Config
identifier_name
config.rs
extern crate serde; extern crate serde_json; use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct Config { pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Result<Config, io::Error>
let mut auth_file = try!(File::open(deserialized.auth_file)); let mut auth_code = String::new(); try!(auth_file.read_to_string(& mut auth_code)); Ok(Config { file_path: deserialized.file_path, auth: auth_code, }) } }
{ // TEST SECTION let point = ConfigFile { file_path: "data".to_string(), auth_file: "auth_file".to_string() }; let serialized = serde_json::to_string(&point).unwrap(); println!("{}", serialized); let deserialized: ConfigFile = serde_json::from_str(&serialized).unwrap(); println!("{:?}", deserialized); // END TEST SECTION let mut file = try!(File::open(path)); let mut data = String::new(); try!(file.read_to_string(& mut data)); let deserialized: ConfigFile = try!( serde_json::from_str(&data).map_err(|err| { io::Error::new(io::ErrorKind::Other, err.description()) }) );
identifier_body
config.rs
extern crate serde; extern crate serde_json;
use std::io; use std::io::Read; use std::fs::File; use std::error::Error; include!(concat!(env!("OUT_DIR"), "/config.rs")); #[derive(Debug)] pub struct Config { pub file_path: String, pub auth: String, } impl Config { pub fn load_from_file(path: &str) -> Result<Config, io::Error> { // TEST SECTION let point = ConfigFile { file_path: "data".to_string(), auth_file: "auth_file".to_string() }; let serialized = serde_json::to_string(&point).unwrap(); println!("{}", serialized); let deserialized: ConfigFile = serde_json::from_str(&serialized).unwrap(); println!("{:?}", deserialized); // END TEST SECTION let mut file = try!(File::open(path)); let mut data = String::new(); try!(file.read_to_string(& mut data)); let deserialized: ConfigFile = try!( serde_json::from_str(&data).map_err(|err| { io::Error::new(io::ErrorKind::Other, err.description()) }) ); let mut auth_file = try!(File::open(deserialized.auth_file)); let mut auth_code = String::new(); try!(auth_file.read_to_string(& mut auth_code)); Ok(Config { file_path: deserialized.file_path, auth: auth_code, }) } }
random_line_split
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kinds.push($kind); )+ map.insert($id, ($name, kinds)); );+ map }} } #[allow(clippy::zero_prefixed_literal)] fn main() { let mut args = std::env::args().skip(1); let path = args.next().expect("Need path to save as first arg"); let save = rgen3_save::Save::load_from_file(&path).unwrap(); let SaveSections { team, pc_boxes,.. } = save.sections(); let pokemap = include!("../../poke.incl"); println!("== Team =="); for pokemon in team { print_pokemon(pokemon, &pokemap); } println!("== PC =="); for pbox in pc_boxes { for slot in &pbox.slots { if let Some(pokemon) = slot { print_pokemon(pokemon, &pokemap); } } } } fn print_pokemon(pokemon: &Pokemon, pokemap: &HashMap<u16, (&'static str, Vec<&'static str>)>)
println!("hp: {}", evc.hp); println!("atk: {}", evc.attack); println!("def: {}", evc.defense); println!("spd: {}", evc.speed); println!("sp atk: {}", evc.sp_attack); println!("sp def: {}", evc.sp_defense); println!( "total: {}/510", u16::from(evc.hp) + u16::from(evc.attack) + u16::from(evc.defense) + u16::from(evc.speed) + u16::from(evc.sp_attack) + u16::from(evc.sp_defense) ); println!("-") }
{ let unk_string: String; let unk_vec = vec![""]; let (name, kinds) = match pokemap.get(&pokemon.data.growth.species) { Some((name, kinds)) => (*name, kinds), None => { unk_string = format!("<Unknown> ({})", pokemon.data.growth.species); (&unk_string[..], &unk_vec) } }; let data = &pokemon.data; let evc = &data.evs_and_condition; println!( "{} <{}> {:?}", decode_string(&pokemon.nickname.0), name, kinds ); println!("friendship: {}", data.growth.friendship); println!("EVs:");
identifier_body
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kinds.push($kind);
map.insert($id, ($name, kinds)); );+ map }} } #[allow(clippy::zero_prefixed_literal)] fn main() { let mut args = std::env::args().skip(1); let path = args.next().expect("Need path to save as first arg"); let save = rgen3_save::Save::load_from_file(&path).unwrap(); let SaveSections { team, pc_boxes,.. } = save.sections(); let pokemap = include!("../../poke.incl"); println!("== Team =="); for pokemon in team { print_pokemon(pokemon, &pokemap); } println!("== PC =="); for pbox in pc_boxes { for slot in &pbox.slots { if let Some(pokemon) = slot { print_pokemon(pokemon, &pokemap); } } } } fn print_pokemon(pokemon: &Pokemon, pokemap: &HashMap<u16, (&'static str, Vec<&'static str>)>) { let unk_string: String; let unk_vec = vec![""]; let (name, kinds) = match pokemap.get(&pokemon.data.growth.species) { Some((name, kinds)) => (*name, kinds), None => { unk_string = format!("<Unknown> ({})", pokemon.data.growth.species); (&unk_string[..], &unk_vec) } }; let data = &pokemon.data; let evc = &data.evs_and_condition; println!( "{} <{}> {:?}", decode_string(&pokemon.nickname.0), name, kinds ); println!("friendship: {}", data.growth.friendship); println!("EVs:"); println!("hp: {}", evc.hp); println!("atk: {}", evc.attack); println!("def: {}", evc.defense); println!("spd: {}", evc.speed); println!("sp atk: {}", evc.sp_attack); println!("sp def: {}", evc.sp_defense); println!( "total: {}/510", u16::from(evc.hp) + u16::from(evc.attack) + u16::from(evc.defense) + u16::from(evc.speed) + u16::from(evc.sp_attack) + u16::from(evc.sp_defense) ); println!("-") }
)+
random_line_split
list-pokemon.rs
use rgen3_save::{Pokemon, SaveSections}; use rgen3_string::decode_string; use std::collections::HashMap; macro_rules! make_poke_map { ($($id:literal,$name:literal,$($kind:literal,)+;)+) => {{ let mut map = HashMap::new(); $( let mut kinds = Vec::new(); $( kinds.push($kind); )+ map.insert($id, ($name, kinds)); );+ map }} } #[allow(clippy::zero_prefixed_literal)] fn
() { let mut args = std::env::args().skip(1); let path = args.next().expect("Need path to save as first arg"); let save = rgen3_save::Save::load_from_file(&path).unwrap(); let SaveSections { team, pc_boxes,.. } = save.sections(); let pokemap = include!("../../poke.incl"); println!("== Team =="); for pokemon in team { print_pokemon(pokemon, &pokemap); } println!("== PC =="); for pbox in pc_boxes { for slot in &pbox.slots { if let Some(pokemon) = slot { print_pokemon(pokemon, &pokemap); } } } } fn print_pokemon(pokemon: &Pokemon, pokemap: &HashMap<u16, (&'static str, Vec<&'static str>)>) { let unk_string: String; let unk_vec = vec![""]; let (name, kinds) = match pokemap.get(&pokemon.data.growth.species) { Some((name, kinds)) => (*name, kinds), None => { unk_string = format!("<Unknown> ({})", pokemon.data.growth.species); (&unk_string[..], &unk_vec) } }; let data = &pokemon.data; let evc = &data.evs_and_condition; println!( "{} <{}> {:?}", decode_string(&pokemon.nickname.0), name, kinds ); println!("friendship: {}", data.growth.friendship); println!("EVs:"); println!("hp: {}", evc.hp); println!("atk: {}", evc.attack); println!("def: {}", evc.defense); println!("spd: {}", evc.speed); println!("sp atk: {}", evc.sp_attack); println!("sp def: {}", evc.sp_defense); println!( "total: {}/510", u16::from(evc.hp) + u16::from(evc.attack) + u16::from(evc.defense) + u16::from(evc.speed) + u16::from(evc.sp_attack) + u16::from(evc.sp_defense) ); println!("-") }
main
identifier_name
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::Name), "fullpath" => Ok(ListFormat::FullPath), _ => Err(()), } } } #[derive(Debug)] pub struct ListCommand { format: ListFormat, } impl ListCommand { pub fn
<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("List local repositories managed by rhq").arg( Arg::from_usage("--format=[format] 'List format'") .possible_values(&["name", "fullpath"]) .default_value("fullpath"), ) } pub fn from_matches(m: &ArgMatches) -> ListCommand { ListCommand { format: m.value_of("format").and_then(|s| s.parse().ok()).unwrap(), } } pub fn run(self) -> Result<()> { let workspace = Workspace::new()?; workspace.for_each_repo(|repo| { match self.format { ListFormat::Name => println!("{}", repo.name()), ListFormat::FullPath => println!("{}", repo.path_string()), } Ok(()) }) } }
app
identifier_name
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::Name), "fullpath" => Ok(ListFormat::FullPath), _ => Err(()), } } } #[derive(Debug)] pub struct ListCommand { format: ListFormat, } impl ListCommand { pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("List local repositories managed by rhq").arg( Arg::from_usage("--format=[format] 'List format'") .possible_values(&["name", "fullpath"]) .default_value("fullpath"), ) } pub fn from_matches(m: &ArgMatches) -> ListCommand { ListCommand { format: m.value_of("format").and_then(|s| s.parse().ok()).unwrap(), } }
ListFormat::FullPath => println!("{}", repo.path_string()), } Ok(()) }) } }
pub fn run(self) -> Result<()> { let workspace = Workspace::new()?; workspace.for_each_repo(|repo| { match self.format { ListFormat::Name => println!("{}", repo.name()),
random_line_split
list.rs
use anyhow::Result; use clap::{App, Arg, ArgMatches}; use rhq::Workspace; use std::str::FromStr; #[derive(Debug)] enum ListFormat { Name, FullPath, } impl FromStr for ListFormat { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "name" => Ok(ListFormat::Name), "fullpath" => Ok(ListFormat::FullPath), _ => Err(()), } } } #[derive(Debug)] pub struct ListCommand { format: ListFormat, } impl ListCommand { pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("List local repositories managed by rhq").arg( Arg::from_usage("--format=[format] 'List format'") .possible_values(&["name", "fullpath"]) .default_value("fullpath"), ) } pub fn from_matches(m: &ArgMatches) -> ListCommand { ListCommand { format: m.value_of("format").and_then(|s| s.parse().ok()).unwrap(), } } pub fn run(self) -> Result<()>
}
{ let workspace = Workspace::new()?; workspace.for_each_repo(|repo| { match self.format { ListFormat::Name => println!("{}", repo.name()), ListFormat::FullPath => println!("{}", repo.path_string()), } Ok(()) }) }
identifier_body
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice appear in // all copies and that both that copyright notice and this permission // notice appear in supporting documentation, and that the name of // the copyright holders not be used in advertising or publicity // pertaining to distribution of the software without specific, // written prior permission. The copyright holders make no // representations about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. // // THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY // SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, // ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF // THIS SOFTWARE. // Generated with version 1.7.0 #![allow(unused_imports)] use std::{ptr, mem}; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use libc::{c_void, c_int, uint32_t}; use ffi; use client::protocol::{FromPrimitive, GetInterface}; use client::base::Proxy as BaseProxy; use client::base::{FromRawPtr, AsRawPtr, EventQueue}; #[link(name="wayland-client")] extern { static wl_output_interface: ffi::wayland::WLInterface; } /// This enumeration describes how the physical /// pixels on an output are layed out. #[repr(C)] #[derive(Debug)] pub enum OutputSubpixel { Unknown = 0, None = 1, HorizontalRgb = 2, HorizontalBgr = 3, VerticalRgb = 4, VerticalBgr = 5, } impl FromPrimitive for OutputSubpixel { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputSubpixel::Unknown), 1 => Some(OutputSubpixel::None), 2 => Some(OutputSubpixel::HorizontalRgb), 3 => Some(OutputSubpixel::HorizontalBgr), 4 => Some(OutputSubpixel::VerticalRgb), 5 => Some(OutputSubpixel::VerticalBgr), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputSubpixelSet { fn has_unknown(&self) -> bool; fn has_none(&self) -> bool; fn has_horizontal_rgb(&self) -> bool; fn has_horizontal_bgr(&self) -> bool; fn has_vertical_rgb(&self) -> bool; fn has_vertical_bgr(&self) -> bool; } impl OutputSubpixelSet for u32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as u32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as u32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as u32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as u32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as u32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as u32)!= 0; } } impl OutputSubpixelSet for i32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as i32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as i32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as i32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as i32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as i32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as i32)!= 0; } } /// This describes the transform that a compositor will apply to a /// surface to compensate for the rotation or mirroring of an /// output device. /// /// The flipped values correspond to an initial flip around a /// vertical axis followed by rotation. /// /// The purpose is mainly to allow clients render accordingly and /// tell the compositor, so that for fullscreen surfaces, the /// compositor will still be able to scan out directly from client /// surfaces. #[repr(C)] #[derive(Debug)] pub enum OutputTransform { Normal = 0, _90 = 1, _180 = 2, _270 = 3, Flipped = 4, Flipped90 = 5, Flipped180 = 6, Flipped270 = 7, } impl FromPrimitive for OutputTransform { fn from_u32(num: u32) -> Option<Self> {
fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputTransformSet { fn has_normal(&self) -> bool; fn has_90(&self) -> bool; fn has_180(&self) -> bool; fn has_270(&self) -> bool; fn has_flipped(&self) -> bool; fn has_flipped_90(&self) -> bool; fn has_flipped_180(&self) -> bool; fn has_flipped_270(&self) -> bool; } impl OutputTransformSet for u32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as u32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as u32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as u32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as u32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as u32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as u32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as u32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as u32)!= 0; } } impl OutputTransformSet for i32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as i32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as i32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as i32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as i32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as i32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as i32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as i32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as i32)!= 0; } } /// These flags describe properties of an output mode. /// They are used in the flags bitfield of the mode event. #[repr(C)] #[derive(Debug)] pub enum OutputMode { /// indicates this is the current mode Current = 0x1, /// indicates this is the preferred mode Preferred = 0x2, } impl FromPrimitive for OutputMode { fn from_u32(num: u32) -> Option<Self> { return match num { 0x1 => Some(OutputMode::Current), 0x2 => Some(OutputMode::Preferred), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputModeSet { fn has_current(&self) -> bool; fn has_preferred(&self) -> bool; } impl OutputModeSet for u32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as u32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as u32)!= 0; } } impl OutputModeSet for i32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as i32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as i32)!= 0; } } #[repr(C)] enum OutputEvent { Geometry = 0, Mode = 1, Done = 2, Scale = 3, } impl FromPrimitive for OutputEvent { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputEvent::Geometry), 1 => Some(OutputEvent::Mode), 2 => Some(OutputEvent::Done), 3 => Some(OutputEvent::Scale), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } /// An output describes part of the compositor geometry. The /// compositor works in the 'compositor coordinate system' and an /// output corresponds to rectangular area in that space that is /// actually visible. This typically corresponds to a monitor that /// displays part of the compositor space. This object is published /// as global during start up, or when a monitor is hotplugged. #[derive(Debug)] pub struct Output { proxy: BaseProxy, } impl Output { pub fn get_id(&mut self) -> u32 { return self.proxy.get_id(); } pub fn get_class(&mut self) -> String { return self.proxy.get_class(); } pub fn set_queue(&mut self, queue: Option<&mut EventQueue>) { self.proxy.set_queue(queue); } } impl FromRawPtr<ffi::wayland::WLProxy> for Output { fn from_mut_ptr(ptr: *mut ffi::wayland::WLProxy) -> Result<Self, &'static str> { return match FromRawPtr::from_mut_ptr(ptr) { Ok(proxy) => Ok(Output { proxy: proxy, }), Err(str) => Err(str), } } } impl AsRawPtr<ffi::wayland::WLProxy> for Output { fn as_mut_ptr(&mut self) -> *mut ffi::wayland::WLProxy { return self.proxy.as_mut_ptr(); } } impl GetInterface for Output { fn get_interface() -> *const ffi::wayland::WLInterface { return &wl_output_interface as *const ffi::wayland::WLInterface; } } #[allow(unused_variables)] extern fn output_event_dispatcher<T: OutputEventHandler>( user_data: *mut c_void, _target: *mut c_void, opcode: uint32_t, _message: *const ffi::wayland::WLMessage, arguments: *mut ffi::wayland::WLArgument) -> c_int { let object = user_data as *mut T; return match OutputEvent::from_u32(opcode) { Some(event) => { match event { OutputEvent::Geometry => { let x = unsafe { *(*arguments.offset(0)).int() }; let y = unsafe { *(*arguments.offset(1)).int() }; let physical_width = unsafe { *(*arguments.offset(2)).int() }; let physical_height = unsafe { *(*arguments.offset(3)).int() }; let subpixel = unsafe { *(*arguments.offset(4)).int() }; let make_raw = unsafe { *(*arguments.offset(5)).string() }; let make_buffer = unsafe { CStr::from_ptr(make_raw).to_bytes() }; let make = String::from_utf8(make_buffer.to_vec()).unwrap(); let model_raw = unsafe { *(*arguments.offset(6)).string() }; let model_buffer = unsafe { CStr::from_ptr(model_raw).to_bytes() }; let model = String::from_utf8(model_buffer.to_vec()).unwrap(); let transform = unsafe { *(*arguments.offset(7)).int() }; unsafe { (*object).on_geometry(x, y, physical_width, physical_height, subpixel, make, model, transform); } }, OutputEvent::Mode => { let flags = unsafe { *(*arguments.offset(0)).uint() }; let width = unsafe { *(*arguments.offset(1)).int() }; let height = unsafe { *(*arguments.offset(2)).int() }; let refresh = unsafe { *(*arguments.offset(3)).int() }; unsafe { (*object).on_mode(flags, width, height, refresh); } }, OutputEvent::Done => { unsafe { (*object).on_done(); } }, OutputEvent::Scale => { let factor = unsafe { *(*arguments.offset(0)).int() }; unsafe { (*object).on_scale(factor); } }, } 0 }, _ => -1, } } pub trait OutputEventHandler: Sized { fn connect_dispatcher(&mut self) { unsafe { ffi::wayland::wl_proxy_add_dispatcher( self.get_output().as_mut_ptr(), output_event_dispatcher::<Self>, self as *mut Self as *mut c_void, ptr::null_mut()); } } fn get_output(&mut self) -> &mut Output; /// The geometry event describes geometric properties of the output. /// The event is sent when binding to the output object and whenever /// any of the properties change. #[allow(unused_variables)] fn on_geometry(&mut self, x: i32, y: i32, physical_width: i32, physical_height: i32, subpixel: i32, make: String, model: String, transform: i32) {} /// The mode event describes an available mode for the output. /// /// The event is sent when binding to the output object and there /// will always be one mode, the current mode. The event is sent /// again if an output changes mode, for the mode that is now /// current. In other words, the current mode is always the last /// mode that was received with the current flag set. /// /// The size of a mode is given in physical hardware units of /// the output device. This is not necessarily the same as /// the output size in the global compositor space. For instance, /// the output may be scaled, as described in wl_output.scale, /// or transformed, as described in wl_output.transform. #[allow(unused_variables)] fn on_mode(&mut self, flags: u32, width: i32, height: i32, refresh: i32) {} /// This event is sent after all other properties has been /// sent after binding to the output object and after any /// other property changes done after that. This allows /// changes to the output properties to be seen as /// atomic, even if they happen via multiple events. #[allow(unused_variables)] fn on_done(&mut self) {} /// This event contains scaling geometry information /// that is not in the geometry event. It may be sent after /// binding the output object or if the output scale changes /// later. If it is not sent, the client should assume a /// scale of 1. /// /// A scale larger than 1 means that the compositor will /// automatically scale surface buffers by this amount /// when rendering. This is used for very high resolution /// displays where applications rendering at the native /// resolution would be too small to be legible. /// /// It is intended that scaling aware clients track the /// current output of a surface, and if it is on a scaled /// output it should use wl_surface.set_buffer_scale with /// the scale of the output. That way the compositor can /// avoid scaling the surface, and the client can supply /// a higher detail image. #[allow(unused_variables)] fn on_scale(&mut self, factor: i32) {} }
return match num { 0 => Some(OutputTransform::Normal), 1 => Some(OutputTransform::_90), 2 => Some(OutputTransform::_180), 3 => Some(OutputTransform::_270), 4 => Some(OutputTransform::Flipped), 5 => Some(OutputTransform::Flipped90), 6 => Some(OutputTransform::Flipped180), 7 => Some(OutputTransform::Flipped270), _ => None } }
identifier_body
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice appear in // all copies and that both that copyright notice and this permission // notice appear in supporting documentation, and that the name of // the copyright holders not be used in advertising or publicity // pertaining to distribution of the software without specific, // written prior permission. The copyright holders make no // representations about the suitability of this software for any
// purpose. It is provided "as is" without express or implied // warranty. // // THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY // SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, // ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF // THIS SOFTWARE. // Generated with version 1.7.0 #![allow(unused_imports)] use std::{ptr, mem}; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use libc::{c_void, c_int, uint32_t}; use ffi; use client::protocol::{FromPrimitive, GetInterface}; use client::base::Proxy as BaseProxy; use client::base::{FromRawPtr, AsRawPtr, EventQueue}; #[link(name="wayland-client")] extern { static wl_output_interface: ffi::wayland::WLInterface; } /// This enumeration describes how the physical /// pixels on an output are layed out. #[repr(C)] #[derive(Debug)] pub enum OutputSubpixel { Unknown = 0, None = 1, HorizontalRgb = 2, HorizontalBgr = 3, VerticalRgb = 4, VerticalBgr = 5, } impl FromPrimitive for OutputSubpixel { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputSubpixel::Unknown), 1 => Some(OutputSubpixel::None), 2 => Some(OutputSubpixel::HorizontalRgb), 3 => Some(OutputSubpixel::HorizontalBgr), 4 => Some(OutputSubpixel::VerticalRgb), 5 => Some(OutputSubpixel::VerticalBgr), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputSubpixelSet { fn has_unknown(&self) -> bool; fn has_none(&self) -> bool; fn has_horizontal_rgb(&self) -> bool; fn has_horizontal_bgr(&self) -> bool; fn has_vertical_rgb(&self) -> bool; fn has_vertical_bgr(&self) -> bool; } impl OutputSubpixelSet for u32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as u32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as u32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as u32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as u32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as u32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as u32)!= 0; } } impl OutputSubpixelSet for i32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as i32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as i32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as i32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as i32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as i32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as i32)!= 0; } } /// This describes the transform that a compositor will apply to a /// surface to compensate for the rotation or mirroring of an /// output device. /// /// The flipped values correspond to an initial flip around a /// vertical axis followed by rotation. /// /// The purpose is mainly to allow clients render accordingly and /// tell the compositor, so that for fullscreen surfaces, the /// compositor will still be able to scan out directly from client /// surfaces. #[repr(C)] #[derive(Debug)] pub enum OutputTransform { Normal = 0, _90 = 1, _180 = 2, _270 = 3, Flipped = 4, Flipped90 = 5, Flipped180 = 6, Flipped270 = 7, } impl FromPrimitive for OutputTransform { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputTransform::Normal), 1 => Some(OutputTransform::_90), 2 => Some(OutputTransform::_180), 3 => Some(OutputTransform::_270), 4 => Some(OutputTransform::Flipped), 5 => Some(OutputTransform::Flipped90), 6 => Some(OutputTransform::Flipped180), 7 => Some(OutputTransform::Flipped270), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputTransformSet { fn has_normal(&self) -> bool; fn has_90(&self) -> bool; fn has_180(&self) -> bool; fn has_270(&self) -> bool; fn has_flipped(&self) -> bool; fn has_flipped_90(&self) -> bool; fn has_flipped_180(&self) -> bool; fn has_flipped_270(&self) -> bool; } impl OutputTransformSet for u32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as u32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as u32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as u32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as u32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as u32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as u32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as u32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as u32)!= 0; } } impl OutputTransformSet for i32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as i32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as i32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as i32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as i32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as i32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as i32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as i32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as i32)!= 0; } } /// These flags describe properties of an output mode. /// They are used in the flags bitfield of the mode event. #[repr(C)] #[derive(Debug)] pub enum OutputMode { /// indicates this is the current mode Current = 0x1, /// indicates this is the preferred mode Preferred = 0x2, } impl FromPrimitive for OutputMode { fn from_u32(num: u32) -> Option<Self> { return match num { 0x1 => Some(OutputMode::Current), 0x2 => Some(OutputMode::Preferred), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputModeSet { fn has_current(&self) -> bool; fn has_preferred(&self) -> bool; } impl OutputModeSet for u32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as u32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as u32)!= 0; } } impl OutputModeSet for i32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as i32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as i32)!= 0; } } #[repr(C)] enum OutputEvent { Geometry = 0, Mode = 1, Done = 2, Scale = 3, } impl FromPrimitive for OutputEvent { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputEvent::Geometry), 1 => Some(OutputEvent::Mode), 2 => Some(OutputEvent::Done), 3 => Some(OutputEvent::Scale), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } /// An output describes part of the compositor geometry. The /// compositor works in the 'compositor coordinate system' and an /// output corresponds to rectangular area in that space that is /// actually visible. This typically corresponds to a monitor that /// displays part of the compositor space. This object is published /// as global during start up, or when a monitor is hotplugged. #[derive(Debug)] pub struct Output { proxy: BaseProxy, } impl Output { pub fn get_id(&mut self) -> u32 { return self.proxy.get_id(); } pub fn get_class(&mut self) -> String { return self.proxy.get_class(); } pub fn set_queue(&mut self, queue: Option<&mut EventQueue>) { self.proxy.set_queue(queue); } } impl FromRawPtr<ffi::wayland::WLProxy> for Output { fn from_mut_ptr(ptr: *mut ffi::wayland::WLProxy) -> Result<Self, &'static str> { return match FromRawPtr::from_mut_ptr(ptr) { Ok(proxy) => Ok(Output { proxy: proxy, }), Err(str) => Err(str), } } } impl AsRawPtr<ffi::wayland::WLProxy> for Output { fn as_mut_ptr(&mut self) -> *mut ffi::wayland::WLProxy { return self.proxy.as_mut_ptr(); } } impl GetInterface for Output { fn get_interface() -> *const ffi::wayland::WLInterface { return &wl_output_interface as *const ffi::wayland::WLInterface; } } #[allow(unused_variables)] extern fn output_event_dispatcher<T: OutputEventHandler>( user_data: *mut c_void, _target: *mut c_void, opcode: uint32_t, _message: *const ffi::wayland::WLMessage, arguments: *mut ffi::wayland::WLArgument) -> c_int { let object = user_data as *mut T; return match OutputEvent::from_u32(opcode) { Some(event) => { match event { OutputEvent::Geometry => { let x = unsafe { *(*arguments.offset(0)).int() }; let y = unsafe { *(*arguments.offset(1)).int() }; let physical_width = unsafe { *(*arguments.offset(2)).int() }; let physical_height = unsafe { *(*arguments.offset(3)).int() }; let subpixel = unsafe { *(*arguments.offset(4)).int() }; let make_raw = unsafe { *(*arguments.offset(5)).string() }; let make_buffer = unsafe { CStr::from_ptr(make_raw).to_bytes() }; let make = String::from_utf8(make_buffer.to_vec()).unwrap(); let model_raw = unsafe { *(*arguments.offset(6)).string() }; let model_buffer = unsafe { CStr::from_ptr(model_raw).to_bytes() }; let model = String::from_utf8(model_buffer.to_vec()).unwrap(); let transform = unsafe { *(*arguments.offset(7)).int() }; unsafe { (*object).on_geometry(x, y, physical_width, physical_height, subpixel, make, model, transform); } }, OutputEvent::Mode => { let flags = unsafe { *(*arguments.offset(0)).uint() }; let width = unsafe { *(*arguments.offset(1)).int() }; let height = unsafe { *(*arguments.offset(2)).int() }; let refresh = unsafe { *(*arguments.offset(3)).int() }; unsafe { (*object).on_mode(flags, width, height, refresh); } }, OutputEvent::Done => { unsafe { (*object).on_done(); } }, OutputEvent::Scale => { let factor = unsafe { *(*arguments.offset(0)).int() }; unsafe { (*object).on_scale(factor); } }, } 0 }, _ => -1, } } pub trait OutputEventHandler: Sized { fn connect_dispatcher(&mut self) { unsafe { ffi::wayland::wl_proxy_add_dispatcher( self.get_output().as_mut_ptr(), output_event_dispatcher::<Self>, self as *mut Self as *mut c_void, ptr::null_mut()); } } fn get_output(&mut self) -> &mut Output; /// The geometry event describes geometric properties of the output. /// The event is sent when binding to the output object and whenever /// any of the properties change. #[allow(unused_variables)] fn on_geometry(&mut self, x: i32, y: i32, physical_width: i32, physical_height: i32, subpixel: i32, make: String, model: String, transform: i32) {} /// The mode event describes an available mode for the output. /// /// The event is sent when binding to the output object and there /// will always be one mode, the current mode. The event is sent /// again if an output changes mode, for the mode that is now /// current. In other words, the current mode is always the last /// mode that was received with the current flag set. /// /// The size of a mode is given in physical hardware units of /// the output device. This is not necessarily the same as /// the output size in the global compositor space. For instance, /// the output may be scaled, as described in wl_output.scale, /// or transformed, as described in wl_output.transform. #[allow(unused_variables)] fn on_mode(&mut self, flags: u32, width: i32, height: i32, refresh: i32) {} /// This event is sent after all other properties has been /// sent after binding to the output object and after any /// other property changes done after that. This allows /// changes to the output properties to be seen as /// atomic, even if they happen via multiple events. #[allow(unused_variables)] fn on_done(&mut self) {} /// This event contains scaling geometry information /// that is not in the geometry event. It may be sent after /// binding the output object or if the output scale changes /// later. If it is not sent, the client should assume a /// scale of 1. /// /// A scale larger than 1 means that the compositor will /// automatically scale surface buffers by this amount /// when rendering. This is used for very high resolution /// displays where applications rendering at the native /// resolution would be too small to be legible. /// /// It is intended that scaling aware clients track the /// current output of a surface, and if it is on a scaled /// output it should use wl_surface.set_buffer_scale with /// the scale of the output. That way the compositor can /// avoid scaling the surface, and the client can supply /// a higher detail image. #[allow(unused_variables)] fn on_scale(&mut self, factor: i32) {} }
random_line_split
output.rs
// Copyright © 2008-2011 Kristian Høgsberg // Copyright © 2010-2011 Intel Corporation // Copyright © 2012-2013 Collabora, Ltd. // // Permission to use, copy, modify, distribute, and sell this // software and its documentation for any purpose is hereby granted // without fee, provided that the above copyright notice appear in // all copies and that both that copyright notice and this permission // notice appear in supporting documentation, and that the name of // the copyright holders not be used in advertising or publicity // pertaining to distribution of the software without specific, // written prior permission. The copyright holders make no // representations about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. // // THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY // SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, // ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF // THIS SOFTWARE. // Generated with version 1.7.0 #![allow(unused_imports)] use std::{ptr, mem}; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use libc::{c_void, c_int, uint32_t}; use ffi; use client::protocol::{FromPrimitive, GetInterface}; use client::base::Proxy as BaseProxy; use client::base::{FromRawPtr, AsRawPtr, EventQueue}; #[link(name="wayland-client")] extern { static wl_output_interface: ffi::wayland::WLInterface; } /// This enumeration describes how the physical /// pixels on an output are layed out. #[repr(C)] #[derive(Debug)] pub enum OutputSubpixel { Unknown = 0, None = 1, HorizontalRgb = 2, HorizontalBgr = 3, VerticalRgb = 4, VerticalBgr = 5, } impl FromPrimitive for OutputSubpixel { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputSubpixel::Unknown), 1 => Some(OutputSubpixel::None), 2 => Some(OutputSubpixel::HorizontalRgb), 3 => Some(OutputSubpixel::HorizontalBgr), 4 => Some(OutputSubpixel::VerticalRgb), 5 => Some(OutputSubpixel::VerticalBgr), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputSubpixelSet { fn has_unknown(&self) -> bool; fn has_none(&self) -> bool; fn has_horizontal_rgb(&self) -> bool; fn has_horizontal_bgr(&self) -> bool; fn has_vertical_rgb(&self) -> bool; fn has_vertical_bgr(&self) -> bool; } impl OutputSubpixelSet for u32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as u32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as u32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as u32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as u32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as u32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as u32)!= 0; } } impl OutputSubpixelSet for i32 { fn has_unknown(&self) -> bool { return self & (OutputSubpixel::Unknown as i32)!= 0; } fn has_none(&self) -> bool { return self & (OutputSubpixel::None as i32)!= 0; } fn has_horizontal_rgb(&self) -> bool { return self & (OutputSubpixel::HorizontalRgb as i32)!= 0; } fn has_horizontal_bgr(&self) -> bool { return self & (OutputSubpixel::HorizontalBgr as i32)!= 0; } fn has_vertical_rgb(&self) -> bool { return self & (OutputSubpixel::VerticalRgb as i32)!= 0; } fn has_vertical_bgr(&self) -> bool { return self & (OutputSubpixel::VerticalBgr as i32)!= 0; } } /// This describes the transform that a compositor will apply to a /// surface to compensate for the rotation or mirroring of an /// output device. /// /// The flipped values correspond to an initial flip around a /// vertical axis followed by rotation. /// /// The purpose is mainly to allow clients render accordingly and /// tell the compositor, so that for fullscreen surfaces, the /// compositor will still be able to scan out directly from client /// surfaces. #[repr(C)] #[derive(Debug)] pub enum Outp
Normal = 0, _90 = 1, _180 = 2, _270 = 3, Flipped = 4, Flipped90 = 5, Flipped180 = 6, Flipped270 = 7, } impl FromPrimitive for OutputTransform { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputTransform::Normal), 1 => Some(OutputTransform::_90), 2 => Some(OutputTransform::_180), 3 => Some(OutputTransform::_270), 4 => Some(OutputTransform::Flipped), 5 => Some(OutputTransform::Flipped90), 6 => Some(OutputTransform::Flipped180), 7 => Some(OutputTransform::Flipped270), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputTransformSet { fn has_normal(&self) -> bool; fn has_90(&self) -> bool; fn has_180(&self) -> bool; fn has_270(&self) -> bool; fn has_flipped(&self) -> bool; fn has_flipped_90(&self) -> bool; fn has_flipped_180(&self) -> bool; fn has_flipped_270(&self) -> bool; } impl OutputTransformSet for u32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as u32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as u32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as u32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as u32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as u32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as u32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as u32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as u32)!= 0; } } impl OutputTransformSet for i32 { fn has_normal(&self) -> bool { return self & (OutputTransform::Normal as i32)!= 0; } fn has_90(&self) -> bool { return self & (OutputTransform::_90 as i32)!= 0; } fn has_180(&self) -> bool { return self & (OutputTransform::_180 as i32)!= 0; } fn has_270(&self) -> bool { return self & (OutputTransform::_270 as i32)!= 0; } fn has_flipped(&self) -> bool { return self & (OutputTransform::Flipped as i32)!= 0; } fn has_flipped_90(&self) -> bool { return self & (OutputTransform::Flipped90 as i32)!= 0; } fn has_flipped_180(&self) -> bool { return self & (OutputTransform::Flipped180 as i32)!= 0; } fn has_flipped_270(&self) -> bool { return self & (OutputTransform::Flipped270 as i32)!= 0; } } /// These flags describe properties of an output mode. /// They are used in the flags bitfield of the mode event. #[repr(C)] #[derive(Debug)] pub enum OutputMode { /// indicates this is the current mode Current = 0x1, /// indicates this is the preferred mode Preferred = 0x2, } impl FromPrimitive for OutputMode { fn from_u32(num: u32) -> Option<Self> { return match num { 0x1 => Some(OutputMode::Current), 0x2 => Some(OutputMode::Preferred), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } pub trait OutputModeSet { fn has_current(&self) -> bool; fn has_preferred(&self) -> bool; } impl OutputModeSet for u32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as u32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as u32)!= 0; } } impl OutputModeSet for i32 { fn has_current(&self) -> bool { return self & (OutputMode::Current as i32)!= 0; } fn has_preferred(&self) -> bool { return self & (OutputMode::Preferred as i32)!= 0; } } #[repr(C)] enum OutputEvent { Geometry = 0, Mode = 1, Done = 2, Scale = 3, } impl FromPrimitive for OutputEvent { fn from_u32(num: u32) -> Option<Self> { return match num { 0 => Some(OutputEvent::Geometry), 1 => Some(OutputEvent::Mode), 2 => Some(OutputEvent::Done), 3 => Some(OutputEvent::Scale), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } /// An output describes part of the compositor geometry. The /// compositor works in the 'compositor coordinate system' and an /// output corresponds to rectangular area in that space that is /// actually visible. This typically corresponds to a monitor that /// displays part of the compositor space. This object is published /// as global during start up, or when a monitor is hotplugged. #[derive(Debug)] pub struct Output { proxy: BaseProxy, } impl Output { pub fn get_id(&mut self) -> u32 { return self.proxy.get_id(); } pub fn get_class(&mut self) -> String { return self.proxy.get_class(); } pub fn set_queue(&mut self, queue: Option<&mut EventQueue>) { self.proxy.set_queue(queue); } } impl FromRawPtr<ffi::wayland::WLProxy> for Output { fn from_mut_ptr(ptr: *mut ffi::wayland::WLProxy) -> Result<Self, &'static str> { return match FromRawPtr::from_mut_ptr(ptr) { Ok(proxy) => Ok(Output { proxy: proxy, }), Err(str) => Err(str), } } } impl AsRawPtr<ffi::wayland::WLProxy> for Output { fn as_mut_ptr(&mut self) -> *mut ffi::wayland::WLProxy { return self.proxy.as_mut_ptr(); } } impl GetInterface for Output { fn get_interface() -> *const ffi::wayland::WLInterface { return &wl_output_interface as *const ffi::wayland::WLInterface; } } #[allow(unused_variables)] extern fn output_event_dispatcher<T: OutputEventHandler>( user_data: *mut c_void, _target: *mut c_void, opcode: uint32_t, _message: *const ffi::wayland::WLMessage, arguments: *mut ffi::wayland::WLArgument) -> c_int { let object = user_data as *mut T; return match OutputEvent::from_u32(opcode) { Some(event) => { match event { OutputEvent::Geometry => { let x = unsafe { *(*arguments.offset(0)).int() }; let y = unsafe { *(*arguments.offset(1)).int() }; let physical_width = unsafe { *(*arguments.offset(2)).int() }; let physical_height = unsafe { *(*arguments.offset(3)).int() }; let subpixel = unsafe { *(*arguments.offset(4)).int() }; let make_raw = unsafe { *(*arguments.offset(5)).string() }; let make_buffer = unsafe { CStr::from_ptr(make_raw).to_bytes() }; let make = String::from_utf8(make_buffer.to_vec()).unwrap(); let model_raw = unsafe { *(*arguments.offset(6)).string() }; let model_buffer = unsafe { CStr::from_ptr(model_raw).to_bytes() }; let model = String::from_utf8(model_buffer.to_vec()).unwrap(); let transform = unsafe { *(*arguments.offset(7)).int() }; unsafe { (*object).on_geometry(x, y, physical_width, physical_height, subpixel, make, model, transform); } }, OutputEvent::Mode => { let flags = unsafe { *(*arguments.offset(0)).uint() }; let width = unsafe { *(*arguments.offset(1)).int() }; let height = unsafe { *(*arguments.offset(2)).int() }; let refresh = unsafe { *(*arguments.offset(3)).int() }; unsafe { (*object).on_mode(flags, width, height, refresh); } }, OutputEvent::Done => { unsafe { (*object).on_done(); } }, OutputEvent::Scale => { let factor = unsafe { *(*arguments.offset(0)).int() }; unsafe { (*object).on_scale(factor); } }, } 0 }, _ => -1, } } pub trait OutputEventHandler: Sized { fn connect_dispatcher(&mut self) { unsafe { ffi::wayland::wl_proxy_add_dispatcher( self.get_output().as_mut_ptr(), output_event_dispatcher::<Self>, self as *mut Self as *mut c_void, ptr::null_mut()); } } fn get_output(&mut self) -> &mut Output; /// The geometry event describes geometric properties of the output. /// The event is sent when binding to the output object and whenever /// any of the properties change. #[allow(unused_variables)] fn on_geometry(&mut self, x: i32, y: i32, physical_width: i32, physical_height: i32, subpixel: i32, make: String, model: String, transform: i32) {} /// The mode event describes an available mode for the output. /// /// The event is sent when binding to the output object and there /// will always be one mode, the current mode. The event is sent /// again if an output changes mode, for the mode that is now /// current. In other words, the current mode is always the last /// mode that was received with the current flag set. /// /// The size of a mode is given in physical hardware units of /// the output device. This is not necessarily the same as /// the output size in the global compositor space. For instance, /// the output may be scaled, as described in wl_output.scale, /// or transformed, as described in wl_output.transform. #[allow(unused_variables)] fn on_mode(&mut self, flags: u32, width: i32, height: i32, refresh: i32) {} /// This event is sent after all other properties has been /// sent after binding to the output object and after any /// other property changes done after that. This allows /// changes to the output properties to be seen as /// atomic, even if they happen via multiple events. #[allow(unused_variables)] fn on_done(&mut self) {} /// This event contains scaling geometry information /// that is not in the geometry event. It may be sent after /// binding the output object or if the output scale changes /// later. If it is not sent, the client should assume a /// scale of 1. /// /// A scale larger than 1 means that the compositor will /// automatically scale surface buffers by this amount /// when rendering. This is used for very high resolution /// displays where applications rendering at the native /// resolution would be too small to be legible. /// /// It is intended that scaling aware clients track the /// current output of a surface, and if it is on a scaled /// output it should use wl_surface.set_buffer_scale with /// the scale of the output. That way the compositor can /// avoid scaling the surface, and the client can supply /// a higher detail image. #[allow(unused_variables)] fn on_scale(&mut self, factor: i32) {} }
utTransform {
identifier_name
extent.rs
// // Copyright 2016 Andrew Hunter // // 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 super::address::*; /// /// An extent represents a series of nodes starting at a specified node /// #[derive(Clone, Copy, PartialEq)] pub enum TreeExtent { /// Just the initial node ThisNode,
/// The entire subtree (all children, and their children, and so on) /// /// Unlike Children, this covers the current node and its entire subtree SubTree } impl TreeExtent { /// /// Returns true if this extent will cover the specified address, which is relative to where the extent starts /// pub fn covers(&self, address: &TreeAddress) -> bool { match *self { TreeExtent::ThisNode => { match *address { TreeAddress::Here => true, _ => false } }, TreeExtent::Children => { match *address { TreeAddress::ChildAtIndex(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), TreeAddress::ChildWithTag(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), _ => false } }, TreeExtent::SubTree => true } } } #[cfg(test)] mod extent_tests { use super::super::super::tree::*; #[test] fn thisnode_covers_only_here() { assert!(TreeExtent::ThisNode.covers(&TreeAddress::Here)); assert!(!TreeExtent::ThisNode.covers(&(1.to_tree_address()))); } #[test] fn children_covers_only_immediate_children() { assert!(TreeExtent::Children.covers(&(1.to_tree_address()))); assert!(TreeExtent::Children.covers(&("tag".to_tree_address()))); assert!(!TreeExtent::Children.covers(&((1, 2).to_tree_address()))); assert!(!TreeExtent::Children.covers(&(("tag", "othertag").to_tree_address()))); assert!(!TreeExtent::Children.covers(&TreeAddress::Here)); } #[test] fn subtree_covers_everything() { assert!(TreeExtent::SubTree.covers(&(1.to_tree_address()))); assert!(TreeExtent::SubTree.covers(&("tag".to_tree_address()))); assert!(TreeExtent::SubTree.covers(&((1, 2).to_tree_address()))); assert!(TreeExtent::SubTree.covers(&(("tag", "othertag").to_tree_address()))); assert!(TreeExtent::SubTree.covers(&TreeAddress::Here)); } }
/// The children of this node /// /// This does not extend beyond the immediate children of the current node. Children,
random_line_split
extent.rs
// // Copyright 2016 Andrew Hunter // // 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 super::address::*; /// /// An extent represents a series of nodes starting at a specified node /// #[derive(Clone, Copy, PartialEq)] pub enum TreeExtent { /// Just the initial node ThisNode, /// The children of this node /// /// This does not extend beyond the immediate children of the current node. Children, /// The entire subtree (all children, and their children, and so on) /// /// Unlike Children, this covers the current node and its entire subtree SubTree } impl TreeExtent { /// /// Returns true if this extent will cover the specified address, which is relative to where the extent starts /// pub fn covers(&self, address: &TreeAddress) -> bool { match *self { TreeExtent::ThisNode => { match *address { TreeAddress::Here => true, _ => false } }, TreeExtent::Children => { match *address { TreeAddress::ChildAtIndex(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), TreeAddress::ChildWithTag(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), _ => false } }, TreeExtent::SubTree => true } } } #[cfg(test)] mod extent_tests { use super::super::super::tree::*; #[test] fn thisnode_covers_only_here() { assert!(TreeExtent::ThisNode.covers(&TreeAddress::Here)); assert!(!TreeExtent::ThisNode.covers(&(1.to_tree_address()))); } #[test] fn
() { assert!(TreeExtent::Children.covers(&(1.to_tree_address()))); assert!(TreeExtent::Children.covers(&("tag".to_tree_address()))); assert!(!TreeExtent::Children.covers(&((1, 2).to_tree_address()))); assert!(!TreeExtent::Children.covers(&(("tag", "othertag").to_tree_address()))); assert!(!TreeExtent::Children.covers(&TreeAddress::Here)); } #[test] fn subtree_covers_everything() { assert!(TreeExtent::SubTree.covers(&(1.to_tree_address()))); assert!(TreeExtent::SubTree.covers(&("tag".to_tree_address()))); assert!(TreeExtent::SubTree.covers(&((1, 2).to_tree_address()))); assert!(TreeExtent::SubTree.covers(&(("tag", "othertag").to_tree_address()))); assert!(TreeExtent::SubTree.covers(&TreeAddress::Here)); } }
children_covers_only_immediate_children
identifier_name
extent.rs
// // Copyright 2016 Andrew Hunter // // 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 super::address::*; /// /// An extent represents a series of nodes starting at a specified node /// #[derive(Clone, Copy, PartialEq)] pub enum TreeExtent { /// Just the initial node ThisNode, /// The children of this node /// /// This does not extend beyond the immediate children of the current node. Children, /// The entire subtree (all children, and their children, and so on) /// /// Unlike Children, this covers the current node and its entire subtree SubTree } impl TreeExtent { /// /// Returns true if this extent will cover the specified address, which is relative to where the extent starts /// pub fn covers(&self, address: &TreeAddress) -> bool { match *self { TreeExtent::ThisNode => { match *address { TreeAddress::Here => true, _ => false } }, TreeExtent::Children => { match *address { TreeAddress::ChildAtIndex(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), TreeAddress::ChildWithTag(_, ref child_address) => TreeExtent::ThisNode.covers(child_address), _ => false } }, TreeExtent::SubTree => true } } } #[cfg(test)] mod extent_tests { use super::super::super::tree::*; #[test] fn thisnode_covers_only_here() { assert!(TreeExtent::ThisNode.covers(&TreeAddress::Here)); assert!(!TreeExtent::ThisNode.covers(&(1.to_tree_address()))); } #[test] fn children_covers_only_immediate_children() { assert!(TreeExtent::Children.covers(&(1.to_tree_address()))); assert!(TreeExtent::Children.covers(&("tag".to_tree_address()))); assert!(!TreeExtent::Children.covers(&((1, 2).to_tree_address()))); assert!(!TreeExtent::Children.covers(&(("tag", "othertag").to_tree_address()))); assert!(!TreeExtent::Children.covers(&TreeAddress::Here)); } #[test] fn subtree_covers_everything()
}
{ assert!(TreeExtent::SubTree.covers(&(1.to_tree_address()))); assert!(TreeExtent::SubTree.covers(&("tag".to_tree_address()))); assert!(TreeExtent::SubTree.covers(&((1, 2).to_tree_address()))); assert!(TreeExtent::SubTree.covers(&(("tag", "othertag").to_tree_address()))); assert!(TreeExtent::SubTree.covers(&TreeAddress::Here)); }
identifier_body
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pub struct FunctionFlags: u8 { const NORET = 0b0000_0001; const THUNK = 0b0000_0010; } } pub struct FunctionAnalysis { pub flags: FunctionFlags, } #[derive(Default)] pub struct NameIndex { pub names_by_address: BTreeMap<VA, String>, pub addresses_by_name: BTreeMap<String, VA>, } impl NameIndex { pub fn
(&mut self, va: VA, name: String) { self.names_by_address.insert(va, name.clone()); self.addresses_by_name.insert(name, va); } pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some(); } pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format analysis passes // - cfg flow analysis (call insns) // - manual actions pub functions: BTreeMap<VA, FunctionAnalysis>, // derived from: // - file format analysis pass: pe::get_improts() pub imports: BTreeMap<VA, Import>, // derived from: // - user names // - export names // - imported symbols // - flirt sigs pub names: NameIndex, } pub struct PEWorkspace { pub config: Box<dyn cfg::Configuration>, pub pe: PE, pub cfg: CFG, pub analysis: WorkspaceAnalysis, } impl PEWorkspace { pub fn from_pe(config: Box<dyn cfg::Configuration>, pe: PE) -> Result<PEWorkspace> { let mut insns: InstructionIndex = Default::default(); let mut function_starts: BTreeSet<VA> = Default::default(); function_starts.extend(crate::analysis::pe::entrypoints::find_pe_entrypoint(&pe)?); function_starts.extend(crate::analysis::pe::exports::find_pe_exports(&pe)?); function_starts.extend(crate::analysis::pe::safeseh::find_pe_safeseh_handlers(&pe)?); function_starts.extend(crate::analysis::pe::runtime_functions::find_pe_runtime_functions(&pe)?); function_starts.extend(crate::analysis::pe::control_flow_guard::find_pe_cfguard_functions(&pe)?); // heuristics: // function_starts.extend(crate::analysis::pe::call_targets:: // find_pe_call_targets(pe)?); function_starts.extend(crate::analysis:: // pe::patterns::find_function_prologues(pe)?); function_starts. // extend(crate::analysis::pe::pointers:: // find_pe_nonrelocated_executable_pointers(pe)?; TODO: only do the // above searches in unrecovered regions. for &function in function_starts.iter() { insns.build_index(&pe.module, function)?; } let mut cfg = CFG::from_instructions(&pe.module, insns)?; let mut noret = crate::analysis::pe::noret_imports::cfg_prune_noret_imports(&pe, &mut cfg)?; let mut function_starts = function_starts .into_iter() .filter(|va| cfg.insns.insns_by_address.contains_key(va)) .collect::<BTreeSet<VA>>(); let call_targets = cfg .basic_blocks .blocks_by_address .keys() .cloned() .filter(|bb| { cfg.flows.flows_by_dst[bb] .iter() .any(|flow| matches!(flow, Flow::Call(_))) }) .collect::<BTreeSet<VA>>(); function_starts.extend(call_targets); let imports = crate::analysis::pe::get_imports(&pe)?; let mut names: NameIndex = Default::default(); for import in imports.values() { let name = match &import.symbol { ImportedSymbol::Name(name) => format!("{}!{}", import.dll, name), ImportedSymbol::Ordinal(ordinal) => format!("{}!#{}", import.dll, ordinal), }; names.insert(import.address, name); } let sigs = config.get_sigs()?; for &function in function_starts.iter() { let matches = crate::analysis::flirt::match_flirt(&pe.module, &sigs, function)?; match matches.len().cmp(&1) { std::cmp::Ordering::Less => { // no matches continue; } std::cmp::Ordering::Equal => { // exactly one match: perfect. if let Some(name) = matches[0].get_name() { log::info!("FLIRT match: {:#x}: {}", function, name); names.insert(function, name.to_string()); } else { // no associated name, just know its a library function continue; } } std::cmp::Ordering::Greater => { // colliding matches, can't determine the name. // TODO: maybe check for special case that all names are the same? log::info!("FLIRT match: {:#x}: {} collisions", function, matches.len()); continue; } } } for name in [ "kernel32.dll!ExitProcess", "kernel32.dll!ExitThread", "exit", "_exit", "__exit", "__amsg_exit", ] { if let Some(&va) = names.addresses_by_name.get(name) { log::info!("noret via name: {}: {:#x}", name, va); noret.extend(crate::analysis::cfg::noret::cfg_mark_noret(&pe.module, &mut cfg, va)?); } } let thunks = crate::analysis::cfg::thunk::find_thunks(&cfg, function_starts.iter()); let mut functions: BTreeMap<VA, FunctionAnalysis> = Default::default(); for va in function_starts { let mut flags = FunctionFlags::empty(); if noret.contains(&va) { flags.set(FunctionFlags::NORET, true); } if thunks.contains(&va) { flags.set(FunctionFlags::THUNK, true); } functions.insert(va, FunctionAnalysis { flags }); } for &function in functions.keys() { if names.contains_address(function).not() { names.insert(function, format!("sub_{:x}", function)); } } Ok(PEWorkspace { config, pe, cfg, analysis: WorkspaceAnalysis { functions, imports, names, }, }) } } #[cfg(test)] mod tests { use super::*; use crate::rsrc::*; use anyhow::Result; #[test] fn nop() -> Result<()> { crate::test::init_logging(); let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let config = get_config(); let ws = PEWorkspace::from_pe(config, pe)?; // entry point assert!(ws.analysis.functions.contains_key(&0x401081)); // main assert!(ws.analysis.functions.contains_key(&0x401000)); assert!(ws.analysis.imports.contains_key(&0x40600C)); assert!(ws .analysis .names .contains_name(&String::from("kernel32.dll!ExitProcess"))); assert!(ws.analysis.names.contains_address(0x40600C)); // 0x401C4E: void __cdecl __noreturn __crtExitProcess(UINT uExitCode) assert!(ws.analysis.functions[&0x401C4E].flags.intersects(FunctionFlags::NORET)); // ``` // .text:00405F42 ; void __stdcall RtlUnwind(PVOID TargetFrame, PVOID TargetIp, PEXCEPTION_RECORD ExceptionRecord, PVOID ReturnValue) // .text:00405F42 RtlUnwind proc near ; CODE XREF: __global_unwind2+13↑p // .text:00405F42 // .text:00405F42 TargetFrame = dword ptr 4 // .text:00405F42 TargetIp = dword ptr 8 // .text:00405F42 ExceptionRecord = dword ptr 0Ch // .text:00405F42 ReturnValue = dword ptr 10h // .text:00405F42 // .text:00405F42 000 FF 25 7C 60 40 00 jmp ds:__imp_RtlUnwind // .text:00405F42 RtlUnwind endp // ``` assert!(ws.analysis.functions[&0x405F42].flags.intersects(FunctionFlags::THUNK)); // via FLIRT 0x401da9: _exit assert!(ws.analysis.functions.contains_key(&0x401da9)); assert!(ws.analysis.names.contains_name(&String::from("_exit"))); assert!(ws.analysis.functions[&0x401da9].flags.intersects(FunctionFlags::NORET)); Ok(()) } }
insert
identifier_name
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pub struct FunctionFlags: u8 { const NORET = 0b0000_0001; const THUNK = 0b0000_0010; } } pub struct FunctionAnalysis { pub flags: FunctionFlags, } #[derive(Default)] pub struct NameIndex { pub names_by_address: BTreeMap<VA, String>, pub addresses_by_name: BTreeMap<String, VA>, } impl NameIndex { pub fn insert(&mut self, va: VA, name: String) { self.names_by_address.insert(va, name.clone());
} pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format analysis passes // - cfg flow analysis (call insns) // - manual actions pub functions: BTreeMap<VA, FunctionAnalysis>, // derived from: // - file format analysis pass: pe::get_improts() pub imports: BTreeMap<VA, Import>, // derived from: // - user names // - export names // - imported symbols // - flirt sigs pub names: NameIndex, } pub struct PEWorkspace { pub config: Box<dyn cfg::Configuration>, pub pe: PE, pub cfg: CFG, pub analysis: WorkspaceAnalysis, } impl PEWorkspace { pub fn from_pe(config: Box<dyn cfg::Configuration>, pe: PE) -> Result<PEWorkspace> { let mut insns: InstructionIndex = Default::default(); let mut function_starts: BTreeSet<VA> = Default::default(); function_starts.extend(crate::analysis::pe::entrypoints::find_pe_entrypoint(&pe)?); function_starts.extend(crate::analysis::pe::exports::find_pe_exports(&pe)?); function_starts.extend(crate::analysis::pe::safeseh::find_pe_safeseh_handlers(&pe)?); function_starts.extend(crate::analysis::pe::runtime_functions::find_pe_runtime_functions(&pe)?); function_starts.extend(crate::analysis::pe::control_flow_guard::find_pe_cfguard_functions(&pe)?); // heuristics: // function_starts.extend(crate::analysis::pe::call_targets:: // find_pe_call_targets(pe)?); function_starts.extend(crate::analysis:: // pe::patterns::find_function_prologues(pe)?); function_starts. // extend(crate::analysis::pe::pointers:: // find_pe_nonrelocated_executable_pointers(pe)?; TODO: only do the // above searches in unrecovered regions. for &function in function_starts.iter() { insns.build_index(&pe.module, function)?; } let mut cfg = CFG::from_instructions(&pe.module, insns)?; let mut noret = crate::analysis::pe::noret_imports::cfg_prune_noret_imports(&pe, &mut cfg)?; let mut function_starts = function_starts .into_iter() .filter(|va| cfg.insns.insns_by_address.contains_key(va)) .collect::<BTreeSet<VA>>(); let call_targets = cfg .basic_blocks .blocks_by_address .keys() .cloned() .filter(|bb| { cfg.flows.flows_by_dst[bb] .iter() .any(|flow| matches!(flow, Flow::Call(_))) }) .collect::<BTreeSet<VA>>(); function_starts.extend(call_targets); let imports = crate::analysis::pe::get_imports(&pe)?; let mut names: NameIndex = Default::default(); for import in imports.values() { let name = match &import.symbol { ImportedSymbol::Name(name) => format!("{}!{}", import.dll, name), ImportedSymbol::Ordinal(ordinal) => format!("{}!#{}", import.dll, ordinal), }; names.insert(import.address, name); } let sigs = config.get_sigs()?; for &function in function_starts.iter() { let matches = crate::analysis::flirt::match_flirt(&pe.module, &sigs, function)?; match matches.len().cmp(&1) { std::cmp::Ordering::Less => { // no matches continue; } std::cmp::Ordering::Equal => { // exactly one match: perfect. if let Some(name) = matches[0].get_name() { log::info!("FLIRT match: {:#x}: {}", function, name); names.insert(function, name.to_string()); } else { // no associated name, just know its a library function continue; } } std::cmp::Ordering::Greater => { // colliding matches, can't determine the name. // TODO: maybe check for special case that all names are the same? log::info!("FLIRT match: {:#x}: {} collisions", function, matches.len()); continue; } } } for name in [ "kernel32.dll!ExitProcess", "kernel32.dll!ExitThread", "exit", "_exit", "__exit", "__amsg_exit", ] { if let Some(&va) = names.addresses_by_name.get(name) { log::info!("noret via name: {}: {:#x}", name, va); noret.extend(crate::analysis::cfg::noret::cfg_mark_noret(&pe.module, &mut cfg, va)?); } } let thunks = crate::analysis::cfg::thunk::find_thunks(&cfg, function_starts.iter()); let mut functions: BTreeMap<VA, FunctionAnalysis> = Default::default(); for va in function_starts { let mut flags = FunctionFlags::empty(); if noret.contains(&va) { flags.set(FunctionFlags::NORET, true); } if thunks.contains(&va) { flags.set(FunctionFlags::THUNK, true); } functions.insert(va, FunctionAnalysis { flags }); } for &function in functions.keys() { if names.contains_address(function).not() { names.insert(function, format!("sub_{:x}", function)); } } Ok(PEWorkspace { config, pe, cfg, analysis: WorkspaceAnalysis { functions, imports, names, }, }) } } #[cfg(test)] mod tests { use super::*; use crate::rsrc::*; use anyhow::Result; #[test] fn nop() -> Result<()> { crate::test::init_logging(); let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let config = get_config(); let ws = PEWorkspace::from_pe(config, pe)?; // entry point assert!(ws.analysis.functions.contains_key(&0x401081)); // main assert!(ws.analysis.functions.contains_key(&0x401000)); assert!(ws.analysis.imports.contains_key(&0x40600C)); assert!(ws .analysis .names .contains_name(&String::from("kernel32.dll!ExitProcess"))); assert!(ws.analysis.names.contains_address(0x40600C)); // 0x401C4E: void __cdecl __noreturn __crtExitProcess(UINT uExitCode) assert!(ws.analysis.functions[&0x401C4E].flags.intersects(FunctionFlags::NORET)); // ``` // .text:00405F42 ; void __stdcall RtlUnwind(PVOID TargetFrame, PVOID TargetIp, PEXCEPTION_RECORD ExceptionRecord, PVOID ReturnValue) // .text:00405F42 RtlUnwind proc near ; CODE XREF: __global_unwind2+13↑p // .text:00405F42 // .text:00405F42 TargetFrame = dword ptr 4 // .text:00405F42 TargetIp = dword ptr 8 // .text:00405F42 ExceptionRecord = dword ptr 0Ch // .text:00405F42 ReturnValue = dword ptr 10h // .text:00405F42 // .text:00405F42 000 FF 25 7C 60 40 00 jmp ds:__imp_RtlUnwind // .text:00405F42 RtlUnwind endp // ``` assert!(ws.analysis.functions[&0x405F42].flags.intersects(FunctionFlags::THUNK)); // via FLIRT 0x401da9: _exit assert!(ws.analysis.functions.contains_key(&0x401da9)); assert!(ws.analysis.names.contains_name(&String::from("_exit"))); assert!(ws.analysis.functions[&0x401da9].flags.intersects(FunctionFlags::NORET)); Ok(()) } }
self.addresses_by_name.insert(name, va); } pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some();
random_line_split
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pub struct FunctionFlags: u8 { const NORET = 0b0000_0001; const THUNK = 0b0000_0010; } } pub struct FunctionAnalysis { pub flags: FunctionFlags, } #[derive(Default)] pub struct NameIndex { pub names_by_address: BTreeMap<VA, String>, pub addresses_by_name: BTreeMap<String, VA>, } impl NameIndex { pub fn insert(&mut self, va: VA, name: String) { self.names_by_address.insert(va, name.clone()); self.addresses_by_name.insert(name, va); } pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some(); } pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format analysis passes // - cfg flow analysis (call insns) // - manual actions pub functions: BTreeMap<VA, FunctionAnalysis>, // derived from: // - file format analysis pass: pe::get_improts() pub imports: BTreeMap<VA, Import>, // derived from: // - user names // - export names // - imported symbols // - flirt sigs pub names: NameIndex, } pub struct PEWorkspace { pub config: Box<dyn cfg::Configuration>, pub pe: PE, pub cfg: CFG, pub analysis: WorkspaceAnalysis, } impl PEWorkspace { pub fn from_pe(config: Box<dyn cfg::Configuration>, pe: PE) -> Result<PEWorkspace> { let mut insns: InstructionIndex = Default::default(); let mut function_starts: BTreeSet<VA> = Default::default(); function_starts.extend(crate::analysis::pe::entrypoints::find_pe_entrypoint(&pe)?); function_starts.extend(crate::analysis::pe::exports::find_pe_exports(&pe)?); function_starts.extend(crate::analysis::pe::safeseh::find_pe_safeseh_handlers(&pe)?); function_starts.extend(crate::analysis::pe::runtime_functions::find_pe_runtime_functions(&pe)?); function_starts.extend(crate::analysis::pe::control_flow_guard::find_pe_cfguard_functions(&pe)?); // heuristics: // function_starts.extend(crate::analysis::pe::call_targets:: // find_pe_call_targets(pe)?); function_starts.extend(crate::analysis:: // pe::patterns::find_function_prologues(pe)?); function_starts. // extend(crate::analysis::pe::pointers:: // find_pe_nonrelocated_executable_pointers(pe)?; TODO: only do the // above searches in unrecovered regions. for &function in function_starts.iter() { insns.build_index(&pe.module, function)?; } let mut cfg = CFG::from_instructions(&pe.module, insns)?; let mut noret = crate::analysis::pe::noret_imports::cfg_prune_noret_imports(&pe, &mut cfg)?; let mut function_starts = function_starts .into_iter() .filter(|va| cfg.insns.insns_by_address.contains_key(va)) .collect::<BTreeSet<VA>>(); let call_targets = cfg .basic_blocks .blocks_by_address .keys() .cloned() .filter(|bb| { cfg.flows.flows_by_dst[bb] .iter() .any(|flow| matches!(flow, Flow::Call(_))) }) .collect::<BTreeSet<VA>>(); function_starts.extend(call_targets); let imports = crate::analysis::pe::get_imports(&pe)?; let mut names: NameIndex = Default::default(); for import in imports.values() { let name = match &import.symbol { ImportedSymbol::Name(name) => format!("{}!{}", import.dll, name), ImportedSymbol::Ordinal(ordinal) => format!("{}!#{}", import.dll, ordinal), }; names.insert(import.address, name); } let sigs = config.get_sigs()?; for &function in function_starts.iter() { let matches = crate::analysis::flirt::match_flirt(&pe.module, &sigs, function)?; match matches.len().cmp(&1) { std::cmp::Ordering::Less => { // no matches continue; } std::cmp::Ordering::Equal => { // exactly one match: perfect. if let Some(name) = matches[0].get_name() { log::info!("FLIRT match: {:#x}: {}", function, name); names.insert(function, name.to_string()); } else { // no associated name, just know its a library function continue; } } std::cmp::Ordering::Greater =>
} } for name in [ "kernel32.dll!ExitProcess", "kernel32.dll!ExitThread", "exit", "_exit", "__exit", "__amsg_exit", ] { if let Some(&va) = names.addresses_by_name.get(name) { log::info!("noret via name: {}: {:#x}", name, va); noret.extend(crate::analysis::cfg::noret::cfg_mark_noret(&pe.module, &mut cfg, va)?); } } let thunks = crate::analysis::cfg::thunk::find_thunks(&cfg, function_starts.iter()); let mut functions: BTreeMap<VA, FunctionAnalysis> = Default::default(); for va in function_starts { let mut flags = FunctionFlags::empty(); if noret.contains(&va) { flags.set(FunctionFlags::NORET, true); } if thunks.contains(&va) { flags.set(FunctionFlags::THUNK, true); } functions.insert(va, FunctionAnalysis { flags }); } for &function in functions.keys() { if names.contains_address(function).not() { names.insert(function, format!("sub_{:x}", function)); } } Ok(PEWorkspace { config, pe, cfg, analysis: WorkspaceAnalysis { functions, imports, names, }, }) } } #[cfg(test)] mod tests { use super::*; use crate::rsrc::*; use anyhow::Result; #[test] fn nop() -> Result<()> { crate::test::init_logging(); let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let config = get_config(); let ws = PEWorkspace::from_pe(config, pe)?; // entry point assert!(ws.analysis.functions.contains_key(&0x401081)); // main assert!(ws.analysis.functions.contains_key(&0x401000)); assert!(ws.analysis.imports.contains_key(&0x40600C)); assert!(ws .analysis .names .contains_name(&String::from("kernel32.dll!ExitProcess"))); assert!(ws.analysis.names.contains_address(0x40600C)); // 0x401C4E: void __cdecl __noreturn __crtExitProcess(UINT uExitCode) assert!(ws.analysis.functions[&0x401C4E].flags.intersects(FunctionFlags::NORET)); // ``` // .text:00405F42 ; void __stdcall RtlUnwind(PVOID TargetFrame, PVOID TargetIp, PEXCEPTION_RECORD ExceptionRecord, PVOID ReturnValue) // .text:00405F42 RtlUnwind proc near ; CODE XREF: __global_unwind2+13↑p // .text:00405F42 // .text:00405F42 TargetFrame = dword ptr 4 // .text:00405F42 TargetIp = dword ptr 8 // .text:00405F42 ExceptionRecord = dword ptr 0Ch // .text:00405F42 ReturnValue = dword ptr 10h // .text:00405F42 // .text:00405F42 000 FF 25 7C 60 40 00 jmp ds:__imp_RtlUnwind // .text:00405F42 RtlUnwind endp // ``` assert!(ws.analysis.functions[&0x405F42].flags.intersects(FunctionFlags::THUNK)); // via FLIRT 0x401da9: _exit assert!(ws.analysis.functions.contains_key(&0x401da9)); assert!(ws.analysis.names.contains_name(&String::from("_exit"))); assert!(ws.analysis.functions[&0x401da9].flags.intersects(FunctionFlags::NORET)); Ok(()) } }
{ // colliding matches, can't determine the name. // TODO: maybe check for special case that all names are the same? log::info!("FLIRT match: {:#x}: {} collisions", function, matches.len()); continue; }
conditional_block
mod.rs
use std::{ collections::{BTreeMap, BTreeSet}, ops::Not, }; use anyhow::Result; use bitflags::bitflags; use crate::{ analysis::{ cfg::{flow::Flow, InstructionIndex, CFG}, pe::{Import, ImportedSymbol}, }, loader::pe::PE, VA, }; pub mod cfg; pub mod formatter; bitflags! { pub struct FunctionFlags: u8 { const NORET = 0b0000_0001; const THUNK = 0b0000_0010; } } pub struct FunctionAnalysis { pub flags: FunctionFlags, } #[derive(Default)] pub struct NameIndex { pub names_by_address: BTreeMap<VA, String>, pub addresses_by_name: BTreeMap<String, VA>, } impl NameIndex { pub fn insert(&mut self, va: VA, name: String)
pub fn contains_address(&self, va: VA) -> bool { return self.names_by_address.get(&va).is_some(); } pub fn contains_name(&self, name: &str) -> bool { return self.addresses_by_name.get(name).is_some(); } } pub struct WorkspaceAnalysis { // derived from: // - file format analysis passes // - cfg flow analysis (call insns) // - manual actions pub functions: BTreeMap<VA, FunctionAnalysis>, // derived from: // - file format analysis pass: pe::get_improts() pub imports: BTreeMap<VA, Import>, // derived from: // - user names // - export names // - imported symbols // - flirt sigs pub names: NameIndex, } pub struct PEWorkspace { pub config: Box<dyn cfg::Configuration>, pub pe: PE, pub cfg: CFG, pub analysis: WorkspaceAnalysis, } impl PEWorkspace { pub fn from_pe(config: Box<dyn cfg::Configuration>, pe: PE) -> Result<PEWorkspace> { let mut insns: InstructionIndex = Default::default(); let mut function_starts: BTreeSet<VA> = Default::default(); function_starts.extend(crate::analysis::pe::entrypoints::find_pe_entrypoint(&pe)?); function_starts.extend(crate::analysis::pe::exports::find_pe_exports(&pe)?); function_starts.extend(crate::analysis::pe::safeseh::find_pe_safeseh_handlers(&pe)?); function_starts.extend(crate::analysis::pe::runtime_functions::find_pe_runtime_functions(&pe)?); function_starts.extend(crate::analysis::pe::control_flow_guard::find_pe_cfguard_functions(&pe)?); // heuristics: // function_starts.extend(crate::analysis::pe::call_targets:: // find_pe_call_targets(pe)?); function_starts.extend(crate::analysis:: // pe::patterns::find_function_prologues(pe)?); function_starts. // extend(crate::analysis::pe::pointers:: // find_pe_nonrelocated_executable_pointers(pe)?; TODO: only do the // above searches in unrecovered regions. for &function in function_starts.iter() { insns.build_index(&pe.module, function)?; } let mut cfg = CFG::from_instructions(&pe.module, insns)?; let mut noret = crate::analysis::pe::noret_imports::cfg_prune_noret_imports(&pe, &mut cfg)?; let mut function_starts = function_starts .into_iter() .filter(|va| cfg.insns.insns_by_address.contains_key(va)) .collect::<BTreeSet<VA>>(); let call_targets = cfg .basic_blocks .blocks_by_address .keys() .cloned() .filter(|bb| { cfg.flows.flows_by_dst[bb] .iter() .any(|flow| matches!(flow, Flow::Call(_))) }) .collect::<BTreeSet<VA>>(); function_starts.extend(call_targets); let imports = crate::analysis::pe::get_imports(&pe)?; let mut names: NameIndex = Default::default(); for import in imports.values() { let name = match &import.symbol { ImportedSymbol::Name(name) => format!("{}!{}", import.dll, name), ImportedSymbol::Ordinal(ordinal) => format!("{}!#{}", import.dll, ordinal), }; names.insert(import.address, name); } let sigs = config.get_sigs()?; for &function in function_starts.iter() { let matches = crate::analysis::flirt::match_flirt(&pe.module, &sigs, function)?; match matches.len().cmp(&1) { std::cmp::Ordering::Less => { // no matches continue; } std::cmp::Ordering::Equal => { // exactly one match: perfect. if let Some(name) = matches[0].get_name() { log::info!("FLIRT match: {:#x}: {}", function, name); names.insert(function, name.to_string()); } else { // no associated name, just know its a library function continue; } } std::cmp::Ordering::Greater => { // colliding matches, can't determine the name. // TODO: maybe check for special case that all names are the same? log::info!("FLIRT match: {:#x}: {} collisions", function, matches.len()); continue; } } } for name in [ "kernel32.dll!ExitProcess", "kernel32.dll!ExitThread", "exit", "_exit", "__exit", "__amsg_exit", ] { if let Some(&va) = names.addresses_by_name.get(name) { log::info!("noret via name: {}: {:#x}", name, va); noret.extend(crate::analysis::cfg::noret::cfg_mark_noret(&pe.module, &mut cfg, va)?); } } let thunks = crate::analysis::cfg::thunk::find_thunks(&cfg, function_starts.iter()); let mut functions: BTreeMap<VA, FunctionAnalysis> = Default::default(); for va in function_starts { let mut flags = FunctionFlags::empty(); if noret.contains(&va) { flags.set(FunctionFlags::NORET, true); } if thunks.contains(&va) { flags.set(FunctionFlags::THUNK, true); } functions.insert(va, FunctionAnalysis { flags }); } for &function in functions.keys() { if names.contains_address(function).not() { names.insert(function, format!("sub_{:x}", function)); } } Ok(PEWorkspace { config, pe, cfg, analysis: WorkspaceAnalysis { functions, imports, names, }, }) } } #[cfg(test)] mod tests { use super::*; use crate::rsrc::*; use anyhow::Result; #[test] fn nop() -> Result<()> { crate::test::init_logging(); let buf = get_buf(Rsrc::NOP); let pe = crate::loader::pe::PE::from_bytes(&buf)?; let config = get_config(); let ws = PEWorkspace::from_pe(config, pe)?; // entry point assert!(ws.analysis.functions.contains_key(&0x401081)); // main assert!(ws.analysis.functions.contains_key(&0x401000)); assert!(ws.analysis.imports.contains_key(&0x40600C)); assert!(ws .analysis .names .contains_name(&String::from("kernel32.dll!ExitProcess"))); assert!(ws.analysis.names.contains_address(0x40600C)); // 0x401C4E: void __cdecl __noreturn __crtExitProcess(UINT uExitCode) assert!(ws.analysis.functions[&0x401C4E].flags.intersects(FunctionFlags::NORET)); // ``` // .text:00405F42 ; void __stdcall RtlUnwind(PVOID TargetFrame, PVOID TargetIp, PEXCEPTION_RECORD ExceptionRecord, PVOID ReturnValue) // .text:00405F42 RtlUnwind proc near ; CODE XREF: __global_unwind2+13↑p // .text:00405F42 // .text:00405F42 TargetFrame = dword ptr 4 // .text:00405F42 TargetIp = dword ptr 8 // .text:00405F42 ExceptionRecord = dword ptr 0Ch // .text:00405F42 ReturnValue = dword ptr 10h // .text:00405F42 // .text:00405F42 000 FF 25 7C 60 40 00 jmp ds:__imp_RtlUnwind // .text:00405F42 RtlUnwind endp // ``` assert!(ws.analysis.functions[&0x405F42].flags.intersects(FunctionFlags::THUNK)); // via FLIRT 0x401da9: _exit assert!(ws.analysis.functions.contains_key(&0x401da9)); assert!(ws.analysis.names.contains_name(&String::from("_exit"))); assert!(ws.analysis.functions[&0x401da9].flags.intersects(FunctionFlags::NORET)); Ok(()) } }
{ self.names_by_address.insert(va, name.clone()); self.addresses_by_name.insert(name, va); }
identifier_body
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding::TextDecoderMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::str::USVString; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use encoding::Encoding; use encoding::label::encoding_from_whatwg_label; use encoding::types::{EncodingRef, DecoderTrap}; use js::jsapi::JS_GetObjectAsArrayBufferView; use js::jsapi::{JSContext, JSObject}; use std::borrow::ToOwned; use std::ptr; use std::slice; #[dom_struct] pub struct TextDecoder { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-encoding"] encoding: EncodingRef, fatal: bool, } impl TextDecoder { fn new_inherited(encoding: EncodingRef, fatal: bool) -> TextDecoder { TextDecoder { reflector_: Reflector::new(), encoding: encoding, fatal: fatal, } } fn make_range_error() -> Fallible<Root<TextDecoder>> { Err(Error::Range("The given encoding is not supported.".to_owned())) } pub fn new(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder> { reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) } /// https://encoding.spec.whatwg.org/#dom-textdecoder pub fn Constructor(global: GlobalRef, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible<Root<TextDecoder>> { let encoding = match encoding_from_whatwg_label(&label) { None => return TextDecoder::make_range_error(), Some(enc) => enc }; // The rust-encoding crate has WHATWG compatibility, so we are // guaranteed to have a whatwg_name because we successfully got // the encoding from encoding_from_whatwg_label. // Use match + panic! instead of unwrap for better error message match encoding.whatwg_name() { None => panic!("Label {} fits valid encoding without valid name", label), Some("replacement") => return TextDecoder::make_range_error(), _ => () }; Ok(TextDecoder::new(global, encoding, options.fatal)) } } impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding fn Encoding(&self) -> DOMString { self.encoding.whatwg_name().unwrap().to_owned() } // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal fn Fatal(&self) -> bool { self.fatal } #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible<USVString> { let input = match input { Some(input) => input, None => return Ok(USVString("".to_owned())), };
let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to TextDecoder.decode is not an ArrayBufferView".to_owned())); } let buffer = unsafe { slice::from_raw_parts(data as *const _, length as usize) }; let trap = if self.fatal { DecoderTrap::Strict } else { DecoderTrap::Replace }; match self.encoding.decode(buffer, trap) { Ok(s) => Ok(USVString(s)), Err(_) => Err(Error::Type("Decoding failed".to_owned())), } } }
random_line_split
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding::TextDecoderMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::str::USVString; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use encoding::Encoding; use encoding::label::encoding_from_whatwg_label; use encoding::types::{EncodingRef, DecoderTrap}; use js::jsapi::JS_GetObjectAsArrayBufferView; use js::jsapi::{JSContext, JSObject}; use std::borrow::ToOwned; use std::ptr; use std::slice; #[dom_struct] pub struct TextDecoder { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-encoding"] encoding: EncodingRef, fatal: bool, } impl TextDecoder { fn new_inherited(encoding: EncodingRef, fatal: bool) -> TextDecoder { TextDecoder { reflector_: Reflector::new(), encoding: encoding, fatal: fatal, } } fn make_range_error() -> Fallible<Root<TextDecoder>> { Err(Error::Range("The given encoding is not supported.".to_owned())) } pub fn
(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder> { reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) } /// https://encoding.spec.whatwg.org/#dom-textdecoder pub fn Constructor(global: GlobalRef, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible<Root<TextDecoder>> { let encoding = match encoding_from_whatwg_label(&label) { None => return TextDecoder::make_range_error(), Some(enc) => enc }; // The rust-encoding crate has WHATWG compatibility, so we are // guaranteed to have a whatwg_name because we successfully got // the encoding from encoding_from_whatwg_label. // Use match + panic! instead of unwrap for better error message match encoding.whatwg_name() { None => panic!("Label {} fits valid encoding without valid name", label), Some("replacement") => return TextDecoder::make_range_error(), _ => () }; Ok(TextDecoder::new(global, encoding, options.fatal)) } } impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding fn Encoding(&self) -> DOMString { self.encoding.whatwg_name().unwrap().to_owned() } // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal fn Fatal(&self) -> bool { self.fatal } #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible<USVString> { let input = match input { Some(input) => input, None => return Ok(USVString("".to_owned())), }; let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to TextDecoder.decode is not an ArrayBufferView".to_owned())); } let buffer = unsafe { slice::from_raw_parts(data as *const _, length as usize) }; let trap = if self.fatal { DecoderTrap::Strict } else { DecoderTrap::Replace }; match self.encoding.decode(buffer, trap) { Ok(s) => Ok(USVString(s)), Err(_) => Err(Error::Type("Decoding failed".to_owned())), } } }
new
identifier_name
textdecoder.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding::TextDecoderMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::str::USVString; use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{Reflector, reflect_dom_object}; use util::str::DOMString; use encoding::Encoding; use encoding::label::encoding_from_whatwg_label; use encoding::types::{EncodingRef, DecoderTrap}; use js::jsapi::JS_GetObjectAsArrayBufferView; use js::jsapi::{JSContext, JSObject}; use std::borrow::ToOwned; use std::ptr; use std::slice; #[dom_struct] pub struct TextDecoder { reflector_: Reflector, #[ignore_heap_size_of = "Defined in rust-encoding"] encoding: EncodingRef, fatal: bool, } impl TextDecoder { fn new_inherited(encoding: EncodingRef, fatal: bool) -> TextDecoder { TextDecoder { reflector_: Reflector::new(), encoding: encoding, fatal: fatal, } } fn make_range_error() -> Fallible<Root<TextDecoder>> { Err(Error::Range("The given encoding is not supported.".to_owned())) } pub fn new(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder>
/// https://encoding.spec.whatwg.org/#dom-textdecoder pub fn Constructor(global: GlobalRef, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible<Root<TextDecoder>> { let encoding = match encoding_from_whatwg_label(&label) { None => return TextDecoder::make_range_error(), Some(enc) => enc }; // The rust-encoding crate has WHATWG compatibility, so we are // guaranteed to have a whatwg_name because we successfully got // the encoding from encoding_from_whatwg_label. // Use match + panic! instead of unwrap for better error message match encoding.whatwg_name() { None => panic!("Label {} fits valid encoding without valid name", label), Some("replacement") => return TextDecoder::make_range_error(), _ => () }; Ok(TextDecoder::new(global, encoding, options.fatal)) } } impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding fn Encoding(&self) -> DOMString { self.encoding.whatwg_name().unwrap().to_owned() } // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal fn Fatal(&self) -> bool { self.fatal } #[allow(unsafe_code)] // https://encoding.spec.whatwg.org/#dom-textdecoder-decode fn Decode(&self, _cx: *mut JSContext, input: Option<*mut JSObject>) -> Fallible<USVString> { let input = match input { Some(input) => input, None => return Ok(USVString("".to_owned())), }; let mut length = 0; let mut data = ptr::null_mut(); if unsafe { JS_GetObjectAsArrayBufferView(input, &mut length, &mut data).is_null() } { return Err(Error::Type("Argument to TextDecoder.decode is not an ArrayBufferView".to_owned())); } let buffer = unsafe { slice::from_raw_parts(data as *const _, length as usize) }; let trap = if self.fatal { DecoderTrap::Strict } else { DecoderTrap::Replace }; match self.encoding.decode(buffer, trap) { Ok(s) => Ok(USVString(s)), Err(_) => Err(Error::Type("Decoding failed".to_owned())), } } }
{ reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) }
identifier_body
hunter.rs
// // Copyright 2021 The Project Oak 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,
// use common::module_common::{move_by, print_str, srand, Context, GRID_H, GRID_W}; use common::println; use common::shared::{cptr, State}; #[no_mangle] pub extern "C" fn malloc_(size: usize) -> cptr { let vec: Vec<u8> = Vec::with_capacity(size); let ptr = vec.as_ptr(); std::mem::forget(vec); // Leak the vector ptr as cptr } #[no_mangle] pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context { Context::new_unowned(ro_ptr, rw_ptr) } #[no_mangle] pub extern "C" fn update_context(ctx: &mut Context, ro_ptr: cptr, rw_ptr: cptr) { ctx.update(ro_ptr, rw_ptr); } #[no_mangle] pub extern "C" fn init(ctx: &mut Context, rand_seed: i32) { srand(rand_seed as usize); ctx.hunter.x = GRID_W / 2; ctx.hunter.y = GRID_H / 2; } #[no_mangle] pub extern "C" fn tick(ctx: &mut Context) { // Find the closest runner and move towards it. let mut min_dx: i32 = 0; let mut min_dy: i32 = 0; let mut min_dist = 99999; for r in &*ctx.runners { if r.state == State::Dead { continue; } let dx: i32 = r.x as i32 - ctx.hunter.x as i32; let dy: i32 = r.y as i32 - ctx.hunter.y as i32; let dist = dx * dx + dy * dy; if dist < min_dist { min_dx = dx; min_dy = dy; min_dist = dist; } } move_by(&ctx.grid, &mut ctx.hunter.x, &mut ctx.hunter.y, min_dx, min_dy); } #[no_mangle] pub extern "C" fn large_alloc() { println!("[h] Requesting large allocation"); std::mem::forget(Vec::<u8>::with_capacity(100000)); } #[no_mangle] pub extern "C" fn modify_grid(ctx: &mut Context) { println!("[h] Attempting to write to read-only memory..."); ctx.grid[0][0] = 2; } fn main() { println!("hunter: Not meant to be run as a main"); }
// 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.
random_line_split