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 |
---|---|---|---|---|
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self {
VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element {
self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn replace(&mut self, i: usize, val: Self::Element) |
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
}
| {
self.vector.replace(i, val.vector)
} | identifier_body |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self { | self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn replace(&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
} | VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element { | random_line_split |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultAllocator: Allocator<N, D> + Allocator<N::Element, D>,
{
type Element = Translation<N::Element, D>;
type SimdBool = N::SimdBool;
#[inline]
fn lanes() -> usize {
N::lanes()
}
#[inline]
fn splat(val: Self::Element) -> Self {
VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element {
self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn | (&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
}
| replace | identifier_name |
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if!org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo|!repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if!github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if!pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
} | let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) {
println!("{}", message);
::std::process::exit(exit_code);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn suggestion_for_org_sad() {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
} | random_line_split |
|
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if!org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo|!repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if!github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if!pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
}
let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) {
println!("{}", message);
::std::process::exit(exit_code);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn | () {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
}
| suggestion_for_org_sad | identifier_name |
main.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#[macro_use]
extern crate clap;
extern crate reqwest;
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate indicatif;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate hyper;
use clap::App;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VERSION: String = {
let yaml = load_yaml!("release-party.yml");
let app = App::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
print_message_and_exit(
&format!("{} environment variable should be set", GITHUB_TOKEN),
-1,
);
unreachable!();
}
};
let reqwest_client = get_reqwest_client(&token);
let links = get_pr_links(
&get_repos_we_care_about(&org_url, &reqwest_client),
&reqwest_client,
is_dryrun(&matches),
);
print_party_links(links);
}
fn version_string(app: &App) -> String {
let mut version: Vec<u8> = Vec::new();
app.write_version(&mut version)
.expect("Should write to version vec.");
String::from_utf8(version).expect("Version text should be utf8 text")
}
fn is_dryrun(matches: &clap::ArgMatches) -> bool {
matches.is_present("DRYRUN")
}
fn org_is_just_org(org: &str) -> bool {
if org.contains("https://api.github.com") {
return false;
}
true
}
fn suggest_org_arg(org: &str) -> Result<String, String> {
if org.starts_with("https://api.github.com/orgs/") && org.ends_with("/repos") {
let suggestion = org
.replace("https://api.github.com/orgs/", "")
.replace("/repos", "");
return Ok(suggestion.to_string());
}
Err("Can't make a suggestion".to_owned())
}
fn make_org_url(matches: &clap::ArgMatches) -> String {
let org = matches
.value_of("ORG")
.expect("Please specify a github org");
if!org_is_just_org(&org) {
match suggest_org_arg(&org) {
Ok(suggestion) => {
print_message_and_exit(&format!("Try this for the org value: {}", suggestion), -1)
}
Err(_) => {
print_message_and_exit(&"Please make org just the organization name.".to_string(), -1)
}
}
}
format!("https://api.github.com/orgs/{}/repos", org)
}
fn get_pr_links(
repos: &Vec<github::GithubRepo>,
reqwest_client: &reqwest::Client,
dryrun: bool,
) -> Vec<Option<String>> {
let pbar = ProgressBar::new(repos.len() as u64);
pbar.set_style(ProgressStyle::default_bar().template("[{elapsed_precise}] {bar:50.cyan/blue} {pos:>7}/{len:7} {msg}"));
let mut pr_links: Vec<Option<String>> = repos
.iter()
.map(|repo| {
pbar.inc(1);
let i = match get_release_pr_for(&repo, reqwest_client, dryrun) {
Some(pr_url) => Some(pr_url),
None => None,
};
// update the PR body
// pr_url will look like https://github.com/matthewkmayer/release-party-BR/pull/39
// split by '/' and grab last chunk.
if let Some(ref pr_url) = i {
let pr_split = pr_url.split('/').collect::<Vec<&str>>();
let pr_num = pr_split.last().expect("PR link malformed?");
github::update_pr_body(repo, pr_num, reqwest_client, &RP_VERSION);
}
i
})
.collect();
pbar.finish();
// only keep the Some(PR_URL) items:
pr_links.retain(|maybe_pr_link| maybe_pr_link.is_some());
pr_links
}
fn get_reqwest_client(token: &str) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
USER_AGENT,
USERAGENT.parse().expect("useragent should be a string"),
);
headers.insert(
AUTHORIZATION,
format!("token {}", token)
.parse()
.expect("token should be a string"),
);
match reqwest::Client::builder().default_headers(headers).build() {
Ok(new_client) => new_client,
Err(e) => panic!("Couldn't create new reqwest client: {}", e),
}
}
fn get_repos_we_care_about(
github_org_url: &str,
reqwest_client: &reqwest::Client,
) -> Vec<github::GithubRepo> {
let mut repos = match github::get_repos_at(github_org_url, reqwest_client) {
Ok(repos) => repos,
Err(e) => panic!(format!("Couldn't get repos from github: {}", e)),
};
let repos_to_ignore = ignored_repos();
// remove repos we don't care about:
repos.retain(|repo|!repos_to_ignore.contains(&repo.name));
repos
}
fn get_release_pr_for(
repo: &github::GithubRepo,
client: &reqwest::Client,
dryrun: bool,
) -> Option<String> {
match github::existing_release_pr_location(repo, client) {
Some(url) => Some(url),
None => {
if!github::is_release_up_to_date_with_master(&repo.url, client) {
if dryrun {
Some(format!("Dry run: {} would get a release PR.", repo.url))
} else {
match github::create_release_pull_request(repo, client) {
Ok(pr_url) => Some(pr_url),
Err(_) => None,
}
}
} else {
None
}
}
}
}
fn print_party_links(pr_links: Vec<Option<String>>) {
if!pr_links.is_empty() {
println!("\nIt's a release party! PRs to review and approve:");
for link in pr_links {
match link {
Some(pr_link) => println!("{}", pr_link),
None => println!("Party link is None: this shouldn't happen."),
}
}
} else {
println!("\nNo party today, all releases are done.");
}
}
#[derive(Deserialize, Debug)]
struct IgnoredRepo {
ignore: Option<Vec<String>>,
}
fn ignored_repos() -> Vec<String> {
let hfi = match dirs::home_dir() {
Some(path) => {
if Path::new(&path).join(".ignoredrepos.toml").exists() {
Some(Path::new(&path).join(".ignoredrepos.toml"))
} else {
None
}
},
None => None,
};
let lfi = match Path::new("ignoredrepos.toml").exists() {
true => Some(Path::new("ignoredrepos.toml").to_path_buf()),
false => None,
};
let fi = match (lfi, hfi) {
(Some(a), _) => a,
(None, Some(b)) => b,
(_, _) => {println!("The ignoredrepos.toml file not found"); return Vec::new()},
};
let mut f = match File::open(&fi) {
Ok(file) => file,
Err(e) => {
println!(
"Couldn't load ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
println!(
"Found ignoredrepos.toml file at {:#?}",
fi
);
let mut buffer = String::new();
match f.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
println!(
"Couldn't read from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
}
let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}
};
match ignored.ignore {
Some(repos_to_ignore) => repos_to_ignore,
None => Vec::new(),
}
}
fn print_message_and_exit(message: &str, exit_code: i32) |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
false,
org_is_just_org("https://api.github.com/orgs/ORG-HERE/repos")
);
}
#[test]
fn handle_okay_org() {
assert_eq!(true, org_is_just_org("ORG-HERE"));
}
#[test]
fn suggestion_for_org_happy() {
assert_eq!(
"ORG-HERE",
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/repos").unwrap()
);
}
#[test]
fn suggestion_for_org_sad() {
assert_eq!(
true,
suggest_org_arg("https://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("http://api.github.com/orgs/ORG-HERE/").is_err()
);
assert_eq!(
true,
suggest_org_arg("api.github.com/orgs/ORG-HERE/repos").is_err()
);
}
}
| {
println!("{}", message);
::std::process::exit(exit_code);
} | identifier_body |
volumes.rs | use std::path::PathBuf;
use std::collections::BTreeMap;
use quire::validate as V;
use quire::ast::{Ast, Tag};
use libc::{uid_t, gid_t};
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct SnapshotInfo {
pub size: usize,
pub owner_uid: Option<uid_t>,
pub owner_gid: Option<gid_t>,
pub container: Option<String>,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct PersistentInfo {
pub name: String,
pub owner_uid: uid_t,
pub owner_gid: gid_t,
pub init_command: Option<String>,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub enum Volume {
Tmpfs(TmpfsInfo),
BindRW(PathBuf),
BindRO(PathBuf),
Empty,
VaggaBin,
Snapshot(SnapshotInfo),
Container(String),
Persistent(PersistentInfo),
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct Dir {
pub mode: u32,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct TmpfsInfo {
pub size: usize,
pub mode: u32,
pub subdirs: BTreeMap<PathBuf, Dir>,
pub files: BTreeMap<PathBuf, Option<String>>,
}
pub fn volume_validator<'x>() -> V::Enum<'x> {
V::Enum::new()
.option("Tmpfs", V::Structure::new()
.member("size", V::Numeric::new()
.min(0).default(100*1024*1024))
.member("mode", V::Numeric::new()
.min(0).max(0o1777).default(0o1777))
.member("subdirs",
V::Mapping::new( | V::Directory::new().is_absolute(false),
V::Structure::new()
.member("mode", V::Numeric::new()
.min(0).max(0o1777).default(0o755))
))
.member("files",
V::Mapping::new(
V::Directory::new().is_absolute(false),
V::Scalar::new().optional(),
)))
.option("VaggaBin", V::Nothing)
.option("BindRW", V::Scalar::new())
.option("BindRO", V::Scalar::new())
.option("Empty", V::Nothing)
.option("Snapshot", V::Structure::new()
.member("container", V::Scalar::new().optional())
.member("size", V::Numeric::new().min(0).default(100*1024*1024))
.member("owner_uid", V::Numeric::new().min(0).optional())
.member("owner_gid", V::Numeric::new().min(0).optional())
)
.option("Container", V::Scalar::new())
.option("Persistent", V::Structure::new()
.member("name", V::Scalar::new())
.member("init_command", V::Scalar::new().optional())
.member("owner_uid", V::Numeric::new().min(0).default(0))
.member("owner_gid", V::Numeric::new().min(0).default(0))
.parser(persistent_volume_string))
}
fn persistent_volume_string(ast: Ast) -> BTreeMap<String, Ast> {
match ast {
Ast::Scalar(pos, _, style, value) => {
let mut map = BTreeMap::new();
map.insert("name".to_string(),
Ast::Scalar(pos.clone(), Tag::NonSpecific, style, value));
map
},
_ => unreachable!(),
}
} | random_line_split |
|
volumes.rs | use std::path::PathBuf;
use std::collections::BTreeMap;
use quire::validate as V;
use quire::ast::{Ast, Tag};
use libc::{uid_t, gid_t};
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct SnapshotInfo {
pub size: usize,
pub owner_uid: Option<uid_t>,
pub owner_gid: Option<gid_t>,
pub container: Option<String>,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct | {
pub name: String,
pub owner_uid: uid_t,
pub owner_gid: gid_t,
pub init_command: Option<String>,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub enum Volume {
Tmpfs(TmpfsInfo),
BindRW(PathBuf),
BindRO(PathBuf),
Empty,
VaggaBin,
Snapshot(SnapshotInfo),
Container(String),
Persistent(PersistentInfo),
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct Dir {
pub mode: u32,
}
#[derive(RustcDecodable, Clone, PartialEq, Eq)]
pub struct TmpfsInfo {
pub size: usize,
pub mode: u32,
pub subdirs: BTreeMap<PathBuf, Dir>,
pub files: BTreeMap<PathBuf, Option<String>>,
}
pub fn volume_validator<'x>() -> V::Enum<'x> {
V::Enum::new()
.option("Tmpfs", V::Structure::new()
.member("size", V::Numeric::new()
.min(0).default(100*1024*1024))
.member("mode", V::Numeric::new()
.min(0).max(0o1777).default(0o1777))
.member("subdirs",
V::Mapping::new(
V::Directory::new().is_absolute(false),
V::Structure::new()
.member("mode", V::Numeric::new()
.min(0).max(0o1777).default(0o755))
))
.member("files",
V::Mapping::new(
V::Directory::new().is_absolute(false),
V::Scalar::new().optional(),
)))
.option("VaggaBin", V::Nothing)
.option("BindRW", V::Scalar::new())
.option("BindRO", V::Scalar::new())
.option("Empty", V::Nothing)
.option("Snapshot", V::Structure::new()
.member("container", V::Scalar::new().optional())
.member("size", V::Numeric::new().min(0).default(100*1024*1024))
.member("owner_uid", V::Numeric::new().min(0).optional())
.member("owner_gid", V::Numeric::new().min(0).optional())
)
.option("Container", V::Scalar::new())
.option("Persistent", V::Structure::new()
.member("name", V::Scalar::new())
.member("init_command", V::Scalar::new().optional())
.member("owner_uid", V::Numeric::new().min(0).default(0))
.member("owner_gid", V::Numeric::new().min(0).default(0))
.parser(persistent_volume_string))
}
fn persistent_volume_string(ast: Ast) -> BTreeMap<String, Ast> {
match ast {
Ast::Scalar(pos, _, style, value) => {
let mut map = BTreeMap::new();
map.insert("name".to_string(),
Ast::Scalar(pos.clone(), Tag::NonSpecific, style, value));
map
},
_ => unreachable!(),
}
}
| PersistentInfo | identifier_name |
info_result.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// Generates a extension for the `Result<T, E>`, named `DebugResult` which has functionality to
// print either `T` or `E` via `info!()`.
generate_result_logging_extension!( | map_info,
map_info_str,
map_info_err,
map_info_err_str,
|s| { info!("{}", s); }
); | InfoResult, | random_line_split |
fuzz_target_1.rs | #![no_main]
#[macro_use] extern crate libfuzzer_sys;
extern crate quick_xml;
| fuzz_target!(|data: &[u8]| {
// fuzzed code goes here
let cursor = Cursor::new(data);
let mut reader = Reader::from_reader(cursor);
let mut buf = vec![];
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e))=> {
if e.unescaped().is_err() {
break;
}
for a in e.attributes() {
if a.ok().map_or(false, |a| a.unescaped_value().is_err()) {
break;
}
}
}
Ok(Event::Text(ref e)) | Ok(Event::Comment(ref e))
| Ok(Event::CData(ref e)) | Ok(Event::PI(ref e))
| Ok(Event::DocType(ref e)) => {
if e.unescaped().is_err() {
break;
}
}
Ok(Event::Decl(ref e)) => {
let _ = e.version();
let _ = e.encoding();
let _ = e.standalone();
}
Ok(Event::End(_)) => (),
Ok(Event::Eof) | Err(..) => break,
}
buf.clear();
}
}); | use quick_xml::Reader;
use quick_xml::events::Event;
use std::io::Cursor;
| random_line_split |
cabi_arm.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
use llvm::{Integer, Pointer, Float, Double, Struct, Array, Vector};
use llvm::{StructRetAttribute, ZExtAttribute};
use trans::cabi::{FnType, ArgType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
pub enum Flavor {
General,
Ios
}
type TyAlignFn = fn(ty: Type) -> uint;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1) / a * a;
}
fn align(off: uint, ty: Type, align_fn: TyAlignFn) -> uint {
let a = align_fn(ty);
return align_up_to(off, a);
}
fn general_ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, general_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
general_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
general_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
// For more information see:
// ARMv7
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv7FunctionCallingConventions.html
// ARMv6
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html
fn ios_ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => cmp::min(4, ((ty.int_width() as uint) + 7) / 8),
Pointer => 4,
Float => 4,
Double => 4,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ios_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ios_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ios_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type, align_fn: TyAlignFn) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t, align_fn))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter()
.fold(0, |s, t| {
align(s, *t, align_fn) + ty_size(*t, align_fn)
});
align(size, ty, align_fn)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
}
let size = ty_size(ty, align_fn);
if size <= 4 {
let llty = if size <= 1 {
Type::i8(ccx)
} else if size <= 2 {
Type::i16(ccx)
} else {
Type::i32(ccx)
};
return ArgType::direct(ty, Some(llty), None, None);
}
ArgType::indirect(ty, Some(StructRetAttribute))
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
} | let align = align_fn(ty);
let size = ty_size(ty, align_fn);
let llty = if align <= 4 {
Type::array(&Type::i32(ccx), ((size + 3) / 4) as u64)
} else {
Type::array(&Type::i64(ccx), ((size + 7) / 8) as u64)
};
ArgType::direct(ty, Some(llty), None, None)
}
fn is_reg_ty(ty: Type) -> bool {
match ty.kind() {
Integer
| Pointer
| Float
| Double
| Vector => true,
_ => false
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool,
flavor: Flavor) -> FnType {
let align_fn = match flavor {
Flavor::General => general_ty_align as TyAlignFn,
Flavor::Ios => ios_ty_align as TyAlignFn,
};
let mut arg_tys = Vec::new();
for &aty in atys {
let ty = classify_arg_ty(ccx, aty, align_fn);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty, align_fn)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
} | random_line_split |
|
cabi_arm.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
use llvm::{Integer, Pointer, Float, Double, Struct, Array, Vector};
use llvm::{StructRetAttribute, ZExtAttribute};
use trans::cabi::{FnType, ArgType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
pub enum Flavor {
General,
Ios
}
type TyAlignFn = fn(ty: Type) -> uint;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1) / a * a;
}
fn align(off: uint, ty: Type, align_fn: TyAlignFn) -> uint {
let a = align_fn(ty);
return align_up_to(off, a);
}
fn general_ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, general_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
general_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
general_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
// For more information see:
// ARMv7
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv7FunctionCallingConventions.html
// ARMv6
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html
fn ios_ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => cmp::min(4, ((ty.int_width() as uint) + 7) / 8),
Pointer => 4,
Float => 4,
Double => 4,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ios_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ios_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ios_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type, align_fn: TyAlignFn) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t, align_fn))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter()
.fold(0, |s, t| {
align(s, *t, align_fn) + ty_size(*t, align_fn)
});
align(size, ty, align_fn)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
}
let size = ty_size(ty, align_fn);
if size <= 4 {
let llty = if size <= 1 {
Type::i8(ccx)
} else if size <= 2 {
Type::i16(ccx)
} else {
Type::i32(ccx)
};
return ArgType::direct(ty, Some(llty), None, None);
}
ArgType::indirect(ty, Some(StructRetAttribute))
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType |
fn is_reg_ty(ty: Type) -> bool {
match ty.kind() {
Integer
| Pointer
| Float
| Double
| Vector => true,
_ => false
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool,
flavor: Flavor) -> FnType {
let align_fn = match flavor {
Flavor::General => general_ty_align as TyAlignFn,
Flavor::Ios => ios_ty_align as TyAlignFn,
};
let mut arg_tys = Vec::new();
for &aty in atys {
let ty = classify_arg_ty(ccx, aty, align_fn);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty, align_fn)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
}
let align = align_fn(ty);
let size = ty_size(ty, align_fn);
let llty = if align <= 4 {
Type::array(&Type::i32(ccx), ((size + 3) / 4) as u64)
} else {
Type::array(&Type::i64(ccx), ((size + 7) / 8) as u64)
};
ArgType::direct(ty, Some(llty), None, None)
} | identifier_body |
cabi_arm.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
use llvm::{Integer, Pointer, Float, Double, Struct, Array, Vector};
use llvm::{StructRetAttribute, ZExtAttribute};
use trans::cabi::{FnType, ArgType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
pub enum Flavor {
General,
Ios
}
type TyAlignFn = fn(ty: Type) -> uint;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1) / a * a;
}
fn align(off: uint, ty: Type, align_fn: TyAlignFn) -> uint {
let a = align_fn(ty);
return align_up_to(off, a);
}
fn | (ty: Type) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, general_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
general_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
general_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
// For more information see:
// ARMv7
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv7FunctionCallingConventions.html
// ARMv6
// https://developer.apple.com/library/ios/documentation/Xcode/Conceptual
// /iPhoneOSABIReference/Articles/ARMv6FunctionCallingConventions.html
fn ios_ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => cmp::min(4, ((ty.int_width() as uint) + 7) / 8),
Pointer => 4,
Float => 4,
Double => 4,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ios_ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ios_ty_align(elt)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ios_ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type, align_fn: TyAlignFn) -> uint {
match ty.kind() {
Integer => ((ty.int_width() as uint) + 7) / 8,
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t, align_fn))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter()
.fold(0, |s, t| {
align(s, *t, align_fn) + ty_size(*t, align_fn)
});
align(size, ty, align_fn)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt, align_fn);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
}
let size = ty_size(ty, align_fn);
if size <= 4 {
let llty = if size <= 1 {
Type::i8(ccx)
} else if size <= 2 {
Type::i16(ccx)
} else {
Type::i32(ccx)
};
return ArgType::direct(ty, Some(llty), None, None);
}
ArgType::indirect(ty, Some(StructRetAttribute))
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, align_fn: TyAlignFn) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
return ArgType::direct(ty, None, None, attr);
}
let align = align_fn(ty);
let size = ty_size(ty, align_fn);
let llty = if align <= 4 {
Type::array(&Type::i32(ccx), ((size + 3) / 4) as u64)
} else {
Type::array(&Type::i64(ccx), ((size + 7) / 8) as u64)
};
ArgType::direct(ty, Some(llty), None, None)
}
fn is_reg_ty(ty: Type) -> bool {
match ty.kind() {
Integer
| Pointer
| Float
| Double
| Vector => true,
_ => false
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool,
flavor: Flavor) -> FnType {
let align_fn = match flavor {
Flavor::General => general_ty_align as TyAlignFn,
Flavor::Ios => ios_ty_align as TyAlignFn,
};
let mut arg_tys = Vec::new();
for &aty in atys {
let ty = classify_arg_ty(ccx, aty, align_fn);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty, align_fn)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| general_ty_align | identifier_name |
main.rs | extern crate libc;
extern crate scaly;
use libc::c_char;
use libc::c_int;
use scaly::containers::{Array, Ref, String, Vector};
use scaly::memory::Heap;
use scaly::memory::Page;
use scaly::memory::Region;
use scaly::memory::StackBucket;
use std::ffi::CString;
mod scalyc;
// Rust's main which converts args back to C's main convention (used here for the Rust backend)
fn main() {
let args = std::env::args() | .map(|arg| arg.as_ptr())
.collect::<Vec<*const c_char>>();
_main(c_args.len() as c_int, c_args.as_ptr());
}
// C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend)
fn _main(argc: c_int, argv: *const *const c_char) {
let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize));
_scalyc_main(&_r, {
let _r_1 = Region::create(&_r);
let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new());
for n in 0..argc {
if n == 0 {
continue;
}
unsafe {
let arg = argv.offset(n as isize);
let s = String::from_c_string(_r.page, *arg);
(*arguments).add(s);
}
}
Ref::new(_r.page, Vector::from_array(_r.page, arguments))
});
}
fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) {
use scalyc::compiler::Compiler;
let _r = Region::create(_pr);
let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));
(*compiler).compile(&_r, _r.page, _r.page);
} | .map(|arg| CString::new(arg).unwrap())
.collect::<Vec<CString>>();
let c_args = args
.iter() | random_line_split |
main.rs | extern crate libc;
extern crate scaly;
use libc::c_char;
use libc::c_int;
use scaly::containers::{Array, Ref, String, Vector};
use scaly::memory::Heap;
use scaly::memory::Page;
use scaly::memory::Region;
use scaly::memory::StackBucket;
use std::ffi::CString;
mod scalyc;
// Rust's main which converts args back to C's main convention (used here for the Rust backend)
fn main() {
let args = std::env::args()
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<CString>>();
let c_args = args
.iter()
.map(|arg| arg.as_ptr())
.collect::<Vec<*const c_char>>();
_main(c_args.len() as c_int, c_args.as_ptr());
}
// C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend)
fn | (argc: c_int, argv: *const *const c_char) {
let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize));
_scalyc_main(&_r, {
let _r_1 = Region::create(&_r);
let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new());
for n in 0..argc {
if n == 0 {
continue;
}
unsafe {
let arg = argv.offset(n as isize);
let s = String::from_c_string(_r.page, *arg);
(*arguments).add(s);
}
}
Ref::new(_r.page, Vector::from_array(_r.page, arguments))
});
}
fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) {
use scalyc::compiler::Compiler;
let _r = Region::create(_pr);
let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));
(*compiler).compile(&_r, _r.page, _r.page);
}
| _main | identifier_name |
main.rs | extern crate libc;
extern crate scaly;
use libc::c_char;
use libc::c_int;
use scaly::containers::{Array, Ref, String, Vector};
use scaly::memory::Heap;
use scaly::memory::Page;
use scaly::memory::Region;
use scaly::memory::StackBucket;
use std::ffi::CString;
mod scalyc;
// Rust's main which converts args back to C's main convention (used here for the Rust backend)
fn main() {
let args = std::env::args()
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<CString>>();
let c_args = args
.iter()
.map(|arg| arg.as_ptr())
.collect::<Vec<*const c_char>>();
_main(c_args.len() as c_int, c_args.as_ptr());
}
// C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend)
fn _main(argc: c_int, argv: *const *const c_char) {
let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize));
_scalyc_main(&_r, {
let _r_1 = Region::create(&_r);
let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new());
for n in 0..argc {
if n == 0 |
unsafe {
let arg = argv.offset(n as isize);
let s = String::from_c_string(_r.page, *arg);
(*arguments).add(s);
}
}
Ref::new(_r.page, Vector::from_array(_r.page, arguments))
});
}
fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) {
use scalyc::compiler::Compiler;
let _r = Region::create(_pr);
let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));
(*compiler).compile(&_r, _r.page, _r.page);
}
| {
continue;
} | conditional_block |
main.rs | extern crate libc;
extern crate scaly;
use libc::c_char;
use libc::c_int;
use scaly::containers::{Array, Ref, String, Vector};
use scaly::memory::Heap;
use scaly::memory::Page;
use scaly::memory::Region;
use scaly::memory::StackBucket;
use std::ffi::CString;
mod scalyc;
// Rust's main which converts args back to C's main convention (used here for the Rust backend)
fn main() {
let args = std::env::args()
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<CString>>();
let c_args = args
.iter()
.map(|arg| arg.as_ptr())
.collect::<Vec<*const c_char>>();
_main(c_args.len() as c_int, c_args.as_ptr());
}
// C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend)
fn _main(argc: c_int, argv: *const *const c_char) {
let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize));
_scalyc_main(&_r, {
let _r_1 = Region::create(&_r);
let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new());
for n in 0..argc {
if n == 0 {
continue;
}
unsafe {
let arg = argv.offset(n as isize);
let s = String::from_c_string(_r.page, *arg);
(*arguments).add(s);
}
}
Ref::new(_r.page, Vector::from_array(_r.page, arguments))
});
}
fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) | {
use scalyc::compiler::Compiler;
let _r = Region::create(_pr);
let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));
(*compiler).compile(&_r, _r.page, _r.page);
} | identifier_body |
|
hex.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ignore-lexer-test FIXME #15679
//! Hex binary-to-text encoding
pub use self::FromHexError::*;
use std::fmt;
use std::error;
/// A trait for converting a value to hexadecimal encoding
pub trait ToHex {
/// Converts the value of `self` to a hex value, returning the owned
/// string.
fn to_hex(&self) -> String;
}
const CHARS: &'static [u8] = b"0123456789abcdef";
impl ToHex for [u8] {
/// Turn a vector of `u8` bytes into a hexadecimal string.
///
/// # Examples
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::ToHex;
///
/// fn main () {
/// let str = [52,32].to_hex();
/// println!("{}", str);
/// }
/// ```
fn to_hex(&self) -> String {
let mut v = Vec::with_capacity(self.len() * 2);
for &byte in self {
v.push(CHARS[(byte >> 4) as usize]);
v.push(CHARS[(byte & 0xf) as usize]);
}
unsafe {
String::from_utf8_unchecked(v)
}
}
}
/// A trait for converting hexadecimal encoded values
pub trait FromHex {
/// Converts the value of `self`, interpreted as hexadecimal encoded data,
/// into an owned vector of bytes, returning the vector.
fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
}
/// Errors that can occur when decoding a hex encoded string
#[derive(Copy, Clone, Debug)]
pub enum FromHexError {
/// The input contained a character not part of the hex format
InvalidHexCharacter(char, usize),
/// The input had an invalid length
InvalidHexLength,
}
impl fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidHexCharacter(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidHexLength => write!(f, "Invalid input length"),
}
}
}
impl error::Error for FromHexError {
fn description(&self) -> &str {
match *self {
InvalidHexCharacter(_, _) => "invalid character",
InvalidHexLength => "invalid length",
}
}
}
impl FromHex for str {
/// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
/// to the byte values it encodes.
///
/// You can use the `String::from_utf8` function to turn a
/// `Vec<u8>` into a string with characters corresponding to those values.
///
/// # Examples
///
/// This converts a string literal to hexadecimal and back.
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::{FromHex, ToHex};
///
/// fn main () {
/// let hello_str = "Hello, World".as_bytes().to_hex();
/// println!("{}", hello_str);
/// let bytes = hello_str.from_hex().unwrap();
/// println!("{:?}", bytes);
/// let result_str = String::from_utf8(bytes).unwrap();
/// println!("{}", result_str);
/// }
/// ```
fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
// This may be an overestimate if there is any whitespace
let mut b = Vec::with_capacity(self.len() / 2);
let mut modulus = 0;
let mut buf = 0;
for (idx, byte) in self.bytes().enumerate() {
buf <<= 4;
match byte {
b'A'...b'F' => buf |= byte - b'A' + 10,
b'a'...b'f' => buf |= byte - b'a' + 10,
b'0'...b'9' => buf |= byte - b'0',
b' '|b'\r'|b'\n'|b'\t' => {
buf >>= 4;
continue
}
_ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
}
modulus += 1;
if modulus == 2 {
modulus = 0;
b.push(buf);
}
}
match modulus {
0 => Ok(b.into_iter().collect()),
_ => Err(InvalidHexLength),
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use hex::{FromHex, ToHex};
#[test]
pub fn test_to_hex() {
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}
#[test]
pub fn test_from_hex_okay() {
assert_eq!("666f6f626172".from_hex().unwrap(),
b"foobar");
assert_eq!("666F6F626172".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_from_hex_odd_len() |
#[test]
pub fn test_from_hex_invalid_char() {
assert!("66y6".from_hex().is_err());
}
#[test]
pub fn test_from_hex_ignores_whitespace() {
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_to_hex_all_bytes() {
for i in 0..256 {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
}
}
#[test]
pub fn test_from_hex_all_bytes() {
for i in 0..256 {
let ii: &[u8] = &[i as u8];
assert_eq!(format!("{:02x}", i as usize).from_hex()
.unwrap(),
ii);
assert_eq!(format!("{:02X}", i as usize).from_hex()
.unwrap(),
ii);
}
}
#[bench]
pub fn bench_to_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes().to_hex();
});
b.bytes = s.len() as u64;
}
#[bench]
pub fn bench_from_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
let sb = s.as_bytes().to_hex();
b.iter(|| {
sb.from_hex().unwrap();
});
b.bytes = sb.len() as u64;
}
}
| {
assert!("666".from_hex().is_err());
assert!("66 6".from_hex().is_err());
} | identifier_body |
hex.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ignore-lexer-test FIXME #15679 | use std::fmt;
use std::error;
/// A trait for converting a value to hexadecimal encoding
pub trait ToHex {
/// Converts the value of `self` to a hex value, returning the owned
/// string.
fn to_hex(&self) -> String;
}
const CHARS: &'static [u8] = b"0123456789abcdef";
impl ToHex for [u8] {
/// Turn a vector of `u8` bytes into a hexadecimal string.
///
/// # Examples
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::ToHex;
///
/// fn main () {
/// let str = [52,32].to_hex();
/// println!("{}", str);
/// }
/// ```
fn to_hex(&self) -> String {
let mut v = Vec::with_capacity(self.len() * 2);
for &byte in self {
v.push(CHARS[(byte >> 4) as usize]);
v.push(CHARS[(byte & 0xf) as usize]);
}
unsafe {
String::from_utf8_unchecked(v)
}
}
}
/// A trait for converting hexadecimal encoded values
pub trait FromHex {
/// Converts the value of `self`, interpreted as hexadecimal encoded data,
/// into an owned vector of bytes, returning the vector.
fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
}
/// Errors that can occur when decoding a hex encoded string
#[derive(Copy, Clone, Debug)]
pub enum FromHexError {
/// The input contained a character not part of the hex format
InvalidHexCharacter(char, usize),
/// The input had an invalid length
InvalidHexLength,
}
impl fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidHexCharacter(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidHexLength => write!(f, "Invalid input length"),
}
}
}
impl error::Error for FromHexError {
fn description(&self) -> &str {
match *self {
InvalidHexCharacter(_, _) => "invalid character",
InvalidHexLength => "invalid length",
}
}
}
impl FromHex for str {
/// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
/// to the byte values it encodes.
///
/// You can use the `String::from_utf8` function to turn a
/// `Vec<u8>` into a string with characters corresponding to those values.
///
/// # Examples
///
/// This converts a string literal to hexadecimal and back.
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::{FromHex, ToHex};
///
/// fn main () {
/// let hello_str = "Hello, World".as_bytes().to_hex();
/// println!("{}", hello_str);
/// let bytes = hello_str.from_hex().unwrap();
/// println!("{:?}", bytes);
/// let result_str = String::from_utf8(bytes).unwrap();
/// println!("{}", result_str);
/// }
/// ```
fn from_hex(&self) -> Result<Vec<u8>, FromHexError> {
// This may be an overestimate if there is any whitespace
let mut b = Vec::with_capacity(self.len() / 2);
let mut modulus = 0;
let mut buf = 0;
for (idx, byte) in self.bytes().enumerate() {
buf <<= 4;
match byte {
b'A'...b'F' => buf |= byte - b'A' + 10,
b'a'...b'f' => buf |= byte - b'a' + 10,
b'0'...b'9' => buf |= byte - b'0',
b' '|b'\r'|b'\n'|b'\t' => {
buf >>= 4;
continue
}
_ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
}
modulus += 1;
if modulus == 2 {
modulus = 0;
b.push(buf);
}
}
match modulus {
0 => Ok(b.into_iter().collect()),
_ => Err(InvalidHexLength),
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use hex::{FromHex, ToHex};
#[test]
pub fn test_to_hex() {
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}
#[test]
pub fn test_from_hex_okay() {
assert_eq!("666f6f626172".from_hex().unwrap(),
b"foobar");
assert_eq!("666F6F626172".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_from_hex_odd_len() {
assert!("666".from_hex().is_err());
assert!("66 6".from_hex().is_err());
}
#[test]
pub fn test_from_hex_invalid_char() {
assert!("66y6".from_hex().is_err());
}
#[test]
pub fn test_from_hex_ignores_whitespace() {
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_to_hex_all_bytes() {
for i in 0..256 {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
}
}
#[test]
pub fn test_from_hex_all_bytes() {
for i in 0..256 {
let ii: &[u8] = &[i as u8];
assert_eq!(format!("{:02x}", i as usize).from_hex()
.unwrap(),
ii);
assert_eq!(format!("{:02X}", i as usize).from_hex()
.unwrap(),
ii);
}
}
#[bench]
pub fn bench_to_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes().to_hex();
});
b.bytes = s.len() as u64;
}
#[bench]
pub fn bench_from_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
let sb = s.as_bytes().to_hex();
b.iter(|| {
sb.from_hex().unwrap();
});
b.bytes = sb.len() as u64;
}
} |
//! Hex binary-to-text encoding
pub use self::FromHexError::*;
| random_line_split |
hex.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ignore-lexer-test FIXME #15679
//! Hex binary-to-text encoding
pub use self::FromHexError::*;
use std::fmt;
use std::error;
/// A trait for converting a value to hexadecimal encoding
pub trait ToHex {
/// Converts the value of `self` to a hex value, returning the owned
/// string.
fn to_hex(&self) -> String;
}
const CHARS: &'static [u8] = b"0123456789abcdef";
impl ToHex for [u8] {
/// Turn a vector of `u8` bytes into a hexadecimal string.
///
/// # Examples
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::ToHex;
///
/// fn main () {
/// let str = [52,32].to_hex();
/// println!("{}", str);
/// }
/// ```
fn to_hex(&self) -> String {
let mut v = Vec::with_capacity(self.len() * 2);
for &byte in self {
v.push(CHARS[(byte >> 4) as usize]);
v.push(CHARS[(byte & 0xf) as usize]);
}
unsafe {
String::from_utf8_unchecked(v)
}
}
}
/// A trait for converting hexadecimal encoded values
pub trait FromHex {
/// Converts the value of `self`, interpreted as hexadecimal encoded data,
/// into an owned vector of bytes, returning the vector.
fn from_hex(&self) -> Result<Vec<u8>, FromHexError>;
}
/// Errors that can occur when decoding a hex encoded string
#[derive(Copy, Clone, Debug)]
pub enum FromHexError {
/// The input contained a character not part of the hex format
InvalidHexCharacter(char, usize),
/// The input had an invalid length
InvalidHexLength,
}
impl fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidHexCharacter(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidHexLength => write!(f, "Invalid input length"),
}
}
}
impl error::Error for FromHexError {
fn description(&self) -> &str {
match *self {
InvalidHexCharacter(_, _) => "invalid character",
InvalidHexLength => "invalid length",
}
}
}
impl FromHex for str {
/// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
/// to the byte values it encodes.
///
/// You can use the `String::from_utf8` function to turn a
/// `Vec<u8>` into a string with characters corresponding to those values.
///
/// # Examples
///
/// This converts a string literal to hexadecimal and back.
///
/// ```
/// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::{FromHex, ToHex};
///
/// fn main () {
/// let hello_str = "Hello, World".as_bytes().to_hex();
/// println!("{}", hello_str);
/// let bytes = hello_str.from_hex().unwrap();
/// println!("{:?}", bytes);
/// let result_str = String::from_utf8(bytes).unwrap();
/// println!("{}", result_str);
/// }
/// ```
fn | (&self) -> Result<Vec<u8>, FromHexError> {
// This may be an overestimate if there is any whitespace
let mut b = Vec::with_capacity(self.len() / 2);
let mut modulus = 0;
let mut buf = 0;
for (idx, byte) in self.bytes().enumerate() {
buf <<= 4;
match byte {
b'A'...b'F' => buf |= byte - b'A' + 10,
b'a'...b'f' => buf |= byte - b'a' + 10,
b'0'...b'9' => buf |= byte - b'0',
b' '|b'\r'|b'\n'|b'\t' => {
buf >>= 4;
continue
}
_ => return Err(InvalidHexCharacter(self.char_at(idx), idx)),
}
modulus += 1;
if modulus == 2 {
modulus = 0;
b.push(buf);
}
}
match modulus {
0 => Ok(b.into_iter().collect()),
_ => Err(InvalidHexLength),
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use hex::{FromHex, ToHex};
#[test]
pub fn test_to_hex() {
assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172");
}
#[test]
pub fn test_from_hex_okay() {
assert_eq!("666f6f626172".from_hex().unwrap(),
b"foobar");
assert_eq!("666F6F626172".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_from_hex_odd_len() {
assert!("666".from_hex().is_err());
assert!("66 6".from_hex().is_err());
}
#[test]
pub fn test_from_hex_invalid_char() {
assert!("66y6".from_hex().is_err());
}
#[test]
pub fn test_from_hex_ignores_whitespace() {
assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(),
b"foobar");
}
#[test]
pub fn test_to_hex_all_bytes() {
for i in 0..256 {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as usize));
}
}
#[test]
pub fn test_from_hex_all_bytes() {
for i in 0..256 {
let ii: &[u8] = &[i as u8];
assert_eq!(format!("{:02x}", i as usize).from_hex()
.unwrap(),
ii);
assert_eq!(format!("{:02X}", i as usize).from_hex()
.unwrap(),
ii);
}
}
#[bench]
pub fn bench_to_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes().to_hex();
});
b.bytes = s.len() as u64;
}
#[bench]
pub fn bench_from_hex(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
let sb = s.as_bytes().to_hex();
b.iter(|| {
sb.from_hex().unwrap();
});
b.bytes = sb.len() as u64;
}
}
| from_hex | identifier_name |
40.rs | /* Problem 40: Champernowne's constant
*
* An irrational decimal fraction is created by concatenating the positive integers:
*
* 0.123456789101112131415161718192021...
*
* It can be seen that the 12th digit of the fractional part is 1.
*
* If dn represents the nth digit of the fractional part, find the value of the following
* expression.
*
* d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 */
use shared::digits;
fn main() | let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000]
.iter()
.map(|&position| {
(1..)
.flat_map(digits::new::<_, u32>)
.nth(position as usize - 1)
.unwrap()
})
.fold(1, |acc, n| acc * n);
println!("{}", result);
}
| {
| identifier_name |
40.rs | /* Problem 40: Champernowne's constant
*
* An irrational decimal fraction is created by concatenating the positive integers:
*
* 0.123456789101112131415161718192021...
*
* It can be seen that the 12th digit of the fractional part is 1.
*
* If dn represents the nth digit of the fractional part, find the value of the following
* expression. | *
* d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 */
use shared::digits;
fn main() {
let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000]
.iter()
.map(|&position| {
(1..)
.flat_map(digits::new::<_, u32>)
.nth(position as usize - 1)
.unwrap()
})
.fold(1, |acc, n| acc * n);
println!("{}", result);
} | random_line_split |
|
40.rs | /* Problem 40: Champernowne's constant
*
* An irrational decimal fraction is created by concatenating the positive integers:
*
* 0.123456789101112131415161718192021...
*
* It can be seen that the 12th digit of the fractional part is 1.
*
* If dn represents the nth digit of the fractional part, find the value of the following
* expression.
*
* d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 */
use shared::digits;
fn main() {
| let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000]
.iter()
.map(|&position| {
(1..)
.flat_map(digits::new::<_, u32>)
.nth(position as usize - 1)
.unwrap()
})
.fold(1, |acc, n| acc * n);
println!("{}", result);
}
| identifier_body |
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::global::GlobalRef;
use dom::domexception::{DOMException, DOMErrorName};
use util::mem::HeapSizeOf;
use util::str::DOMString;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{JSContext, JSObject, RootedValue};
use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException};
use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType};
use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain};
use js::jsval::UndefinedValue;
use libc;
use std::ffi::CString;
use std::mem;
use std::ptr;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Debug, Clone, HeapSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// TypeError JavaScript Error
Type(DOMString),
/// RangeError JavaScript Error
Range(DOMString),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef,
result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::Type(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 1);
return;
}
};
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let exception = DOMException::new(global, code);
let mut thrown = RootedValue::new(cx, UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
unsafe {
JS_SetPendingException(cx, thrown.handle());
}
}
/// Report a pending exception, thereby clearing it.
pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) {
unsafe {
if JS_IsExceptionPending(cx)!= 0 {
let saved = JS_SaveFrameChain(cx);
{
let _ac = JSAutoCompartment::new(cx, obj);
JS_ReportPendingException(cx);
}
if saved!= 0 {
JS_RestoreFrameChain(cx);
}
}
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) |
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_TYPEERR as i16,
};
/// Format string struct used to throw `RangeError`s.
static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_RANGEERR as i16,
};
/// Callback used to throw javascript errors.
/// See throw_js_error for info about error_number.
unsafe extern fn get_error_message(_user_ref: *mut libc::c_void,
error_number: libc::c_uint)
-> *const JSErrorFormatString
{
let num: JSExnType = mem::transmute(error_number);
match num {
JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
_ => panic!("Bad js error number given to get_error_message: {}", error_number)
}
}
/// Helper fn to throw a javascript error with the given message and number.
/// Reuse the jsapi error codes to distinguish the error_number
/// passed back to the get_error_message callback.
/// c_uint is u32, so this cast is safe, as is casting to/from i32 from there.
fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) {
let error = CString::new(error).unwrap();
unsafe {
JS_ReportErrorNumber1(cx,
Some(get_error_message),
ptr::null_mut(), error_number, error.as_ptr());
}
}
/// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
}
| {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
} | identifier_body |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::global::GlobalRef;
use dom::domexception::{DOMException, DOMErrorName};
use util::mem::HeapSizeOf;
use util::str::DOMString;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{JSContext, JSObject, RootedValue};
use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException};
use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType};
use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain};
use js::jsval::UndefinedValue;
use libc;
use std::ffi::CString;
use std::mem;
use std::ptr;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Debug, Clone, HeapSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// TypeError JavaScript Error
Type(DOMString),
/// RangeError JavaScript Error
Range(DOMString),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef,
result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::Type(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 1);
return;
}
};
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let exception = DOMException::new(global, code);
let mut thrown = RootedValue::new(cx, UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
unsafe {
JS_SetPendingException(cx, thrown.handle());
}
}
/// Report a pending exception, thereby clearing it.
pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) {
unsafe {
if JS_IsExceptionPending(cx)!= 0 {
let saved = JS_SaveFrameChain(cx);
{
let _ac = JSAutoCompartment::new(cx, obj);
JS_ReportPendingException(cx);
}
if saved!= 0 {
JS_RestoreFrameChain(cx);
}
}
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { | debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_TYPEERR as i16,
};
/// Format string struct used to throw `RangeError`s.
static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_RANGEERR as i16,
};
/// Callback used to throw javascript errors.
/// See throw_js_error for info about error_number.
unsafe extern fn get_error_message(_user_ref: *mut libc::c_void,
error_number: libc::c_uint)
-> *const JSErrorFormatString
{
let num: JSExnType = mem::transmute(error_number);
match num {
JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
_ => panic!("Bad js error number given to get_error_message: {}", error_number)
}
}
/// Helper fn to throw a javascript error with the given message and number.
/// Reuse the jsapi error codes to distinguish the error_number
/// passed back to the get_error_message callback.
/// c_uint is u32, so this cast is safe, as is casting to/from i32 from there.
fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) {
let error = CString::new(error).unwrap();
unsafe {
JS_ReportErrorNumber1(cx,
Some(get_error_message),
ptr::null_mut(), error_number, error.as_ptr());
}
}
/// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
} | random_line_split |
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::global::GlobalRef;
use dom::domexception::{DOMException, DOMErrorName};
use util::mem::HeapSizeOf;
use util::str::DOMString;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{JSContext, JSObject, RootedValue};
use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException};
use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType};
use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain};
use js::jsval::UndefinedValue;
use libc;
use std::ffi::CString;
use std::mem;
use std::ptr;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Debug, Clone, HeapSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// TypeError JavaScript Error
Type(DOMString),
/// RangeError JavaScript Error
Range(DOMString),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef,
result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::Type(message) => | ,
Error::Range(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 1);
return;
}
};
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let exception = DOMException::new(global, code);
let mut thrown = RootedValue::new(cx, UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
unsafe {
JS_SetPendingException(cx, thrown.handle());
}
}
/// Report a pending exception, thereby clearing it.
pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) {
unsafe {
if JS_IsExceptionPending(cx)!= 0 {
let saved = JS_SaveFrameChain(cx);
{
let _ac = JSAutoCompartment::new(cx, obj);
JS_ReportPendingException(cx);
}
if saved!= 0 {
JS_RestoreFrameChain(cx);
}
}
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_TYPEERR as i16,
};
/// Format string struct used to throw `RangeError`s.
static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_RANGEERR as i16,
};
/// Callback used to throw javascript errors.
/// See throw_js_error for info about error_number.
unsafe extern fn get_error_message(_user_ref: *mut libc::c_void,
error_number: libc::c_uint)
-> *const JSErrorFormatString
{
let num: JSExnType = mem::transmute(error_number);
match num {
JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
_ => panic!("Bad js error number given to get_error_message: {}", error_number)
}
}
/// Helper fn to throw a javascript error with the given message and number.
/// Reuse the jsapi error codes to distinguish the error_number
/// passed back to the get_error_message callback.
/// c_uint is u32, so this cast is safe, as is casting to/from i32 from there.
fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) {
let error = CString::new(error).unwrap();
unsafe {
JS_ReportErrorNumber1(cx,
Some(get_error_message),
ptr::null_mut(), error_number, error.as_ptr());
}
}
/// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
}
| {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_type_error(cx, &message);
return;
} | conditional_block |
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::global::GlobalRef;
use dom::domexception::{DOMException, DOMErrorName};
use util::mem::HeapSizeOf;
use util::str::DOMString;
use js::jsapi::JSAutoCompartment;
use js::jsapi::{JSContext, JSObject, RootedValue};
use js::jsapi::{JS_IsExceptionPending, JS_SetPendingException, JS_ReportPendingException};
use js::jsapi::{JS_ReportErrorNumber1, JSErrorFormatString, JSExnType};
use js::jsapi::{JS_SaveFrameChain, JS_RestoreFrameChain};
use js::jsval::UndefinedValue;
use libc;
use std::ffi::CString;
use std::mem;
use std::ptr;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Debug, Clone, HeapSizeOf)]
pub enum | {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// TypeError JavaScript Error
Type(DOMString),
/// RangeError JavaScript Error
Range(DOMString),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef,
result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::Type(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(unsafe { JS_IsExceptionPending(cx) } == 1);
return;
}
};
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let exception = DOMException::new(global, code);
let mut thrown = RootedValue::new(cx, UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
unsafe {
JS_SetPendingException(cx, thrown.handle());
}
}
/// Report a pending exception, thereby clearing it.
pub fn report_pending_exception(cx: *mut JSContext, obj: *mut JSObject) {
unsafe {
if JS_IsExceptionPending(cx)!= 0 {
let saved = JS_SaveFrameChain(cx);
{
let _ac = JSAutoCompartment::new(cx, obj);
JS_ReportPendingException(cx);
}
if saved!= 0 {
JS_RestoreFrameChain(cx);
}
}
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(unsafe { JS_IsExceptionPending(cx) } == 0);
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
/// Format string used to throw javascript errors.
static ERROR_FORMAT_STRING_STRING: [libc::c_char; 4] = [
'{' as libc::c_char,
'0' as libc::c_char,
'}' as libc::c_char,
0 as libc::c_char,
];
/// Format string struct used to throw `TypeError`s.
static mut TYPE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_TYPEERR as i16,
};
/// Format string struct used to throw `RangeError`s.
static mut RANGE_ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1,
exnType: JSExnType::JSEXN_RANGEERR as i16,
};
/// Callback used to throw javascript errors.
/// See throw_js_error for info about error_number.
unsafe extern fn get_error_message(_user_ref: *mut libc::c_void,
error_number: libc::c_uint)
-> *const JSErrorFormatString
{
let num: JSExnType = mem::transmute(error_number);
match num {
JSExnType::JSEXN_TYPEERR => &TYPE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
JSExnType::JSEXN_RANGEERR => &RANGE_ERROR_FORMAT_STRING as *const JSErrorFormatString,
_ => panic!("Bad js error number given to get_error_message: {}", error_number)
}
}
/// Helper fn to throw a javascript error with the given message and number.
/// Reuse the jsapi error codes to distinguish the error_number
/// passed back to the get_error_message callback.
/// c_uint is u32, so this cast is safe, as is casting to/from i32 from there.
fn throw_js_error(cx: *mut JSContext, error: &str, error_number: u32) {
let error = CString::new(error).unwrap();
unsafe {
JS_ReportErrorNumber1(cx,
Some(get_error_message),
ptr::null_mut(), error_number, error.as_ptr());
}
}
/// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_TYPEERR as u32);
}
/// Throw a `RangeError` with the given message.
pub fn throw_range_error(cx: *mut JSContext, error: &str) {
throw_js_error(cx, error, JSExnType::JSEXN_RANGEERR as u32);
}
| Error | identifier_name |
pointer.rs | // Copyright 2019 Jeremy Wall
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use std::rc::Rc;
use crate::ast::Position;
use super::translate::OpsMap;
use super::{Error, Op};
#[derive(Debug, PartialEq, Clone)]
pub struct OpPointer {
pub pos_map: Rc<OpsMap>,
pub ptr: Option<usize>,
pub path: Option<PathBuf>,
}
impl OpPointer {
pub fn new(ops: Rc<OpsMap>) -> Self {
// If we load an empty program what happens?
Self {
pos_map: ops,
ptr: None,
path: None,
}
}
pub fn set_path(&mut self, path: PathBuf) {
self.path = Some(path);
}
pub fn next(&mut self) -> Option<&Op> {
if let Some(i) = self.ptr {
let nxt = i + 1;
if nxt < self.pos_map.len() {
self.ptr = Some(nxt);
} else {
return None;
}
} else if self.pos_map.len()!= 0 {
self.ptr = Some(0);
}
self.op()
}
pub fn | (&mut self, ptr: usize) -> Result<(), Error> {
if ptr < self.pos_map.len() {
self.ptr = Some(ptr);
return Ok(());
}
Err(Error::new(
format!("FAULT!!! Invalid Jump!"),
match self.pos() {
Some(pos) => pos.clone(),
None => Position::new(0, 0, 0),
},
))
}
pub fn op(&self) -> Option<&Op> {
if let Some(i) = self.ptr {
return self.pos_map.ops.get(i);
}
None
}
pub fn pos(&self) -> Option<&Position> {
if let Some(i) = self.ptr {
return self.pos_map.pos.get(i);
}
None
}
pub fn idx(&self) -> Result<usize, Error> {
match self.ptr {
Some(ptr) => Ok(ptr),
None => Err(Error::new(
format!("FAULT!!! Position Check failure!"),
Position::new(0, 0, 0),
)),
}
}
pub fn snapshot(&self) -> Self {
Self {
pos_map: self.pos_map.clone(),
ptr: None,
path: self.path.clone(),
}
}
}
| jump | identifier_name |
pointer.rs | // Copyright 2019 Jeremy Wall
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use std::rc::Rc;
use crate::ast::Position;
use super::translate::OpsMap;
use super::{Error, Op};
#[derive(Debug, PartialEq, Clone)]
pub struct OpPointer {
pub pos_map: Rc<OpsMap>,
pub ptr: Option<usize>,
pub path: Option<PathBuf>,
}
impl OpPointer {
pub fn new(ops: Rc<OpsMap>) -> Self {
// If we load an empty program what happens?
Self {
pos_map: ops,
ptr: None,
path: None,
}
}
pub fn set_path(&mut self, path: PathBuf) {
self.path = Some(path);
}
pub fn next(&mut self) -> Option<&Op> {
if let Some(i) = self.ptr {
let nxt = i + 1;
if nxt < self.pos_map.len() {
self.ptr = Some(nxt);
} else {
return None;
}
} else if self.pos_map.len()!= 0 {
self.ptr = Some(0);
}
self.op()
}
pub fn jump(&mut self, ptr: usize) -> Result<(), Error> {
if ptr < self.pos_map.len() {
self.ptr = Some(ptr);
return Ok(());
}
Err(Error::new(
format!("FAULT!!! Invalid Jump!"), | ))
}
pub fn op(&self) -> Option<&Op> {
if let Some(i) = self.ptr {
return self.pos_map.ops.get(i);
}
None
}
pub fn pos(&self) -> Option<&Position> {
if let Some(i) = self.ptr {
return self.pos_map.pos.get(i);
}
None
}
pub fn idx(&self) -> Result<usize, Error> {
match self.ptr {
Some(ptr) => Ok(ptr),
None => Err(Error::new(
format!("FAULT!!! Position Check failure!"),
Position::new(0, 0, 0),
)),
}
}
pub fn snapshot(&self) -> Self {
Self {
pos_map: self.pos_map.clone(),
ptr: None,
path: self.path.clone(),
}
}
} | match self.pos() {
Some(pos) => pos.clone(),
None => Position::new(0, 0, 0),
}, | random_line_split |
pointer.rs | // Copyright 2019 Jeremy Wall
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use std::rc::Rc;
use crate::ast::Position;
use super::translate::OpsMap;
use super::{Error, Op};
#[derive(Debug, PartialEq, Clone)]
pub struct OpPointer {
pub pos_map: Rc<OpsMap>,
pub ptr: Option<usize>,
pub path: Option<PathBuf>,
}
impl OpPointer {
pub fn new(ops: Rc<OpsMap>) -> Self {
// If we load an empty program what happens?
Self {
pos_map: ops,
ptr: None,
path: None,
}
}
pub fn set_path(&mut self, path: PathBuf) {
self.path = Some(path);
}
pub fn next(&mut self) -> Option<&Op> {
if let Some(i) = self.ptr {
let nxt = i + 1;
if nxt < self.pos_map.len() {
self.ptr = Some(nxt);
} else {
return None;
}
} else if self.pos_map.len()!= 0 {
self.ptr = Some(0);
}
self.op()
}
pub fn jump(&mut self, ptr: usize) -> Result<(), Error> |
pub fn op(&self) -> Option<&Op> {
if let Some(i) = self.ptr {
return self.pos_map.ops.get(i);
}
None
}
pub fn pos(&self) -> Option<&Position> {
if let Some(i) = self.ptr {
return self.pos_map.pos.get(i);
}
None
}
pub fn idx(&self) -> Result<usize, Error> {
match self.ptr {
Some(ptr) => Ok(ptr),
None => Err(Error::new(
format!("FAULT!!! Position Check failure!"),
Position::new(0, 0, 0),
)),
}
}
pub fn snapshot(&self) -> Self {
Self {
pos_map: self.pos_map.clone(),
ptr: None,
path: self.path.clone(),
}
}
}
| {
if ptr < self.pos_map.len() {
self.ptr = Some(ptr);
return Ok(());
}
Err(Error::new(
format!("FAULT!!! Invalid Jump!"),
match self.pos() {
Some(pos) => pos.clone(),
None => Position::new(0, 0, 0),
},
))
} | identifier_body |
mod.rs | // Copyright (c) 2016 Tibor Benke <[email protected]>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use uuid::Uuid;
use config::action::ActionType;
use conditions::Conditions;
mod deser;
pub mod action;
pub struct ContextConfig {
pub name: Option<String>,
pub uuid: Uuid,
pub conditions: Conditions,
pub context_id: Option<Vec<String>>,
pub actions: Vec<ActionType>,
pub patterns: Vec<String>
}
pub struct ContextConfigBuilder {
name: Option<String>,
uuid: Uuid,
conditions: Conditions,
context_id: Option<Vec<String>>,
actions: Vec<ActionType>,
patterns: Vec<String>
}
impl ContextConfigBuilder {
pub fn new(uuid: Uuid, conditions: Conditions) -> ContextConfigBuilder {
ContextConfigBuilder {
name: None,
uuid: uuid,
conditions: conditions,
context_id: None,
actions: Vec::new(),
patterns: Vec::new()
}
}
pub fn context_id(mut self, context_id: Option<Vec<String>>) -> ContextConfigBuilder |
pub fn actions(mut self, actions: Vec<ActionType>) -> ContextConfigBuilder {
self.actions = actions;
self
}
pub fn name(mut self, name: String) -> ContextConfigBuilder {
self.name = Some(name);
self
}
pub fn patterns(mut self, patterns: Vec<String>) -> ContextConfigBuilder {
self.patterns = patterns;
self
}
pub fn build(self) -> ContextConfig {
ContextConfig {
name: self.name,
uuid: self.uuid,
conditions: self.conditions,
context_id: self.context_id,
actions: self.actions,
patterns: self.patterns
}
}
}
| {
self.context_id = context_id;
self
} | identifier_body |
mod.rs | // Copyright (c) 2016 Tibor Benke <[email protected]>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use uuid::Uuid;
use config::action::ActionType;
use conditions::Conditions;
mod deser;
pub mod action;
pub struct ContextConfig {
pub name: Option<String>,
pub uuid: Uuid,
pub conditions: Conditions,
pub context_id: Option<Vec<String>>,
pub actions: Vec<ActionType>,
pub patterns: Vec<String>
} | name: Option<String>,
uuid: Uuid,
conditions: Conditions,
context_id: Option<Vec<String>>,
actions: Vec<ActionType>,
patterns: Vec<String>
}
impl ContextConfigBuilder {
pub fn new(uuid: Uuid, conditions: Conditions) -> ContextConfigBuilder {
ContextConfigBuilder {
name: None,
uuid: uuid,
conditions: conditions,
context_id: None,
actions: Vec::new(),
patterns: Vec::new()
}
}
pub fn context_id(mut self, context_id: Option<Vec<String>>) -> ContextConfigBuilder {
self.context_id = context_id;
self
}
pub fn actions(mut self, actions: Vec<ActionType>) -> ContextConfigBuilder {
self.actions = actions;
self
}
pub fn name(mut self, name: String) -> ContextConfigBuilder {
self.name = Some(name);
self
}
pub fn patterns(mut self, patterns: Vec<String>) -> ContextConfigBuilder {
self.patterns = patterns;
self
}
pub fn build(self) -> ContextConfig {
ContextConfig {
name: self.name,
uuid: self.uuid,
conditions: self.conditions,
context_id: self.context_id,
actions: self.actions,
patterns: self.patterns
}
}
} |
pub struct ContextConfigBuilder { | random_line_split |
mod.rs | // Copyright (c) 2016 Tibor Benke <[email protected]>
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use uuid::Uuid;
use config::action::ActionType;
use conditions::Conditions;
mod deser;
pub mod action;
pub struct ContextConfig {
pub name: Option<String>,
pub uuid: Uuid,
pub conditions: Conditions,
pub context_id: Option<Vec<String>>,
pub actions: Vec<ActionType>,
pub patterns: Vec<String>
}
pub struct ContextConfigBuilder {
name: Option<String>,
uuid: Uuid,
conditions: Conditions,
context_id: Option<Vec<String>>,
actions: Vec<ActionType>,
patterns: Vec<String>
}
impl ContextConfigBuilder {
pub fn new(uuid: Uuid, conditions: Conditions) -> ContextConfigBuilder {
ContextConfigBuilder {
name: None,
uuid: uuid,
conditions: conditions,
context_id: None,
actions: Vec::new(),
patterns: Vec::new()
}
}
pub fn context_id(mut self, context_id: Option<Vec<String>>) -> ContextConfigBuilder {
self.context_id = context_id;
self
}
pub fn actions(mut self, actions: Vec<ActionType>) -> ContextConfigBuilder {
self.actions = actions;
self
}
pub fn name(mut self, name: String) -> ContextConfigBuilder {
self.name = Some(name);
self
}
pub fn | (mut self, patterns: Vec<String>) -> ContextConfigBuilder {
self.patterns = patterns;
self
}
pub fn build(self) -> ContextConfig {
ContextConfig {
name: self.name,
uuid: self.uuid,
conditions: self.conditions,
context_id: self.context_id,
actions: self.actions,
patterns: self.patterns
}
}
}
| patterns | identifier_name |
mod.rs | //! Example nonlinear PDEs
pub mod kse;
pub mod she;
pub use self::kse::KSE;
pub use self::she::SWE;
use fftw::array::*; | /// Pair of one-dimensional Real/Complex aligned arrays
pub struct Pair {
pub r: AlignedVec<f64>,
pub c: AlignedVec<c64>,
r2c: R2CPlan64,
c2r: C2RPlan64,
}
impl Pair {
pub fn new(n: usize) -> Self {
let nf = n / 2 + 1;
let mut r = AlignedVec::new(n);
let mut c = AlignedVec::new(nf);
let r2c = R2CPlan::new(&[n], &mut r, &mut c, Flag::Measure).unwrap();
let c2r = C2RPlan::new(&[n], &mut c, &mut r, Flag::Measure).unwrap();
Pair { r, c, r2c, c2r }
}
pub fn r2c(&mut self) {
self.r2c.r2c(&mut self.r, &mut self.c).unwrap();
let n = 1.0 / self.r.len() as f64;
for v in self.c.iter_mut() {
*v *= n;
}
}
pub fn c2r(&mut self) {
self.c2r.c2r(&mut self.c, &mut self.r).unwrap();
}
pub fn to_r<'a, 'b>(&'a mut self, c: &'b [c64]) -> &'a [f64] {
self.c.copy_from_slice(c);
self.c2r();
&self.r
}
pub fn to_c<'a, 'b>(&'a mut self, r: &'b [f64]) -> &'a [c64] {
self.r.copy_from_slice(r);
self.r2c();
&self.c
}
pub fn real_view(&self) -> ArrayView1<f64> {
ArrayView::from_shape(self.r.len(), &self.r).unwrap()
}
pub fn coeff_view(&self) -> ArrayView1<c64> {
ArrayView::from_shape(self.c.len(), &self.c).unwrap()
}
pub fn real_view_mut(&mut self) -> ArrayViewMut1<f64> {
ArrayViewMut::from_shape(self.r.len(), &mut self.r).unwrap()
}
pub fn coeff_view_mut(&mut self) -> ArrayViewMut1<c64> {
ArrayViewMut::from_shape(self.c.len(), &mut self.c).unwrap()
}
}
impl Clone for Pair {
fn clone(&self) -> Self {
Pair::new(self.r.len())
}
} | use fftw::plan::*;
use fftw::types::*;
use ndarray::*;
| random_line_split |
mod.rs | //! Example nonlinear PDEs
pub mod kse;
pub mod she;
pub use self::kse::KSE;
pub use self::she::SWE;
use fftw::array::*;
use fftw::plan::*;
use fftw::types::*;
use ndarray::*;
/// Pair of one-dimensional Real/Complex aligned arrays
pub struct Pair {
pub r: AlignedVec<f64>,
pub c: AlignedVec<c64>,
r2c: R2CPlan64,
c2r: C2RPlan64,
}
impl Pair {
pub fn new(n: usize) -> Self {
let nf = n / 2 + 1;
let mut r = AlignedVec::new(n);
let mut c = AlignedVec::new(nf);
let r2c = R2CPlan::new(&[n], &mut r, &mut c, Flag::Measure).unwrap();
let c2r = C2RPlan::new(&[n], &mut c, &mut r, Flag::Measure).unwrap();
Pair { r, c, r2c, c2r }
}
pub fn r2c(&mut self) {
self.r2c.r2c(&mut self.r, &mut self.c).unwrap();
let n = 1.0 / self.r.len() as f64;
for v in self.c.iter_mut() {
*v *= n;
}
}
pub fn c2r(&mut self) {
self.c2r.c2r(&mut self.c, &mut self.r).unwrap();
}
pub fn to_r<'a, 'b>(&'a mut self, c: &'b [c64]) -> &'a [f64] {
self.c.copy_from_slice(c);
self.c2r();
&self.r
}
pub fn to_c<'a, 'b>(&'a mut self, r: &'b [f64]) -> &'a [c64] {
self.r.copy_from_slice(r);
self.r2c();
&self.c
}
pub fn real_view(&self) -> ArrayView1<f64> {
ArrayView::from_shape(self.r.len(), &self.r).unwrap()
}
pub fn coeff_view(&self) -> ArrayView1<c64> |
pub fn real_view_mut(&mut self) -> ArrayViewMut1<f64> {
ArrayViewMut::from_shape(self.r.len(), &mut self.r).unwrap()
}
pub fn coeff_view_mut(&mut self) -> ArrayViewMut1<c64> {
ArrayViewMut::from_shape(self.c.len(), &mut self.c).unwrap()
}
}
impl Clone for Pair {
fn clone(&self) -> Self {
Pair::new(self.r.len())
}
}
| {
ArrayView::from_shape(self.c.len(), &self.c).unwrap()
} | identifier_body |
mod.rs | //! Example nonlinear PDEs
pub mod kse;
pub mod she;
pub use self::kse::KSE;
pub use self::she::SWE;
use fftw::array::*;
use fftw::plan::*;
use fftw::types::*;
use ndarray::*;
/// Pair of one-dimensional Real/Complex aligned arrays
pub struct Pair {
pub r: AlignedVec<f64>,
pub c: AlignedVec<c64>,
r2c: R2CPlan64,
c2r: C2RPlan64,
}
impl Pair {
pub fn new(n: usize) -> Self {
let nf = n / 2 + 1;
let mut r = AlignedVec::new(n);
let mut c = AlignedVec::new(nf);
let r2c = R2CPlan::new(&[n], &mut r, &mut c, Flag::Measure).unwrap();
let c2r = C2RPlan::new(&[n], &mut c, &mut r, Flag::Measure).unwrap();
Pair { r, c, r2c, c2r }
}
pub fn | (&mut self) {
self.r2c.r2c(&mut self.r, &mut self.c).unwrap();
let n = 1.0 / self.r.len() as f64;
for v in self.c.iter_mut() {
*v *= n;
}
}
pub fn c2r(&mut self) {
self.c2r.c2r(&mut self.c, &mut self.r).unwrap();
}
pub fn to_r<'a, 'b>(&'a mut self, c: &'b [c64]) -> &'a [f64] {
self.c.copy_from_slice(c);
self.c2r();
&self.r
}
pub fn to_c<'a, 'b>(&'a mut self, r: &'b [f64]) -> &'a [c64] {
self.r.copy_from_slice(r);
self.r2c();
&self.c
}
pub fn real_view(&self) -> ArrayView1<f64> {
ArrayView::from_shape(self.r.len(), &self.r).unwrap()
}
pub fn coeff_view(&self) -> ArrayView1<c64> {
ArrayView::from_shape(self.c.len(), &self.c).unwrap()
}
pub fn real_view_mut(&mut self) -> ArrayViewMut1<f64> {
ArrayViewMut::from_shape(self.r.len(), &mut self.r).unwrap()
}
pub fn coeff_view_mut(&mut self) -> ArrayViewMut1<c64> {
ArrayViewMut::from_shape(self.c.len(), &mut self.c).unwrap()
}
}
impl Clone for Pair {
fn clone(&self) -> Self {
Pair::new(self.r.len())
}
}
| r2c | identifier_name |
renderer.rs | use log::{debug, error};
use std::{thread, time::Duration};
use crate::args::Args;
use crate::context::Context;
use crate::process;
pub fn | (args: Args, context: Context) {
thread::spawn(move || {
let visualizations_dir = context.data_dir.join("visualizations");
loop {
match visualizations_dir.read_dir() {
Ok(read_dir) => {
for dir_entry_result in read_dir {
match dir_entry_result {
Ok(dir_entry) => {
let mut command = context.blender_script_with_env("python/render.py");
command.arg("--id").arg(dir_entry.file_name().into_string().unwrap());
command.arg("--device").arg(args.render_device.to_str());
command.arg("--target-time").arg(args.render_target_time.to_string());
match command.output() {
Ok(output) => if output.status.success() {
debug!("The blender child process finished");
} else {
let blender_output = process::debug_output(output);
error!("The blender child process returned an error exit code.\n\n{}", blender_output)
}
Err(_) => error!("The blender child process could not be executed.")
}
}
Err(_) => debug!("Could not read visualization directory.")
}
}
}
Err(_) => debug!("Could not read visualizations directory.")
}
thread::sleep(Duration::from_secs(1))
}
});
}
| start | identifier_name |
renderer.rs | use log::{debug, error};
use std::{thread, time::Duration};
use crate::args::Args;
use crate::context::Context;
use crate::process;
pub fn start(args: Args, context: Context) | let blender_output = process::debug_output(output);
error!("The blender child process returned an error exit code.\n\n{}", blender_output)
}
Err(_) => error!("The blender child process could not be executed.")
}
}
Err(_) => debug!("Could not read visualization directory.")
}
}
}
Err(_) => debug!("Could not read visualizations directory.")
}
thread::sleep(Duration::from_secs(1))
}
});
}
| {
thread::spawn(move || {
let visualizations_dir = context.data_dir.join("visualizations");
loop {
match visualizations_dir.read_dir() {
Ok(read_dir) => {
for dir_entry_result in read_dir {
match dir_entry_result {
Ok(dir_entry) => {
let mut command = context.blender_script_with_env("python/render.py");
command.arg("--id").arg(dir_entry.file_name().into_string().unwrap());
command.arg("--device").arg(args.render_device.to_str());
command.arg("--target-time").arg(args.render_target_time.to_string());
match command.output() {
Ok(output) => if output.status.success() {
debug!("The blender child process finished");
} else { | identifier_body |
renderer.rs | use log::{debug, error};
use std::{thread, time::Duration};
use crate::args::Args;
use crate::context::Context;
use crate::process;
pub fn start(args: Args, context: Context) {
thread::spawn(move || {
let visualizations_dir = context.data_dir.join("visualizations");
loop {
match visualizations_dir.read_dir() {
Ok(read_dir) => {
for dir_entry_result in read_dir {
match dir_entry_result {
Ok(dir_entry) => {
let mut command = context.blender_script_with_env("python/render.py");
command.arg("--id").arg(dir_entry.file_name().into_string().unwrap());
command.arg("--device").arg(args.render_device.to_str());
command.arg("--target-time").arg(args.render_target_time.to_string());
match command.output() { | debug!("The blender child process finished");
} else {
let blender_output = process::debug_output(output);
error!("The blender child process returned an error exit code.\n\n{}", blender_output)
}
Err(_) => error!("The blender child process could not be executed.")
}
}
Err(_) => debug!("Could not read visualization directory.")
}
}
}
Err(_) => debug!("Could not read visualizations directory.")
}
thread::sleep(Duration::from_secs(1))
}
});
} | Ok(output) => if output.status.success() { | random_line_split |
uint.rs | // Copyright 2015, 2016 Ethcore (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 rustc_serialize::hex::ToHex;
use serde;
use util::{U256 as EthU256, Uint};
macro_rules! impl_uint {
($name: ident, $other: ident, $size: expr) => {
/// Uint serialization.
#[derive(Debug, Default, Clone, Copy, PartialEq, Hash)]
pub struct $name($other);
impl Eq for $name { }
impl<T> From<T> for $name where $other: From<T> {
fn from(o: T) -> Self {
$name($other::from(o))
}
}
impl FromStr for $name {
type Err = <$other as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$other::from_str(s).map($name)
}
}
impl Into<$other> for $name {
fn into(self) -> $other {
self.0
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
let mut hex = "0x".to_owned();
let mut bytes = [0u8; 8 * $size];
self.0.to_big_endian(&mut bytes);
let len = cmp::max((self.0.bits() + 7) / 8, 1);
let bytes_hex = bytes[bytes.len() - len..].to_hex();
if bytes_hex.starts_with('0') {
hex.push_str(&bytes_hex[1..]);
} else {
hex.push_str(&bytes_hex);
}
serializer.serialize_str(&hex)
}
}
impl serde::Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error>
where D: serde::Deserializer {
struct UintVisitor;
impl serde::de::Visitor for UintVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: serde::Error {
// 0x + len
if value.len() > 2 + $size * 16 || value.len() < 2 {
return Err(serde::Error::custom("Invalid length."));
}
if &value[0..2]!= "0x" {
return Err(serde::Error::custom("Use hex encoded numbers with 0x prefix."))
}
$other::from_str(&value[2..]).map($name).map_err(|_| serde::Error::custom("Invalid hex value."))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: serde::Error {
self.visit_str(&value)
}
}
deserializer.deserialize(UintVisitor)
}
}
}
}
impl_uint!(U256, EthU256, 4);
#[cfg(test)]
mod tests {
use super::U256;
use serde_json;
type Res = Result<U256, serde_json::Error>;
#[test]
fn should_serialize_u256() {
let serialized1 = serde_json::to_string(&U256(0.into())).unwrap();
let serialized2 = serde_json::to_string(&U256(1.into())).unwrap();
let serialized3 = serde_json::to_string(&U256(16.into())).unwrap();
let serialized4 = serde_json::to_string(&U256(256.into())).unwrap();
assert_eq!(serialized1, r#""0x0""#);
assert_eq!(serialized2, r#""0x1""#);
assert_eq!(serialized3, r#""0x10""#);
assert_eq!(serialized4, r#""0x100""#);
}
#[test]
fn should_fail_to_deserialize_decimals() {
let deserialized1: Res = serde_json::from_str(r#""""#);
let deserialized2: Res = serde_json::from_str(r#""0""#);
let deserialized3: Res = serde_json::from_str(r#""10""#);
let deserialized4: Res = serde_json::from_str(r#""1000000""#);
let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);
assert!(deserialized1.is_err());
assert!(deserialized2.is_err());
assert!(deserialized3.is_err());
assert!(deserialized4.is_err());
assert!(deserialized5.is_err());
}
#[test]
fn should_deserialize_u256() {
let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap();
let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap();
let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap();
let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unwrap();
let deserialized5: U256 = serde_json::from_str(r#""0x100""#).unwrap();
assert_eq!(deserialized1, U256(0.into()));
assert_eq!(deserialized2, U256(0.into()));
assert_eq!(deserialized3, U256(1.into()));
assert_eq!(deserialized4, U256(1.into()));
assert_eq!(deserialized5, U256(256.into()));
}
} | use std::cmp;
use std::str::FromStr; | random_line_split |
uint.rs | // Copyright 2015, 2016 Ethcore (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 std::cmp;
use std::str::FromStr;
use rustc_serialize::hex::ToHex;
use serde;
use util::{U256 as EthU256, Uint};
macro_rules! impl_uint {
($name: ident, $other: ident, $size: expr) => {
/// Uint serialization.
#[derive(Debug, Default, Clone, Copy, PartialEq, Hash)]
pub struct $name($other);
impl Eq for $name { }
impl<T> From<T> for $name where $other: From<T> {
fn from(o: T) -> Self {
$name($other::from(o))
}
}
impl FromStr for $name {
type Err = <$other as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$other::from_str(s).map($name)
}
}
impl Into<$other> for $name {
fn into(self) -> $other {
self.0
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
let mut hex = "0x".to_owned();
let mut bytes = [0u8; 8 * $size];
self.0.to_big_endian(&mut bytes);
let len = cmp::max((self.0.bits() + 7) / 8, 1);
let bytes_hex = bytes[bytes.len() - len..].to_hex();
if bytes_hex.starts_with('0') {
hex.push_str(&bytes_hex[1..]);
} else {
hex.push_str(&bytes_hex);
}
serializer.serialize_str(&hex)
}
}
impl serde::Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error>
where D: serde::Deserializer {
struct UintVisitor;
impl serde::de::Visitor for UintVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: serde::Error {
// 0x + len
if value.len() > 2 + $size * 16 || value.len() < 2 {
return Err(serde::Error::custom("Invalid length."));
}
if &value[0..2]!= "0x" {
return Err(serde::Error::custom("Use hex encoded numbers with 0x prefix."))
}
$other::from_str(&value[2..]).map($name).map_err(|_| serde::Error::custom("Invalid hex value."))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: serde::Error {
self.visit_str(&value)
}
}
deserializer.deserialize(UintVisitor)
}
}
}
}
impl_uint!(U256, EthU256, 4);
#[cfg(test)]
mod tests {
use super::U256;
use serde_json;
type Res = Result<U256, serde_json::Error>;
#[test]
fn should_serialize_u256() {
let serialized1 = serde_json::to_string(&U256(0.into())).unwrap();
let serialized2 = serde_json::to_string(&U256(1.into())).unwrap();
let serialized3 = serde_json::to_string(&U256(16.into())).unwrap();
let serialized4 = serde_json::to_string(&U256(256.into())).unwrap();
assert_eq!(serialized1, r#""0x0""#);
assert_eq!(serialized2, r#""0x1""#);
assert_eq!(serialized3, r#""0x10""#);
assert_eq!(serialized4, r#""0x100""#);
}
#[test]
fn | () {
let deserialized1: Res = serde_json::from_str(r#""""#);
let deserialized2: Res = serde_json::from_str(r#""0""#);
let deserialized3: Res = serde_json::from_str(r#""10""#);
let deserialized4: Res = serde_json::from_str(r#""1000000""#);
let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);
assert!(deserialized1.is_err());
assert!(deserialized2.is_err());
assert!(deserialized3.is_err());
assert!(deserialized4.is_err());
assert!(deserialized5.is_err());
}
#[test]
fn should_deserialize_u256() {
let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap();
let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap();
let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap();
let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unwrap();
let deserialized5: U256 = serde_json::from_str(r#""0x100""#).unwrap();
assert_eq!(deserialized1, U256(0.into()));
assert_eq!(deserialized2, U256(0.into()));
assert_eq!(deserialized3, U256(1.into()));
assert_eq!(deserialized4, U256(1.into()));
assert_eq!(deserialized5, U256(256.into()));
}
}
| should_fail_to_deserialize_decimals | identifier_name |
uint.rs | // Copyright 2015, 2016 Ethcore (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 std::cmp;
use std::str::FromStr;
use rustc_serialize::hex::ToHex;
use serde;
use util::{U256 as EthU256, Uint};
macro_rules! impl_uint {
($name: ident, $other: ident, $size: expr) => {
/// Uint serialization.
#[derive(Debug, Default, Clone, Copy, PartialEq, Hash)]
pub struct $name($other);
impl Eq for $name { }
impl<T> From<T> for $name where $other: From<T> {
fn from(o: T) -> Self {
$name($other::from(o))
}
}
impl FromStr for $name {
type Err = <$other as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$other::from_str(s).map($name)
}
}
impl Into<$other> for $name {
fn into(self) -> $other {
self.0
}
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
let mut hex = "0x".to_owned();
let mut bytes = [0u8; 8 * $size];
self.0.to_big_endian(&mut bytes);
let len = cmp::max((self.0.bits() + 7) / 8, 1);
let bytes_hex = bytes[bytes.len() - len..].to_hex();
if bytes_hex.starts_with('0') {
hex.push_str(&bytes_hex[1..]);
} else {
hex.push_str(&bytes_hex);
}
serializer.serialize_str(&hex)
}
}
impl serde::Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<$name, D::Error>
where D: serde::Deserializer {
struct UintVisitor;
impl serde::de::Visitor for UintVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: serde::Error {
// 0x + len
if value.len() > 2 + $size * 16 || value.len() < 2 {
return Err(serde::Error::custom("Invalid length."));
}
if &value[0..2]!= "0x" {
return Err(serde::Error::custom("Use hex encoded numbers with 0x prefix."))
}
$other::from_str(&value[2..]).map($name).map_err(|_| serde::Error::custom("Invalid hex value."))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: serde::Error {
self.visit_str(&value)
}
}
deserializer.deserialize(UintVisitor)
}
}
}
}
impl_uint!(U256, EthU256, 4);
#[cfg(test)]
mod tests {
use super::U256;
use serde_json;
type Res = Result<U256, serde_json::Error>;
#[test]
fn should_serialize_u256() {
let serialized1 = serde_json::to_string(&U256(0.into())).unwrap();
let serialized2 = serde_json::to_string(&U256(1.into())).unwrap();
let serialized3 = serde_json::to_string(&U256(16.into())).unwrap();
let serialized4 = serde_json::to_string(&U256(256.into())).unwrap();
assert_eq!(serialized1, r#""0x0""#);
assert_eq!(serialized2, r#""0x1""#);
assert_eq!(serialized3, r#""0x10""#);
assert_eq!(serialized4, r#""0x100""#);
}
#[test]
fn should_fail_to_deserialize_decimals() |
#[test]
fn should_deserialize_u256() {
let deserialized1: U256 = serde_json::from_str(r#""0x""#).unwrap();
let deserialized2: U256 = serde_json::from_str(r#""0x0""#).unwrap();
let deserialized3: U256 = serde_json::from_str(r#""0x1""#).unwrap();
let deserialized4: U256 = serde_json::from_str(r#""0x01""#).unwrap();
let deserialized5: U256 = serde_json::from_str(r#""0x100""#).unwrap();
assert_eq!(deserialized1, U256(0.into()));
assert_eq!(deserialized2, U256(0.into()));
assert_eq!(deserialized3, U256(1.into()));
assert_eq!(deserialized4, U256(1.into()));
assert_eq!(deserialized5, U256(256.into()));
}
}
| {
let deserialized1: Res = serde_json::from_str(r#""""#);
let deserialized2: Res = serde_json::from_str(r#""0""#);
let deserialized3: Res = serde_json::from_str(r#""10""#);
let deserialized4: Res = serde_json::from_str(r#""1000000""#);
let deserialized5: Res = serde_json::from_str(r#""1000000000000000000""#);
assert!(deserialized1.is_err());
assert!(deserialized2.is_err());
assert!(deserialized3.is_err());
assert!(deserialized4.is_err());
assert!(deserialized5.is_err());
} | identifier_body |
formatting.rs | pub mod placeholder;
pub mod prefix;
pub mod unit;
pub mod value;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use serde::de::{MapAccess, Visitor};
use serde::{de, Deserialize, Deserializer};
use crate::errors::*;
use placeholder::unexpected_token;
use placeholder::Placeholder;
use value::Value;
#[derive(Debug, Clone, PartialEq)]
enum Token {
Text(String),
Var(Placeholder),
}
#[derive(Debug, Default, Clone)]
pub struct FormatTemplate {
full: Option<Vec<Token>>,
short: Option<Vec<Token>>,
}
pub trait FormatMapKey: Borrow<str> + Eq + Hash {}
impl<T> FormatMapKey for T where T: Borrow<str> + Eq + Hash {}
impl FormatTemplate {
pub fn new(full: &str, short: Option<&str>) -> Result<Self> {
Self::new_opt(Some(full), short)
}
pub fn new_opt(full: Option<&str>, short: Option<&str>) -> Result<Self> {
let full = match full {
Some(full) => Some(Self::tokens_from_string(full)?),
None => None,
};
let short = match short {
Some(short) => Some(Self::tokens_from_string(short)?),
None => None,
};
Ok(Self { full, short })
}
/// Initialize `full` field if it is `None`
pub fn with_default(mut self, default_full: &str) -> Result<Self> {
if self.full.is_none() {
self.full = Some(Self::tokens_from_string(default_full)?);
}
Ok(self)
}
/// Whether the format string contains a given placeholder
pub fn contains(&self, var: &str) -> bool {
Self::format_contains(&self.full, var) || Self::format_contains(&self.short, var)
}
pub fn has_tokens(&self) -> bool {
!self.full.as_ref().map(Vec::is_empty).unwrap_or(true)
||!self.short.as_ref().map(Vec::is_empty).unwrap_or(true)
}
fn format_contains(format: &Option<Vec<Token>>, var: &str) -> bool {
if let Some(tokens) = format {
for token in tokens {
if let Token::Var(ref placeholder) = token {
if placeholder.name == var {
return true;
}
}
}
}
false
}
fn tokens_from_string(mut s: &str) -> Result<Vec<Token>> {
let mut tokens = vec![];
// Push text into tokens vector. Check the text for correctness and don't push empty strings
let push_text = |tokens: &mut Vec<Token>, x: &str| {
if x.contains('{') {
unexpected_token('{')
} else if x.contains('}') {
unexpected_token('}')
} else if!x.is_empty() {
tokens.push(Token::Text(x.to_string()));
Ok(())
} else {
Ok(())
}
};
while!s.is_empty() {
// Split `"text {key:1} {key}"` into `"text "` and `"key:1} {key}"`
match s.split_once('{') {
// No placeholders found -> the whole string is just text
None => {
push_text(&mut tokens, s)?;
break;
}
// Found placeholder
Some((before, after)) => {
// `before` is just a text
push_text(&mut tokens, before)?;
// Split `"key:1} {key}"` into `"key:1"` and `" {key}"`
match after.split_once('}') {
// No matching `}`!
None => {
return Err(InternalError(
"format parser".to_string(),
"missing '}'".to_string(),
None,
));
}
// Found the entire placeholder
Some((placeholder, rest)) => {
// `placeholder.parse()` parses the placeholder's configuration string
// (e.g. something like `"key:1;K"`) into `Placeholder` struct. We don't
// need to think about that in this code.
tokens.push(Token::Var(placeholder.parse()?));
s = rest;
}
}
}
}
}
Ok(tokens)
}
pub fn render(
&self,
vars: &HashMap<impl FormatMapKey, Value>,
) -> Result<(String, Option<String>)> {
let full = match &self.full {
Some(tokens) => Self::render_tokens(tokens, vars)?,
None => String::new(), // TODO: throw an error that says that it's a bug?
};
let short = match &self.short {
Some(short) => Some(Self::render_tokens(short, vars)?),
None => None,
};
Ok((full, short))
}
fn render_tokens(tokens: &[Token], vars: &HashMap<impl FormatMapKey, Value>) -> Result<String> {
let mut rendered = String::new();
for token in tokens {
match token {
Token::Text(text) => rendered.push_str(text),
Token::Var(var) => rendered.push_str(
&vars
.get(&*var.name)
.internal_error(
"util",
&format!("Unknown placeholder in format string: '{}'", var.name),
)?
.format(var)?,
),
}
}
Ok(rendered)
}
}
impl<'de> Deserialize<'de> for FormatTemplate {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Full,
Short,
}
struct FormatTemplateVisitor;
impl<'de> Visitor<'de> for FormatTemplateVisitor {
type Value = FormatTemplate;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result |
/// Handle configs like:
///
/// ```toml
/// format = "{layout}"
/// ```
fn visit_str<E>(self, full: &str) -> StdResult<FormatTemplate, E>
where
E: de::Error,
{
FormatTemplate::new(full, None).map_err(de::Error::custom)
}
/// Handle configs like:
///
/// ```toml
/// [block.format]
/// full = "{layout}"
/// short = "{layout^2}"
/// ```
fn visit_map<V>(self, mut map: V) -> StdResult<FormatTemplate, V::Error>
where
V: MapAccess<'de>,
{
let mut full: Option<String> = None;
let mut short: Option<String> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Full => {
if full.is_some() {
return Err(de::Error::duplicate_field("full"));
}
full = Some(map.next_value()?);
}
Field::Short => {
if short.is_some() {
return Err(de::Error::duplicate_field("short"));
}
short = Some(map.next_value()?);
}
}
}
FormatTemplate::new_opt(full.as_deref(), short.as_deref())
.map_err(de::Error::custom)
}
}
deserializer.deserialize_any(FormatTemplateVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render() {
let ft = FormatTemplate::new(
"some text {var} var again {var}{new_var:3} {bar:2#100} {freq;1}.",
None,
);
assert!(ft.is_ok());
let values = map!(
"var" => Value::from_string("|var value|".to_string()),
"new_var" => Value::from_integer(12),
"bar" => Value::from_integer(25),
"freq" => Value::from_float(0.01).hertz(),
);
assert_eq!(
ft.unwrap().render(&values).unwrap().0.as_str(),
"some text |var value| var again |var value| 12 \u{258c} 0.0Hz."
);
}
#[test]
fn contains() {
let format = FormatTemplate::new("some text {foo} {bar:1} foobar", None);
assert!(format.is_ok());
let format = format.unwrap();
assert!(format.contains("foo"));
assert!(format.contains("bar"));
assert!(!format.contains("foobar"));
assert!(!format.contains("random string"));
}
}
| {
formatter.write_str("format structure")
} | identifier_body |
formatting.rs | pub mod placeholder;
pub mod prefix;
pub mod unit;
pub mod value;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use serde::de::{MapAccess, Visitor};
use serde::{de, Deserialize, Deserializer};
use crate::errors::*;
use placeholder::unexpected_token;
use placeholder::Placeholder;
use value::Value;
#[derive(Debug, Clone, PartialEq)]
enum Token {
Text(String),
Var(Placeholder),
}
#[derive(Debug, Default, Clone)]
pub struct FormatTemplate {
full: Option<Vec<Token>>,
short: Option<Vec<Token>>,
}
pub trait FormatMapKey: Borrow<str> + Eq + Hash {}
impl<T> FormatMapKey for T where T: Borrow<str> + Eq + Hash {}
impl FormatTemplate {
pub fn new(full: &str, short: Option<&str>) -> Result<Self> {
Self::new_opt(Some(full), short)
}
pub fn new_opt(full: Option<&str>, short: Option<&str>) -> Result<Self> {
let full = match full {
Some(full) => Some(Self::tokens_from_string(full)?),
None => None,
};
let short = match short {
Some(short) => Some(Self::tokens_from_string(short)?),
None => None,
};
Ok(Self { full, short })
}
/// Initialize `full` field if it is `None`
pub fn with_default(mut self, default_full: &str) -> Result<Self> {
if self.full.is_none() {
self.full = Some(Self::tokens_from_string(default_full)?);
}
Ok(self)
}
/// Whether the format string contains a given placeholder
pub fn contains(&self, var: &str) -> bool {
Self::format_contains(&self.full, var) || Self::format_contains(&self.short, var)
}
pub fn has_tokens(&self) -> bool {
!self.full.as_ref().map(Vec::is_empty).unwrap_or(true)
||!self.short.as_ref().map(Vec::is_empty).unwrap_or(true)
}
fn format_contains(format: &Option<Vec<Token>>, var: &str) -> bool {
if let Some(tokens) = format {
for token in tokens {
if let Token::Var(ref placeholder) = token {
if placeholder.name == var {
return true;
}
}
}
}
false
}
fn tokens_from_string(mut s: &str) -> Result<Vec<Token>> {
let mut tokens = vec![];
// Push text into tokens vector. Check the text for correctness and don't push empty strings
let push_text = |tokens: &mut Vec<Token>, x: &str| {
if x.contains('{') {
unexpected_token('{')
} else if x.contains('}') {
unexpected_token('}')
} else if!x.is_empty() {
tokens.push(Token::Text(x.to_string()));
Ok(())
} else {
Ok(())
}
};
while!s.is_empty() {
// Split `"text {key:1} {key}"` into `"text "` and `"key:1} {key}"`
match s.split_once('{') {
// No placeholders found -> the whole string is just text
None => {
push_text(&mut tokens, s)?;
break;
}
// Found placeholder
Some((before, after)) => {
// `before` is just a text
push_text(&mut tokens, before)?;
// Split `"key:1} {key}"` into `"key:1"` and `" {key}"`
match after.split_once('}') {
// No matching `}`!
None => {
return Err(InternalError(
"format parser".to_string(),
"missing '}'".to_string(),
None,
));
}
// Found the entire placeholder
Some((placeholder, rest)) => {
// `placeholder.parse()` parses the placeholder's configuration string
// (e.g. something like `"key:1;K"`) into `Placeholder` struct. We don't
// need to think about that in this code.
tokens.push(Token::Var(placeholder.parse()?));
s = rest;
}
}
}
}
}
Ok(tokens)
}
pub fn render(
&self,
vars: &HashMap<impl FormatMapKey, Value>,
) -> Result<(String, Option<String>)> {
let full = match &self.full {
Some(tokens) => Self::render_tokens(tokens, vars)?,
None => String::new(), // TODO: throw an error that says that it's a bug?
};
let short = match &self.short {
Some(short) => Some(Self::render_tokens(short, vars)?),
None => None,
};
Ok((full, short))
}
fn render_tokens(tokens: &[Token], vars: &HashMap<impl FormatMapKey, Value>) -> Result<String> {
let mut rendered = String::new();
for token in tokens {
match token {
Token::Text(text) => rendered.push_str(text),
Token::Var(var) => rendered.push_str(
&vars
.get(&*var.name)
.internal_error(
"util",
&format!("Unknown placeholder in format string: '{}'", var.name),
)?
.format(var)?,
),
}
}
Ok(rendered)
}
}
impl<'de> Deserialize<'de> for FormatTemplate {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Full,
Short,
}
struct FormatTemplateVisitor;
impl<'de> Visitor<'de> for FormatTemplateVisitor {
type Value = FormatTemplate;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("format structure")
}
/// Handle configs like:
///
/// ```toml
/// format = "{layout}"
/// ```
fn visit_str<E>(self, full: &str) -> StdResult<FormatTemplate, E>
where
E: de::Error,
{
FormatTemplate::new(full, None).map_err(de::Error::custom)
}
/// Handle configs like:
///
/// ```toml
/// [block.format]
/// full = "{layout}"
/// short = "{layout^2}"
/// ```
fn visit_map<V>(self, mut map: V) -> StdResult<FormatTemplate, V::Error>
where
V: MapAccess<'de>,
{
let mut full: Option<String> = None;
let mut short: Option<String> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Full => {
if full.is_some() {
return Err(de::Error::duplicate_field("full"));
}
full = Some(map.next_value()?);
}
Field::Short => {
if short.is_some() {
return Err(de::Error::duplicate_field("short"));
}
short = Some(map.next_value()?);
}
}
}
FormatTemplate::new_opt(full.as_deref(), short.as_deref())
.map_err(de::Error::custom)
}
}
deserializer.deserialize_any(FormatTemplateVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render() {
let ft = FormatTemplate::new(
"some text {var} var again {var}{new_var:3} {bar:2#100} {freq;1}.",
None,
);
assert!(ft.is_ok());
let values = map!(
"var" => Value::from_string("|var value|".to_string()),
"new_var" => Value::from_integer(12),
"bar" => Value::from_integer(25),
"freq" => Value::from_float(0.01).hertz(),
);
assert_eq!(
ft.unwrap().render(&values).unwrap().0.as_str(),
"some text |var value| var again |var value| 12 \u{258c} 0.0Hz."
);
}
#[test]
fn | () {
let format = FormatTemplate::new("some text {foo} {bar:1} foobar", None);
assert!(format.is_ok());
let format = format.unwrap();
assert!(format.contains("foo"));
assert!(format.contains("bar"));
assert!(!format.contains("foobar"));
assert!(!format.contains("random string"));
}
}
| contains | identifier_name |
formatting.rs | pub mod placeholder;
pub mod prefix;
pub mod unit;
pub mod value;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use serde::de::{MapAccess, Visitor};
use serde::{de, Deserialize, Deserializer};
use crate::errors::*;
use placeholder::unexpected_token;
use placeholder::Placeholder;
use value::Value;
#[derive(Debug, Clone, PartialEq)]
enum Token {
Text(String),
Var(Placeholder),
}
#[derive(Debug, Default, Clone)]
pub struct FormatTemplate {
full: Option<Vec<Token>>,
short: Option<Vec<Token>>,
}
pub trait FormatMapKey: Borrow<str> + Eq + Hash {}
impl<T> FormatMapKey for T where T: Borrow<str> + Eq + Hash {}
impl FormatTemplate {
pub fn new(full: &str, short: Option<&str>) -> Result<Self> {
Self::new_opt(Some(full), short)
}
pub fn new_opt(full: Option<&str>, short: Option<&str>) -> Result<Self> {
let full = match full {
Some(full) => Some(Self::tokens_from_string(full)?),
None => None,
};
let short = match short {
Some(short) => Some(Self::tokens_from_string(short)?),
None => None,
};
Ok(Self { full, short })
}
/// Initialize `full` field if it is `None`
pub fn with_default(mut self, default_full: &str) -> Result<Self> {
if self.full.is_none() {
self.full = Some(Self::tokens_from_string(default_full)?);
}
Ok(self)
}
/// Whether the format string contains a given placeholder
pub fn contains(&self, var: &str) -> bool {
Self::format_contains(&self.full, var) || Self::format_contains(&self.short, var)
}
pub fn has_tokens(&self) -> bool {
!self.full.as_ref().map(Vec::is_empty).unwrap_or(true)
||!self.short.as_ref().map(Vec::is_empty).unwrap_or(true)
}
fn format_contains(format: &Option<Vec<Token>>, var: &str) -> bool {
if let Some(tokens) = format {
for token in tokens {
if let Token::Var(ref placeholder) = token {
if placeholder.name == var {
return true; | false
}
fn tokens_from_string(mut s: &str) -> Result<Vec<Token>> {
let mut tokens = vec![];
// Push text into tokens vector. Check the text for correctness and don't push empty strings
let push_text = |tokens: &mut Vec<Token>, x: &str| {
if x.contains('{') {
unexpected_token('{')
} else if x.contains('}') {
unexpected_token('}')
} else if!x.is_empty() {
tokens.push(Token::Text(x.to_string()));
Ok(())
} else {
Ok(())
}
};
while!s.is_empty() {
// Split `"text {key:1} {key}"` into `"text "` and `"key:1} {key}"`
match s.split_once('{') {
// No placeholders found -> the whole string is just text
None => {
push_text(&mut tokens, s)?;
break;
}
// Found placeholder
Some((before, after)) => {
// `before` is just a text
push_text(&mut tokens, before)?;
// Split `"key:1} {key}"` into `"key:1"` and `" {key}"`
match after.split_once('}') {
// No matching `}`!
None => {
return Err(InternalError(
"format parser".to_string(),
"missing '}'".to_string(),
None,
));
}
// Found the entire placeholder
Some((placeholder, rest)) => {
// `placeholder.parse()` parses the placeholder's configuration string
// (e.g. something like `"key:1;K"`) into `Placeholder` struct. We don't
// need to think about that in this code.
tokens.push(Token::Var(placeholder.parse()?));
s = rest;
}
}
}
}
}
Ok(tokens)
}
pub fn render(
&self,
vars: &HashMap<impl FormatMapKey, Value>,
) -> Result<(String, Option<String>)> {
let full = match &self.full {
Some(tokens) => Self::render_tokens(tokens, vars)?,
None => String::new(), // TODO: throw an error that says that it's a bug?
};
let short = match &self.short {
Some(short) => Some(Self::render_tokens(short, vars)?),
None => None,
};
Ok((full, short))
}
fn render_tokens(tokens: &[Token], vars: &HashMap<impl FormatMapKey, Value>) -> Result<String> {
let mut rendered = String::new();
for token in tokens {
match token {
Token::Text(text) => rendered.push_str(text),
Token::Var(var) => rendered.push_str(
&vars
.get(&*var.name)
.internal_error(
"util",
&format!("Unknown placeholder in format string: '{}'", var.name),
)?
.format(var)?,
),
}
}
Ok(rendered)
}
}
impl<'de> Deserialize<'de> for FormatTemplate {
fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Full,
Short,
}
struct FormatTemplateVisitor;
impl<'de> Visitor<'de> for FormatTemplateVisitor {
type Value = FormatTemplate;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("format structure")
}
/// Handle configs like:
///
/// ```toml
/// format = "{layout}"
/// ```
fn visit_str<E>(self, full: &str) -> StdResult<FormatTemplate, E>
where
E: de::Error,
{
FormatTemplate::new(full, None).map_err(de::Error::custom)
}
/// Handle configs like:
///
/// ```toml
/// [block.format]
/// full = "{layout}"
/// short = "{layout^2}"
/// ```
fn visit_map<V>(self, mut map: V) -> StdResult<FormatTemplate, V::Error>
where
V: MapAccess<'de>,
{
let mut full: Option<String> = None;
let mut short: Option<String> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Full => {
if full.is_some() {
return Err(de::Error::duplicate_field("full"));
}
full = Some(map.next_value()?);
}
Field::Short => {
if short.is_some() {
return Err(de::Error::duplicate_field("short"));
}
short = Some(map.next_value()?);
}
}
}
FormatTemplate::new_opt(full.as_deref(), short.as_deref())
.map_err(de::Error::custom)
}
}
deserializer.deserialize_any(FormatTemplateVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render() {
let ft = FormatTemplate::new(
"some text {var} var again {var}{new_var:3} {bar:2#100} {freq;1}.",
None,
);
assert!(ft.is_ok());
let values = map!(
"var" => Value::from_string("|var value|".to_string()),
"new_var" => Value::from_integer(12),
"bar" => Value::from_integer(25),
"freq" => Value::from_float(0.01).hertz(),
);
assert_eq!(
ft.unwrap().render(&values).unwrap().0.as_str(),
"some text |var value| var again |var value| 12 \u{258c} 0.0Hz."
);
}
#[test]
fn contains() {
let format = FormatTemplate::new("some text {foo} {bar:1} foobar", None);
assert!(format.is_ok());
let format = format.unwrap();
assert!(format.contains("foo"));
assert!(format.contains("bar"));
assert!(!format.contains("foobar"));
assert!(!format.contains("random string"));
}
} | }
}
}
} | random_line_split |
engine.rs | use fact_db::FactDB;
use std::collections::hash_map::HashMap;
use native_types::*;
pub struct Engine {
fact_db : Box<FactDB + Send>,
funcs : HashMap<String, HFunc>
}
#[derive(Debug)]
pub enum Error {
Invalid(String),
Internal(String),
Type(String),
Db(String)
}
use self::Error::*;
fn substitute(clause : &Clause, ans : &Vec<HValue>) -> Fact {
use native_types::MatchExpr::*;
Fact {
pred_name : clause.pred_name.clone(),
args : clause.args.iter().map(|slot| {
match slot {
&Unbound => panic!("Unbound is not allowed in substituted facts"),
&Var(ref n) => ans[*n as usize].clone(),
&HConst(ref v) => v.clone()
}
}).collect()
}
}
impl Engine {
pub fn new(db : Box<FactDB + Send>) -> Engine {
Engine {
fact_db : db,
funcs : HashMap::new(),
}
}
pub fn new_predicate(&mut self, pred : Predicate) -> Result<(), Error> {
// Verify we have at least one argument
if pred.types.len() == 0 {
return Err(Invalid("Predicates must have at least one argument.".to_string()));
}
// Check for existing predicates/type issues
match self.fact_db.get_predicate(&pred.name) {
Some(p) => {
if pred.types == p.types {
()
} else {
return Err(Type(format!("{:?}!= {:?}", pred.types, p.types)))
}
}
None => ()
}
// Have the FactDb persist it
{
use fact_db::PredResponse::*;
match self.fact_db.new_predicate(pred) {
PredicateInvalid(msg) => Err(Db(msg)),
PredicateTypeMismatch => panic!("PredicateTypeMismatch should be masked against"),
PredFail(msg) => Err(Internal(msg)),
PredicateExists | PredicateCreated => Ok(())
}
}
}
pub fn new_fact(&mut self, fact : &Fact) -> Result<(), Error> {
match self.fact_db.get_predicate(&fact.pred_name) {
Some(ref pred) => {
if (fact.args.len()!= pred.types.len())
|| (!fact.args.iter().zip(pred.types.iter()).all(type_check)) {
return Err(Type(format!("Fact ({:?}) does not match predicate ({:?})", fact, pred.types)))
}
}
None => return Err(Invalid("Predicate not registered".to_string()))
}
{
use fact_db::FactResponse::*;
use fact_db::RuleBy;
match self.fact_db.new_fact(&fact) {
FactCreated => {
for rule in self.fact_db.get_rules(RuleBy::Pred(fact.pred_name.clone())) {
self.run_rule(&rule);
}
Ok(())
}
FactExists => Ok(()),
FactTypeMismatch => Err(Type("Fact type mismatch".to_string())),
FactPredUnreg(_) => panic!("FactPredUnreg should be impossible"),
FactFail(msg) => Err(Internal(msg))
}
}
}
fn eval(&self, expr : &Expr, subs : &Vec<HValue>) -> Vec<HValue> {
use native_types::Expr::*;
match *expr {
EVar(var) => vec![subs[var as usize].clone()],
EVal(ref val) => vec![val.clone()],
EApp(ref fun_name, ref args) => {
let arg_vals = args.iter().map(|arg_expr|{
let v = self.eval(arg_expr, subs);
v[0].clone()
}).collect();
(self.funcs[fun_name].run)(arg_vals)
}
}
}
fn run_rule(&mut self, rule : &Rule) {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(&rule.body) {
SearchAns(anss) => {
//TODO: support anything other than one match, then wheres
'ans: for ans in anss {
if self.fact_db.rule_cache_miss(&rule, &ans) {
let mut ans = ans.clone();
for where_clause in rule.wheres.iter() {
let resp = self.eval(&where_clause.rhs, &ans);
for (lhs, rhs) in where_clause.asgns.iter().zip(resp.iter()) {
use native_types::MatchExpr::*;
use native_types::BindExpr::*;
match *lhs {
Normal(Unbound) => (),
Normal(HConst(ref v)) => {
if *v!= *rhs {
continue 'ans
}
}
Normal(Var(n)) => |
Iterate(_) => unimplemented!()
}
}
}
for head_clause in rule.head.iter() {
assert!(self.new_fact(&substitute(&head_clause, &ans)).is_ok());
}
}
}
}
SearchInvalid(s) => panic!("Internal invalid search query {}", s),
SearchFail(s) => panic!("Search procedure failure {}", s),
SearchNone => ()
}
}
pub fn derive(&self, query : &Vec<Clause>) -> Result<Vec<Vec<HValue>>, Error> {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(query) {
SearchNone => Ok(vec![]),
SearchAns(ans) => Ok(ans),
SearchInvalid(err) => Err(Invalid(format!("{:?}", err))),
SearchFail(err) => Err(Internal(format!("{:?}", err))),
}
}
pub fn new_rule(&mut self, rule : &Rule) -> Result<(), Error> {
use fact_db::RuleResponse::*;
match self.fact_db.new_rule(rule) {
RuleAdded => {
self.run_rule(rule);
Ok(())
}
RuleFail(msg) => {
Err(Internal(msg))
}
RuleInvalid(msg) => {
Err(Invalid(msg))
}
}
}
pub fn reg_func(&mut self, name : String, func : HFunc) {
self.funcs.insert(name, func);
}
}
| {
//Definition should be next to be defined.
assert!(n as usize == ans.len());
ans.push(rhs.clone());
} | conditional_block |
engine.rs | use fact_db::FactDB;
use std::collections::hash_map::HashMap;
use native_types::*;
pub struct Engine {
fact_db : Box<FactDB + Send>,
funcs : HashMap<String, HFunc>
}
#[derive(Debug)]
pub enum Error {
Invalid(String),
Internal(String),
Type(String),
Db(String)
}
use self::Error::*;
fn substitute(clause : &Clause, ans : &Vec<HValue>) -> Fact {
use native_types::MatchExpr::*;
Fact {
pred_name : clause.pred_name.clone(),
args : clause.args.iter().map(|slot| {
match slot {
&Unbound => panic!("Unbound is not allowed in substituted facts"),
&Var(ref n) => ans[*n as usize].clone(),
&HConst(ref v) => v.clone()
}
}).collect()
}
}
impl Engine {
pub fn new(db : Box<FactDB + Send>) -> Engine {
Engine {
fact_db : db,
funcs : HashMap::new(),
}
}
pub fn new_predicate(&mut self, pred : Predicate) -> Result<(), Error> {
// Verify we have at least one argument
if pred.types.len() == 0 {
return Err(Invalid("Predicates must have at least one argument.".to_string()));
}
// Check for existing predicates/type issues
match self.fact_db.get_predicate(&pred.name) {
Some(p) => {
if pred.types == p.types {
()
} else {
return Err(Type(format!("{:?}!= {:?}", pred.types, p.types)))
}
}
None => ()
}
// Have the FactDb persist it
{
use fact_db::PredResponse::*;
match self.fact_db.new_predicate(pred) {
PredicateInvalid(msg) => Err(Db(msg)),
PredicateTypeMismatch => panic!("PredicateTypeMismatch should be masked against"),
PredFail(msg) => Err(Internal(msg)),
PredicateExists | PredicateCreated => Ok(())
}
}
}
pub fn new_fact(&mut self, fact : &Fact) -> Result<(), Error> {
match self.fact_db.get_predicate(&fact.pred_name) {
Some(ref pred) => {
if (fact.args.len()!= pred.types.len())
|| (!fact.args.iter().zip(pred.types.iter()).all(type_check)) {
return Err(Type(format!("Fact ({:?}) does not match predicate ({:?})", fact, pred.types)))
}
}
None => return Err(Invalid("Predicate not registered".to_string()))
}
{
use fact_db::FactResponse::*;
use fact_db::RuleBy;
match self.fact_db.new_fact(&fact) {
FactCreated => {
for rule in self.fact_db.get_rules(RuleBy::Pred(fact.pred_name.clone())) {
self.run_rule(&rule);
}
Ok(())
}
FactExists => Ok(()),
FactTypeMismatch => Err(Type("Fact type mismatch".to_string())),
FactPredUnreg(_) => panic!("FactPredUnreg should be impossible"),
FactFail(msg) => Err(Internal(msg))
}
}
}
fn eval(&self, expr : &Expr, subs : &Vec<HValue>) -> Vec<HValue> {
use native_types::Expr::*;
match *expr {
EVar(var) => vec![subs[var as usize].clone()],
EVal(ref val) => vec![val.clone()],
EApp(ref fun_name, ref args) => {
let arg_vals = args.iter().map(|arg_expr|{
let v = self.eval(arg_expr, subs);
v[0].clone()
}).collect();
(self.funcs[fun_name].run)(arg_vals)
}
}
}
fn run_rule(&mut self, rule : &Rule) {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(&rule.body) {
SearchAns(anss) => {
//TODO: support anything other than one match, then wheres
'ans: for ans in anss {
if self.fact_db.rule_cache_miss(&rule, &ans) {
let mut ans = ans.clone();
for where_clause in rule.wheres.iter() {
let resp = self.eval(&where_clause.rhs, &ans);
for (lhs, rhs) in where_clause.asgns.iter().zip(resp.iter()) {
use native_types::MatchExpr::*;
use native_types::BindExpr::*;
match *lhs {
Normal(Unbound) => (),
Normal(HConst(ref v)) => {
if *v!= *rhs {
continue 'ans
}
}
Normal(Var(n)) => {
//Definition should be next to be defined.
assert!(n as usize == ans.len());
ans.push(rhs.clone());
}
Iterate(_) => unimplemented!()
}
}
}
for head_clause in rule.head.iter() {
assert!(self.new_fact(&substitute(&head_clause, &ans)).is_ok());
}
}
}
}
SearchInvalid(s) => panic!("Internal invalid search query {}", s),
SearchFail(s) => panic!("Search procedure failure {}", s),
SearchNone => ()
}
}
pub fn derive(&self, query : &Vec<Clause>) -> Result<Vec<Vec<HValue>>, Error> {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(query) {
SearchNone => Ok(vec![]),
SearchAns(ans) => Ok(ans),
SearchInvalid(err) => Err(Invalid(format!("{:?}", err))),
SearchFail(err) => Err(Internal(format!("{:?}", err))),
}
}
pub fn new_rule(&mut self, rule : &Rule) -> Result<(), Error> {
use fact_db::RuleResponse::*;
match self.fact_db.new_rule(rule) {
RuleAdded => {
self.run_rule(rule);
Ok(())
}
RuleFail(msg) => {
Err(Internal(msg))
}
RuleInvalid(msg) => {
Err(Invalid(msg))
} | pub fn reg_func(&mut self, name : String, func : HFunc) {
self.funcs.insert(name, func);
}
} | }
} | random_line_split |
engine.rs | use fact_db::FactDB;
use std::collections::hash_map::HashMap;
use native_types::*;
pub struct Engine {
fact_db : Box<FactDB + Send>,
funcs : HashMap<String, HFunc>
}
#[derive(Debug)]
pub enum Error {
Invalid(String),
Internal(String),
Type(String),
Db(String)
}
use self::Error::*;
fn substitute(clause : &Clause, ans : &Vec<HValue>) -> Fact {
use native_types::MatchExpr::*;
Fact {
pred_name : clause.pred_name.clone(),
args : clause.args.iter().map(|slot| {
match slot {
&Unbound => panic!("Unbound is not allowed in substituted facts"),
&Var(ref n) => ans[*n as usize].clone(),
&HConst(ref v) => v.clone()
}
}).collect()
}
}
impl Engine {
pub fn new(db : Box<FactDB + Send>) -> Engine {
Engine {
fact_db : db,
funcs : HashMap::new(),
}
}
pub fn new_predicate(&mut self, pred : Predicate) -> Result<(), Error> {
// Verify we have at least one argument
if pred.types.len() == 0 {
return Err(Invalid("Predicates must have at least one argument.".to_string()));
}
// Check for existing predicates/type issues
match self.fact_db.get_predicate(&pred.name) {
Some(p) => {
if pred.types == p.types {
()
} else {
return Err(Type(format!("{:?}!= {:?}", pred.types, p.types)))
}
}
None => ()
}
// Have the FactDb persist it
{
use fact_db::PredResponse::*;
match self.fact_db.new_predicate(pred) {
PredicateInvalid(msg) => Err(Db(msg)),
PredicateTypeMismatch => panic!("PredicateTypeMismatch should be masked against"),
PredFail(msg) => Err(Internal(msg)),
PredicateExists | PredicateCreated => Ok(())
}
}
}
pub fn new_fact(&mut self, fact : &Fact) -> Result<(), Error> {
match self.fact_db.get_predicate(&fact.pred_name) {
Some(ref pred) => {
if (fact.args.len()!= pred.types.len())
|| (!fact.args.iter().zip(pred.types.iter()).all(type_check)) {
return Err(Type(format!("Fact ({:?}) does not match predicate ({:?})", fact, pred.types)))
}
}
None => return Err(Invalid("Predicate not registered".to_string()))
}
{
use fact_db::FactResponse::*;
use fact_db::RuleBy;
match self.fact_db.new_fact(&fact) {
FactCreated => {
for rule in self.fact_db.get_rules(RuleBy::Pred(fact.pred_name.clone())) {
self.run_rule(&rule);
}
Ok(())
}
FactExists => Ok(()),
FactTypeMismatch => Err(Type("Fact type mismatch".to_string())),
FactPredUnreg(_) => panic!("FactPredUnreg should be impossible"),
FactFail(msg) => Err(Internal(msg))
}
}
}
fn eval(&self, expr : &Expr, subs : &Vec<HValue>) -> Vec<HValue> {
use native_types::Expr::*;
match *expr {
EVar(var) => vec![subs[var as usize].clone()],
EVal(ref val) => vec![val.clone()],
EApp(ref fun_name, ref args) => {
let arg_vals = args.iter().map(|arg_expr|{
let v = self.eval(arg_expr, subs);
v[0].clone()
}).collect();
(self.funcs[fun_name].run)(arg_vals)
}
}
}
fn | (&mut self, rule : &Rule) {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(&rule.body) {
SearchAns(anss) => {
//TODO: support anything other than one match, then wheres
'ans: for ans in anss {
if self.fact_db.rule_cache_miss(&rule, &ans) {
let mut ans = ans.clone();
for where_clause in rule.wheres.iter() {
let resp = self.eval(&where_clause.rhs, &ans);
for (lhs, rhs) in where_clause.asgns.iter().zip(resp.iter()) {
use native_types::MatchExpr::*;
use native_types::BindExpr::*;
match *lhs {
Normal(Unbound) => (),
Normal(HConst(ref v)) => {
if *v!= *rhs {
continue 'ans
}
}
Normal(Var(n)) => {
//Definition should be next to be defined.
assert!(n as usize == ans.len());
ans.push(rhs.clone());
}
Iterate(_) => unimplemented!()
}
}
}
for head_clause in rule.head.iter() {
assert!(self.new_fact(&substitute(&head_clause, &ans)).is_ok());
}
}
}
}
SearchInvalid(s) => panic!("Internal invalid search query {}", s),
SearchFail(s) => panic!("Search procedure failure {}", s),
SearchNone => ()
}
}
pub fn derive(&self, query : &Vec<Clause>) -> Result<Vec<Vec<HValue>>, Error> {
use fact_db::SearchResponse::*;
match self.fact_db.search_facts(query) {
SearchNone => Ok(vec![]),
SearchAns(ans) => Ok(ans),
SearchInvalid(err) => Err(Invalid(format!("{:?}", err))),
SearchFail(err) => Err(Internal(format!("{:?}", err))),
}
}
pub fn new_rule(&mut self, rule : &Rule) -> Result<(), Error> {
use fact_db::RuleResponse::*;
match self.fact_db.new_rule(rule) {
RuleAdded => {
self.run_rule(rule);
Ok(())
}
RuleFail(msg) => {
Err(Internal(msg))
}
RuleInvalid(msg) => {
Err(Invalid(msg))
}
}
}
pub fn reg_func(&mut self, name : String, func : HFunc) {
self.funcs.insert(name, func);
}
}
| run_rule | identifier_name |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write};
use std::iter;
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
Shell options may be set using the '-' character, and unset using the '+' character.
OPTIONS
-e Exit immediately if a command exits with a non-zero status.
-o Specifies that an argument will follow that sets the key map.
The keymap argument may be either `vi` or `emacs`.
-x Specifies that commands will be printed as they are executed.
-- Following arguments will be set as positional arguments in the shell.
If no argument are supplied, arguments will be unset.
- Following arguments will be set as positional arguments in the shell.
If no arguments are suppled, arguments will not be unset.
"#;
enum PositionalArgs {
UnsetIfNone,
RetainIfNone,
}
use self::PositionalArgs::*;
pub(crate) fn set(args: &[&str], shell: &mut Shell) -> i32 {
let stdout = io::stdout();
let stderr = io::stderr();
let mut args_iter = args.iter();
let mut positionals = None;
while let Some(arg) = args_iter.next() {
if arg.starts_with("--") {
if arg.len() == 2 {
positionals = Some(UnsetIfNone);
break;
}
if &arg[2..] == "help" {
let mut stdout = stdout.lock();
let _ = stdout.write(HELP.as_bytes());
} else |
} else if arg.starts_with('-') {
if arg.len() == 1 {
positionals = Some(RetainIfNone);
break;
}
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags |= ERR_EXIT,
b'o' => match args_iter.next() {
Some(&mode) if mode == "vi" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Vi;
}
}
Some(&mode) if mode == "emacs" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Emacs;
}
}
Some(_) => {
let _ = stderr.lock().write_all(b"set: invalid keymap\n");
return 0;
}
None => {
let _ = stderr.lock().write_all(b"set: no keymap given\n");
return 0;
}
},
b'x' => shell.flags |= PRINT_COMMS,
_ => return 0,
}
}
} else if arg.starts_with('+') {
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags &= 255 ^ ERR_EXIT,
b'x' => shell.flags &= 255 ^ PRINT_COMMS,
_ => return 0,
}
}
}
}
match positionals {
None => (),
Some(kind) => {
let command: String = shell.variables.get_array("args").unwrap()[0].to_owned();
// This used to take a `&[String]` but cloned them all, so although
// this is non-ideal and could probably be better done with `Rc`, it
// hasn't got any slower.
let arguments = iter::once(command).chain(args_iter.map(|i| i.to_string())).collect();
match kind {
UnsetIfNone => shell.variables.set_array("args", arguments),
RetainIfNone => if arguments.len()!= 1 {
shell.variables.set_array("args", arguments);
},
}
}
}
0
}
| {
return 0;
} | conditional_block |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write}; |
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
Shell options may be set using the '-' character, and unset using the '+' character.
OPTIONS
-e Exit immediately if a command exits with a non-zero status.
-o Specifies that an argument will follow that sets the key map.
The keymap argument may be either `vi` or `emacs`.
-x Specifies that commands will be printed as they are executed.
-- Following arguments will be set as positional arguments in the shell.
If no argument are supplied, arguments will be unset.
- Following arguments will be set as positional arguments in the shell.
If no arguments are suppled, arguments will not be unset.
"#;
enum PositionalArgs {
UnsetIfNone,
RetainIfNone,
}
use self::PositionalArgs::*;
pub(crate) fn set(args: &[&str], shell: &mut Shell) -> i32 {
let stdout = io::stdout();
let stderr = io::stderr();
let mut args_iter = args.iter();
let mut positionals = None;
while let Some(arg) = args_iter.next() {
if arg.starts_with("--") {
if arg.len() == 2 {
positionals = Some(UnsetIfNone);
break;
}
if &arg[2..] == "help" {
let mut stdout = stdout.lock();
let _ = stdout.write(HELP.as_bytes());
} else {
return 0;
}
} else if arg.starts_with('-') {
if arg.len() == 1 {
positionals = Some(RetainIfNone);
break;
}
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags |= ERR_EXIT,
b'o' => match args_iter.next() {
Some(&mode) if mode == "vi" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Vi;
}
}
Some(&mode) if mode == "emacs" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Emacs;
}
}
Some(_) => {
let _ = stderr.lock().write_all(b"set: invalid keymap\n");
return 0;
}
None => {
let _ = stderr.lock().write_all(b"set: no keymap given\n");
return 0;
}
},
b'x' => shell.flags |= PRINT_COMMS,
_ => return 0,
}
}
} else if arg.starts_with('+') {
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags &= 255 ^ ERR_EXIT,
b'x' => shell.flags &= 255 ^ PRINT_COMMS,
_ => return 0,
}
}
}
}
match positionals {
None => (),
Some(kind) => {
let command: String = shell.variables.get_array("args").unwrap()[0].to_owned();
// This used to take a `&[String]` but cloned them all, so although
// this is non-ideal and could probably be better done with `Rc`, it
// hasn't got any slower.
let arguments = iter::once(command).chain(args_iter.map(|i| i.to_string())).collect();
match kind {
UnsetIfNone => shell.variables.set_array("args", arguments),
RetainIfNone => if arguments.len()!= 1 {
shell.variables.set_array("args", arguments);
},
}
}
}
0
} | use std::iter; | random_line_split |
set.rs | use liner::KeyBindings;
use shell::Shell;
use shell::flags::*;
use std::io::{self, Write};
use std::iter;
const HELP: &'static str = r#"NAME
set - Set or unset values of shell options and positional parameters.
SYNOPSIS
set [ --help ] [-e | +e] [-x | +x] [-o [vi | emacs]] [- | --] [STRING]...
DESCRIPTION
Shell options may be set using the '-' character, and unset using the '+' character.
OPTIONS
-e Exit immediately if a command exits with a non-zero status.
-o Specifies that an argument will follow that sets the key map.
The keymap argument may be either `vi` or `emacs`.
-x Specifies that commands will be printed as they are executed.
-- Following arguments will be set as positional arguments in the shell.
If no argument are supplied, arguments will be unset.
- Following arguments will be set as positional arguments in the shell.
If no arguments are suppled, arguments will not be unset.
"#;
enum PositionalArgs {
UnsetIfNone,
RetainIfNone,
}
use self::PositionalArgs::*;
pub(crate) fn | (args: &[&str], shell: &mut Shell) -> i32 {
let stdout = io::stdout();
let stderr = io::stderr();
let mut args_iter = args.iter();
let mut positionals = None;
while let Some(arg) = args_iter.next() {
if arg.starts_with("--") {
if arg.len() == 2 {
positionals = Some(UnsetIfNone);
break;
}
if &arg[2..] == "help" {
let mut stdout = stdout.lock();
let _ = stdout.write(HELP.as_bytes());
} else {
return 0;
}
} else if arg.starts_with('-') {
if arg.len() == 1 {
positionals = Some(RetainIfNone);
break;
}
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags |= ERR_EXIT,
b'o' => match args_iter.next() {
Some(&mode) if mode == "vi" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Vi;
}
}
Some(&mode) if mode == "emacs" => {
if let Some(context) = shell.context.as_mut() {
context.key_bindings = KeyBindings::Emacs;
}
}
Some(_) => {
let _ = stderr.lock().write_all(b"set: invalid keymap\n");
return 0;
}
None => {
let _ = stderr.lock().write_all(b"set: no keymap given\n");
return 0;
}
},
b'x' => shell.flags |= PRINT_COMMS,
_ => return 0,
}
}
} else if arg.starts_with('+') {
for flag in arg.bytes().skip(1) {
match flag {
b'e' => shell.flags &= 255 ^ ERR_EXIT,
b'x' => shell.flags &= 255 ^ PRINT_COMMS,
_ => return 0,
}
}
}
}
match positionals {
None => (),
Some(kind) => {
let command: String = shell.variables.get_array("args").unwrap()[0].to_owned();
// This used to take a `&[String]` but cloned them all, so although
// this is non-ideal and could probably be better done with `Rc`, it
// hasn't got any slower.
let arguments = iter::once(command).chain(args_iter.map(|i| i.to_string())).collect();
match kind {
UnsetIfNone => shell.variables.set_array("args", arguments),
RetainIfNone => if arguments.len()!= 1 {
shell.variables.set_array("args", arguments);
},
}
}
}
0
}
| set | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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.
//! Module that contains Protobuf messages used by Exonum.
use anyhow::{ensure, Error};
use exonum_proto::ProtobufConvert;
use std::convert::TryFrom;
use crate::helpers::{Height, Round, ValidatorId};
pub mod schema;
impl ProtobufConvert for Height {
type ProtoStruct = u64;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for Round {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for ValidatorId {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct |
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
u16::try_from(pb).is_ok(),
"{} is out of range for valid ValidatorId",
pb
);
Ok(Self(pb as u16))
}
}
| {
u32::from(self.0)
} | identifier_body |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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.
//! Module that contains Protobuf messages used by Exonum.
use anyhow::{ensure, Error};
use exonum_proto::ProtobufConvert;
use std::convert::TryFrom;
use crate::helpers::{Height, Round, ValidatorId};
pub mod schema;
impl ProtobufConvert for Height {
type ProtoStruct = u64;
fn | (&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for Round {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for ValidatorId {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
u32::from(self.0)
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
u16::try_from(pb).is_ok(),
"{} is out of range for valid ValidatorId",
pb
);
Ok(Self(pb as u16))
}
}
| to_pb | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// 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.
//! Module that contains Protobuf messages used by Exonum.
use anyhow::{ensure, Error};
use exonum_proto::ProtobufConvert;
use std::convert::TryFrom;
use crate::helpers::{Height, Round, ValidatorId};
pub mod schema;
impl ProtobufConvert for Height {
type ProtoStruct = u64;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for Round {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
self.0
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(Self(pb))
}
}
impl ProtobufConvert for ValidatorId {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
u32::from(self.0)
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> { | u16::try_from(pb).is_ok(),
"{} is out of range for valid ValidatorId",
pb
);
Ok(Self(pb as u16))
}
} | ensure!( | random_line_split |
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE];
#[no_mangle]
pub unsafe extern "C" fn handle_interrupt(num: u8, error_code: u64) {
// thread timer
if num == PIC_1.get_interrupt_idt_num(0) |
vga::print(b"!! Interrupt!!");
println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code);
if PIC_1.has_interrupt(num) {
PIC_1.end_of_interrupt();
}
if PIC_2.has_interrupt(num) {
PIC_1.end_of_interrupt();
PIC_2.end_of_interrupt();
}
}
pub unsafe fn init() {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type_attr = InterruptType::ValidInterruptGate;
// }
let ptr = IdtPtr::new(&IDT_TABLE);
ptr.load()
}
| {
__kernel_timer_tick();
// it will send EOI itself
return;
} | conditional_block |
mod.rs | prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item; | pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE];
#[no_mangle]
pub unsafe extern "C" fn handle_interrupt(num: u8, error_code: u64) {
// thread timer
if num == PIC_1.get_interrupt_idt_num(0) {
__kernel_timer_tick();
// it will send EOI itself
return;
}
vga::print(b"!! Interrupt!!");
println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code);
if PIC_1.has_interrupt(num) {
PIC_1.end_of_interrupt();
}
if PIC_2.has_interrupt(num) {
PIC_1.end_of_interrupt();
PIC_2.end_of_interrupt();
}
}
pub unsafe fn init() {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type_attr = InterruptType::ValidInterruptGate;
// }
let ptr = IdtPtr::new(&IDT_TABLE);
ptr.load()
} | random_line_split |
|
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE];
#[no_mangle]
pub unsafe extern "C" fn handle_interrupt(num: u8, error_code: u64) {
// thread timer
if num == PIC_1.get_interrupt_idt_num(0) {
__kernel_timer_tick();
// it will send EOI itself
return;
}
vga::print(b"!! Interrupt!!");
println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code);
if PIC_1.has_interrupt(num) {
PIC_1.end_of_interrupt();
}
if PIC_2.has_interrupt(num) {
PIC_1.end_of_interrupt();
PIC_2.end_of_interrupt();
}
}
pub unsafe fn init() | {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type_attr = InterruptType::ValidInterruptGate;
// }
let ptr = IdtPtr::new(&IDT_TABLE);
ptr.load()
} | identifier_body |
|
mod.rs |
prelude!();
use ::vga;
use super::pic::{PIC_1, PIC_2};
mod item;
pub use self::item::*;
mod idt_ptr;
pub use self::idt_ptr::*;
extern "C" {
fn interrupt0();
fn interrupt1();
}
extern {
fn __kernel_timer_tick();
}
const IDT_SIZE: usize = 64;
static mut IDT_TABLE: [IdtItem; IDT_SIZE] = [IdtItem::new(); IDT_SIZE];
#[no_mangle]
pub unsafe extern "C" fn handle_interrupt(num: u8, error_code: u64) {
// thread timer
if num == PIC_1.get_interrupt_idt_num(0) {
__kernel_timer_tick();
// it will send EOI itself
return;
}
vga::print(b"!! Interrupt!!");
println!("!! Interrupt: {:#x}, Error code: {:#x}", num, error_code);
if PIC_1.has_interrupt(num) {
PIC_1.end_of_interrupt();
}
if PIC_2.has_interrupt(num) {
PIC_1.end_of_interrupt();
PIC_2.end_of_interrupt();
}
}
pub unsafe fn | () {
let diff = interrupt1 as usize - interrupt0 as usize;
for i in 0..IDT_SIZE {
IDT_TABLE[i].set_offset(interrupt0 as usize + diff * i);
}
// 0 pic interrupt is used by thread scheduler
// { // FIXME
// let idx = PIC_1.get_interrupt_idt_num(0) as usize;
// IDT_TABLE[idx].type_attr = InterruptType::ValidInterruptGate;
// }
let ptr = IdtPtr::new(&IDT_TABLE);
ptr.load()
}
| init | identifier_name |
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progress: bool,
is_done: bool,
packets_send: u32,
packets_lost: u32,
packets_arrived: u32,
route_costs_sum: u32,
route_costs_min_sum: u32,
nodes_connected: usize,
nodes_disconnected: usize,
max_stretch: u32,
run_time: Duration,
dijkstra: Dijkstra
}
impl EvalPaths {
pub fn new() -> Self {
Self {
show_progress: false,
is_done: false,
packets_send: 0,
packets_lost: 0,
packets_arrived: 0,
route_costs_sum: 0,
route_costs_min_sum: 0,
nodes_connected: 0,
nodes_disconnected: 0,
max_stretch: 2,
run_time: Duration::new(0, 0),
dijkstra: Dijkstra::new(),
}
}
pub fn clear_stats(&mut self) {
self.is_done =false;
self.packets_send = 0;
self.packets_lost = 0;
self.packets_arrived = 0;
self.route_costs_sum = 0;
self.route_costs_min_sum = 0;
self.nodes_connected = 0;
self.nodes_disconnected = 0;
self.run_time = Duration::new(0, 0);
}
pub fn clear(&mut self) {
self.dijkstra.clear();
self.clear_stats();
}
pub fn show_progress(&mut self, show_progress: bool) {
self.show_progress = true;
}
fn test_path(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
source: ID, target: ID, costs_min: u32) {
// maximum stretch we record
let mut packet = TestPacket::new(source, source, source, target);
let mut path_costs = 0u32;
self.packets_send += 1;
// max steps to try until we give up
let max_steps = costs_min * self.max_stretch;
for _ in 0..max_steps {
if let Some(next) = route(&packet) {
// Check if link really exists
if let Some(link) = graph.get_link(packet.receiver, next) {
path_costs += link.cost() as u32;
if next == packet.destination {
// packet arrived
self.packets_arrived += 1;
break;
} else {
// forward packet
packet.transmitter = packet.receiver;
packet.receiver = next;
}
} else {
// invalid next hop
self.packets_lost += 1;
break;
}
} else {
// no next hop
self.packets_lost += 1;
break;
}
}
self.route_costs_sum += path_costs;
self.route_costs_min_sum += costs_min;
}
pub fn run_samples(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
samples: usize) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let mut progress = Progress::new();
let mut sample = 0;
if self.show_progress {
progress.start(samples, 0);
}
for _ in 0..samples {
let source = rand::thread_rng().gen_range(0, node_count);
let target = rand::thread_rng().gen_range(0, node_count);
if source == target {
// we do not test those paths
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
sample += 1;
if self.show_progress {
progress.update(samples, sample);
}
}
if self.show_progress {
progress.update(samples, samples);
}
self.run_time = now.elapsed();
self.is_done = true;
}
pub fn run_all(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let tests = (node_count as usize).pow(2);
//let mut progress = Progress::new("test: ");
//let mut test = 0;
//progress.start(tests, 0);
for source in 0..node_count {
for target in 0..node_count {
if source == target {
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
//test += 1;
//progress.update(tests, test);
}
}
self.run_time = now.elapsed();
//clear progress line
//progress.clear_line();
}
pub fn duration(&self) -> Duration {
self.run_time | }
pub fn stretch(&self) -> f32 {
(self.route_costs_sum as f32) / (self.route_costs_min_sum as f32)
}
pub fn arrived(&self) -> f32 {
100.0 * (self.packets_arrived as f32) / (self.packets_send as f32)
}
pub fn connectivity(&self) -> f32 {
100.0 * (self.nodes_connected as f32) / (self.nodes_connected + self.nodes_disconnected) as f32
}
pub fn get_results(&self) -> Vec<(&'static str, f32)> {
vec![
("arrived", self.arrived()),
("connectivity", self.connectivity()),
("stretch", self.stretch())
]
}
} | random_line_split |
|
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progress: bool,
is_done: bool,
packets_send: u32,
packets_lost: u32,
packets_arrived: u32,
route_costs_sum: u32,
route_costs_min_sum: u32,
nodes_connected: usize,
nodes_disconnected: usize,
max_stretch: u32,
run_time: Duration,
dijkstra: Dijkstra
}
impl EvalPaths {
pub fn new() -> Self {
Self {
show_progress: false,
is_done: false,
packets_send: 0,
packets_lost: 0,
packets_arrived: 0,
route_costs_sum: 0,
route_costs_min_sum: 0,
nodes_connected: 0,
nodes_disconnected: 0,
max_stretch: 2,
run_time: Duration::new(0, 0),
dijkstra: Dijkstra::new(),
}
}
pub fn clear_stats(&mut self) {
self.is_done =false;
self.packets_send = 0;
self.packets_lost = 0;
self.packets_arrived = 0;
self.route_costs_sum = 0;
self.route_costs_min_sum = 0;
self.nodes_connected = 0;
self.nodes_disconnected = 0;
self.run_time = Duration::new(0, 0);
}
pub fn | (&mut self) {
self.dijkstra.clear();
self.clear_stats();
}
pub fn show_progress(&mut self, show_progress: bool) {
self.show_progress = true;
}
fn test_path(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
source: ID, target: ID, costs_min: u32) {
// maximum stretch we record
let mut packet = TestPacket::new(source, source, source, target);
let mut path_costs = 0u32;
self.packets_send += 1;
// max steps to try until we give up
let max_steps = costs_min * self.max_stretch;
for _ in 0..max_steps {
if let Some(next) = route(&packet) {
// Check if link really exists
if let Some(link) = graph.get_link(packet.receiver, next) {
path_costs += link.cost() as u32;
if next == packet.destination {
// packet arrived
self.packets_arrived += 1;
break;
} else {
// forward packet
packet.transmitter = packet.receiver;
packet.receiver = next;
}
} else {
// invalid next hop
self.packets_lost += 1;
break;
}
} else {
// no next hop
self.packets_lost += 1;
break;
}
}
self.route_costs_sum += path_costs;
self.route_costs_min_sum += costs_min;
}
pub fn run_samples(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
samples: usize) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let mut progress = Progress::new();
let mut sample = 0;
if self.show_progress {
progress.start(samples, 0);
}
for _ in 0..samples {
let source = rand::thread_rng().gen_range(0, node_count);
let target = rand::thread_rng().gen_range(0, node_count);
if source == target {
// we do not test those paths
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
sample += 1;
if self.show_progress {
progress.update(samples, sample);
}
}
if self.show_progress {
progress.update(samples, samples);
}
self.run_time = now.elapsed();
self.is_done = true;
}
pub fn run_all(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let tests = (node_count as usize).pow(2);
//let mut progress = Progress::new("test: ");
//let mut test = 0;
//progress.start(tests, 0);
for source in 0..node_count {
for target in 0..node_count {
if source == target {
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
//test += 1;
//progress.update(tests, test);
}
}
self.run_time = now.elapsed();
//clear progress line
//progress.clear_line();
}
pub fn duration(&self) -> Duration {
self.run_time
}
pub fn stretch(&self) -> f32 {
(self.route_costs_sum as f32) / (self.route_costs_min_sum as f32)
}
pub fn arrived(&self) -> f32 {
100.0 * (self.packets_arrived as f32) / (self.packets_send as f32)
}
pub fn connectivity(&self) -> f32 {
100.0 * (self.nodes_connected as f32) / (self.nodes_connected + self.nodes_disconnected) as f32
}
pub fn get_results(&self) -> Vec<(&'static str, f32)> {
vec![
("arrived", self.arrived()),
("connectivity", self.connectivity()),
("stretch", self.stretch())
]
}
}
| clear | identifier_name |
eval_paths.rs | use std::time::{Instant, Duration};
use rand::Rng;
use crate::progress::Progress;
use crate::sim::TestPacket;
use crate::dijkstra::Dijkstra;
use crate::graph::*;
/*
* Test if all paths allow for routing.
* This test does not allow the state of the routing algorithm to change.
*/
pub struct EvalPaths {
show_progress: bool,
is_done: bool,
packets_send: u32,
packets_lost: u32,
packets_arrived: u32,
route_costs_sum: u32,
route_costs_min_sum: u32,
nodes_connected: usize,
nodes_disconnected: usize,
max_stretch: u32,
run_time: Duration,
dijkstra: Dijkstra
}
impl EvalPaths {
pub fn new() -> Self {
Self {
show_progress: false,
is_done: false,
packets_send: 0,
packets_lost: 0,
packets_arrived: 0,
route_costs_sum: 0,
route_costs_min_sum: 0,
nodes_connected: 0,
nodes_disconnected: 0,
max_stretch: 2,
run_time: Duration::new(0, 0),
dijkstra: Dijkstra::new(),
}
}
pub fn clear_stats(&mut self) {
self.is_done =false;
self.packets_send = 0;
self.packets_lost = 0;
self.packets_arrived = 0;
self.route_costs_sum = 0;
self.route_costs_min_sum = 0;
self.nodes_connected = 0;
self.nodes_disconnected = 0;
self.run_time = Duration::new(0, 0);
}
pub fn clear(&mut self) {
self.dijkstra.clear();
self.clear_stats();
}
pub fn show_progress(&mut self, show_progress: bool) {
self.show_progress = true;
}
fn test_path(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
source: ID, target: ID, costs_min: u32) {
// maximum stretch we record
let mut packet = TestPacket::new(source, source, source, target);
let mut path_costs = 0u32;
self.packets_send += 1;
// max steps to try until we give up
let max_steps = costs_min * self.max_stretch;
for _ in 0..max_steps {
if let Some(next) = route(&packet) {
// Check if link really exists
if let Some(link) = graph.get_link(packet.receiver, next) | else {
// invalid next hop
self.packets_lost += 1;
break;
}
} else {
// no next hop
self.packets_lost += 1;
break;
}
}
self.route_costs_sum += path_costs;
self.route_costs_min_sum += costs_min;
}
pub fn run_samples(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>,
samples: usize) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let mut progress = Progress::new();
let mut sample = 0;
if self.show_progress {
progress.start(samples, 0);
}
for _ in 0..samples {
let source = rand::thread_rng().gen_range(0, node_count);
let target = rand::thread_rng().gen_range(0, node_count);
if source == target {
// we do not test those paths
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
sample += 1;
if self.show_progress {
progress.update(samples, sample);
}
}
if self.show_progress {
progress.update(samples, samples);
}
self.run_time = now.elapsed();
self.is_done = true;
}
pub fn run_all(&mut self, graph: &Graph, mut route: impl FnMut(&TestPacket) -> Option<u32>) {
self.clear();
let node_count = graph.node_count();
if node_count < 2 {
return;
}
let now = Instant::now();
let tests = (node_count as usize).pow(2);
//let mut progress = Progress::new("test: ");
//let mut test = 0;
//progress.start(tests, 0);
for source in 0..node_count {
for target in 0..node_count {
if source == target {
continue;
}
let min = self.dijkstra.find_shortest_distance(graph, source as ID, target as ID);
if!min.is_finite() {
// no path from target to source => ignore
self.nodes_disconnected += 1;
continue;
} else {
self.nodes_connected += 1;
}
self.test_path(&graph, &mut route, source as ID, target as ID, min as u32);
//test += 1;
//progress.update(tests, test);
}
}
self.run_time = now.elapsed();
//clear progress line
//progress.clear_line();
}
pub fn duration(&self) -> Duration {
self.run_time
}
pub fn stretch(&self) -> f32 {
(self.route_costs_sum as f32) / (self.route_costs_min_sum as f32)
}
pub fn arrived(&self) -> f32 {
100.0 * (self.packets_arrived as f32) / (self.packets_send as f32)
}
pub fn connectivity(&self) -> f32 {
100.0 * (self.nodes_connected as f32) / (self.nodes_connected + self.nodes_disconnected) as f32
}
pub fn get_results(&self) -> Vec<(&'static str, f32)> {
vec![
("arrived", self.arrived()),
("connectivity", self.connectivity()),
("stretch", self.stretch())
]
}
}
| {
path_costs += link.cost() as u32;
if next == packet.destination {
// packet arrived
self.packets_arrived += 1;
break;
} else {
// forward packet
packet.transmitter = packet.receiver;
packet.receiver = next;
}
} | conditional_block |
endian.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::mem;
/// A value casted directly from a little-endian byte buffer. On big-endian
/// processors, the bytes of the value need to be swapped upon reading and writing.
#[repr(C)]
pub struct WireValue<T> {
value: T,
}
impl<T> WireValue<T> where T: Endian {
/// Reads the value, swapping bytes on big-endian processors.
#[inline]
pub fn get(&self) -> T { self.value.get() }
/// Writes the value, swapping bytes on big-endian processors.
#[inline]
pub fn set(&mut self, value: T) { self.value.set(value) }
}
/// Something that can appear in a `WireValue`.
pub trait Endian : Sized {
/// Reads the value, swapping bytes on big-endian processors.
fn get(&self) -> Self;
/// Writes the value, swapping bytes on big-endian processors.
fn set(&mut self, value: Self);
}
macro_rules! endian_impl(
($typ:ty) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { *self }
#[inline]
fn set(&mut self, value: $typ) {*self = value;}
}
);
($typ:ty, $swapper:ident) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { self.$swapper() }
#[inline]
fn set(&mut self, value: $typ) {
*self = value.$swapper();
}
}
);
);
// No swapping necessary for primitives of size less than one byte.
endian_impl!(());
endian_impl!(bool);
endian_impl!(u8);
endian_impl!(i8);
// Need to swap bytes for primitives larger than a byte.
endian_impl!(u16, to_le);
endian_impl!(i16, to_le);
endian_impl!(u32, to_le);
endian_impl!(i32, to_le);
endian_impl!(u64, to_le);
endian_impl!(i64, to_le);
impl Endian for f32 {
fn | (&self) -> f32 {
unsafe { mem::transmute(mem::transmute::<f32, u32>(*self).to_le()) }
}
fn set(&mut self, value : f32) {
*self = unsafe { mem::transmute(mem::transmute::<f32, u32>(value).to_le()) };
}
}
impl Endian for f64 {
fn get(&self) -> f64 {
unsafe { mem::transmute(mem::transmute::<f64, u64>(*self).to_le()) }
}
fn set(&mut self, value : f64) {
*self = unsafe { mem::transmute(mem::transmute::<f64, u64>(value).to_le()) };
}
}
| get | identifier_name |
endian.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::mem;
/// A value casted directly from a little-endian byte buffer. On big-endian
/// processors, the bytes of the value need to be swapped upon reading and writing.
#[repr(C)]
pub struct WireValue<T> {
value: T,
}
impl<T> WireValue<T> where T: Endian {
/// Reads the value, swapping bytes on big-endian processors.
#[inline]
pub fn get(&self) -> T { self.value.get() }
/// Writes the value, swapping bytes on big-endian processors.
#[inline]
pub fn set(&mut self, value: T) { self.value.set(value) }
}
/// Something that can appear in a `WireValue`.
pub trait Endian : Sized {
/// Reads the value, swapping bytes on big-endian processors.
fn get(&self) -> Self;
/// Writes the value, swapping bytes on big-endian processors.
fn set(&mut self, value: Self);
}
macro_rules! endian_impl(
($typ:ty) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { *self }
#[inline]
fn set(&mut self, value: $typ) {*self = value;}
}
);
($typ:ty, $swapper:ident) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { self.$swapper() }
#[inline]
fn set(&mut self, value: $typ) {
*self = value.$swapper();
}
}
);
);
// No swapping necessary for primitives of size less than one byte.
endian_impl!(());
endian_impl!(bool);
endian_impl!(u8);
endian_impl!(i8);
// Need to swap bytes for primitives larger than a byte.
endian_impl!(u16, to_le);
endian_impl!(i16, to_le);
endian_impl!(u32, to_le);
endian_impl!(i32, to_le);
endian_impl!(u64, to_le);
endian_impl!(i64, to_le);
impl Endian for f32 {
fn get(&self) -> f32 {
unsafe { mem::transmute(mem::transmute::<f32, u32>(*self).to_le()) }
}
fn set(&mut self, value : f32) {
*self = unsafe { mem::transmute(mem::transmute::<f32, u32>(value).to_le()) };
}
}
impl Endian for f64 {
fn get(&self) -> f64 {
unsafe { mem::transmute(mem::transmute::<f64, u64>(*self).to_le()) }
}
fn set(&mut self, value : f64) {
*self = unsafe { mem::transmute(mem::transmute::<f64, u64>(value).to_le()) };
} | } | random_line_split |
|
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::io::{self, Write};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use console::style;
use humantime::format_duration;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use super::{
BeginTaskEvent, ChecksumErrorEvent, DeleteEvent, EndBuildEvent,
EndTaskEvent, Event, EventHandler, Timestamp,
};
#[derive(Clone)]
struct TaskState {
/// Time the task started.
start: Timestamp,
/// Progress bar associated with this task.
pb: ProgressBar,
/// String of the task being executed.
name: String,
/// Buffer of output for the task.
buf: Vec<u8>,
}
impl TaskState {
pub fn new(start: Timestamp, pb: ProgressBar) -> Self {
TaskState {
start,
pb,
name: String::new(),
buf: Vec::new(),
}
}
}
/// Calculates the number of spaces a number takes up. Useful for padding
/// decimal numbers.
fn num_width(mut max_value: usize) -> usize {
let mut count = 0;
while max_value > 0 {
max_value /= 10;
count += 1;
}
count
}
/// "Inner" that lives as long as a single build. This is created and destroyed
/// for `BeginBuildEvent`s and `EndBuildEvent`s respectively.
struct Inner {
// Vector of in-flight tasks.
tasks: Vec<TaskState>,
// Time at which the build started. This is used to calculate the duration
// of the build when it finishes.
start_time: Timestamp,
// Progress bar thread.
pb_thread: JoinHandle<Result<(), io::Error>>,
// Continuously updates each of the progress bars.
tick_thread: JoinHandle<()>,
// Name of the build.
name: String,
}
impl Inner {
pub fn new(threads: usize, name: String, timestamp: Timestamp) -> Self {
// Give a bogus start time. This will be changed as we receive events.
let mut tasks = Vec::with_capacity(threads);
let mut bars = Vec::with_capacity(threads);
let progress = MultiProgress::new();
for i in 0..threads {
let pb = progress.add(ProgressBar::new_spinner());
pb.set_style(Console::style_idle());
pb.set_prefix(&format!(
"[{:>width$}]",
i + 1,
width = num_width(threads)
));
pb.set_message(&style("Idle").dim().to_string());
// Clone the progress bar handle so we can update them later.
bars.push(pb.clone());
tasks.push(TaskState::new(timestamp, pb));
}
let pb_thread = thread::spawn(move || progress.join_and_clear());
let tick_thread = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(200));
for pb in &bars {
if pb.is_finished() {
return;
}
pb.tick();
}
});
Inner {
tasks,
start_time: timestamp,
pb_thread,
tick_thread,
name,
}
}
pub fn | (mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
self.tick_thread.join().unwrap();
self.pb_thread.join().unwrap()?;
Ok(())
}
pub fn end_build(
self,
timestamp: Timestamp,
event: EndBuildEvent,
) -> Result<(), io::Error> {
let duration = (timestamp - self.start_time).to_std().unwrap();
let duration = format_duration(duration);
let msg = match event.result {
Ok(()) => format!(
"{} {} in {}",
style("Finished").bold().green(),
style(&self.name).yellow(),
style(duration).cyan(),
),
Err(err) => format!(
"{} {} after {}: {}",
style("Failed").bold().red(),
style(&self.name).yellow(),
style(duration).cyan(),
err
),
};
for task in &self.tasks {
task.pb.set_style(Console::style_idle());
}
self.tasks[0].pb.println(&msg);
self.finish()
}
pub fn begin_task(
&mut self,
timestamp: Timestamp,
event: BeginTaskEvent,
) -> Result<(), io::Error> {
let mut task = &mut self.tasks[event.id];
task.start = timestamp;
let name = event.task.to_string();
task.pb.reset_elapsed();
task.pb.set_style(Console::style_running());
task.pb.set_message(&name);
task.name = name;
Ok(())
}
pub fn end_task(
&mut self,
timestamp: Timestamp,
event: EndTaskEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
let duration = (timestamp - task.start).to_std().unwrap();
let duration = format_duration(duration);
if let Err(err) = event.result {
writeln!(
&mut task.buf,
"{} after {}: {}",
style("Task failed").bold().red(),
style(duration).cyan(),
style(err).red(),
)?;
task.pb.println(format!(
"> {}\n{}",
style(&task.name).bold().red(),
String::from_utf8_lossy(&task.buf),
));
}
task.buf.clear();
task.pb.set_style(Console::style_idle());
Ok(())
}
pub fn delete(
&mut self,
_timestamp: Timestamp,
event: DeleteEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.set_style(Console::style_running());
task.pb.set_message(&format!("Deleted {}", event.resource));
if let Err(err) = event.result {
task.pb.println(format!(
"{} to delete `{}`: {}",
style("Failed").bold().red(),
style(event.resource).yellow(),
err
));
}
Ok(())
}
pub fn checksum_error(
&mut self,
_timestamp: Timestamp,
event: ChecksumErrorEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.println(format!(
"Failed to compute checksum for {} ({})",
event.resource, event.error
));
Ok(())
}
}
/// Logs events to a console.
#[derive(Default)]
pub struct Console {
// Delay creation of the inner state until we receive our first BeginBuild
// event. This lets us handle any number of threads.
inner: Option<Inner>,
}
impl Console {
fn style_idle() -> ProgressStyle {
ProgressStyle::default_spinner().template("{prefix:.bold.dim} 🚶")
}
fn style_running() -> ProgressStyle {
ProgressStyle::default_spinner().template(&format!(
"{{prefix:.bold.dim}} 🏃 {} {{wide_msg}}",
style("{elapsed}").dim()
))
}
pub fn new() -> Self {
// Delay initialization until we receive a BeginBuild event.
Self::default()
}
}
impl EventHandler for Console {
type Error = io::Error;
fn call(
&mut self,
timestamp: Timestamp,
event: Event,
) -> Result<(), Self::Error> {
match event {
Event::BeginBuild(event) => {
if self.inner.is_none() {
self.inner =
Some(Inner::new(event.threads, event.name, timestamp));
}
}
Event::EndBuild(event) => {
if let Some(inner) = self.inner.take() {
inner.end_build(timestamp, event)?;
}
}
Event::BeginTask(event) => {
if let Some(inner) = &mut self.inner {
inner.begin_task(timestamp, event)?;
}
}
Event::TaskOutput(event) => {
if let Some(inner) = &mut self.inner {
inner.tasks[event.id].buf.extend(event.chunk);
}
}
Event::EndTask(event) => {
if let Some(inner) = &mut self.inner {
inner.end_task(timestamp, event)?;
}
}
Event::Delete(event) => {
if let Some(inner) = &mut self.inner {
inner.delete(timestamp, event)?;
}
}
Event::ChecksumError(event) => {
if let Some(inner) = &mut self.inner {
inner.checksum_error(timestamp, event)?;
}
}
}
Ok(())
}
fn finish(&mut self) -> Result<(), Self::Error> {
if let Some(inner) = self.inner.take() {
inner.finish()?;
}
Ok(())
}
}
| finish | identifier_name |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::io::{self, Write};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use console::style;
use humantime::format_duration;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use super::{
BeginTaskEvent, ChecksumErrorEvent, DeleteEvent, EndBuildEvent,
EndTaskEvent, Event, EventHandler, Timestamp,
};
#[derive(Clone)]
struct TaskState {
/// Time the task started.
start: Timestamp,
/// Progress bar associated with this task.
pb: ProgressBar,
/// String of the task being executed.
name: String,
/// Buffer of output for the task.
buf: Vec<u8>,
}
impl TaskState {
pub fn new(start: Timestamp, pb: ProgressBar) -> Self {
TaskState {
start,
pb,
name: String::new(),
buf: Vec::new(),
}
}
}
/// Calculates the number of spaces a number takes up. Useful for padding
/// decimal numbers.
fn num_width(mut max_value: usize) -> usize {
let mut count = 0;
while max_value > 0 {
max_value /= 10;
count += 1;
}
count
}
/// "Inner" that lives as long as a single build. This is created and destroyed
/// for `BeginBuildEvent`s and `EndBuildEvent`s respectively.
struct Inner {
// Vector of in-flight tasks.
tasks: Vec<TaskState>,
// Time at which the build started. This is used to calculate the duration
// of the build when it finishes.
start_time: Timestamp,
// Progress bar thread.
pb_thread: JoinHandle<Result<(), io::Error>>,
// Continuously updates each of the progress bars.
tick_thread: JoinHandle<()>,
// Name of the build.
name: String,
}
impl Inner {
pub fn new(threads: usize, name: String, timestamp: Timestamp) -> Self {
// Give a bogus start time. This will be changed as we receive events.
let mut tasks = Vec::with_capacity(threads);
let mut bars = Vec::with_capacity(threads);
let progress = MultiProgress::new();
for i in 0..threads {
let pb = progress.add(ProgressBar::new_spinner());
pb.set_style(Console::style_idle());
pb.set_prefix(&format!(
"[{:>width$}]",
i + 1,
width = num_width(threads)
));
pb.set_message(&style("Idle").dim().to_string());
// Clone the progress bar handle so we can update them later.
bars.push(pb.clone());
tasks.push(TaskState::new(timestamp, pb));
}
let pb_thread = thread::spawn(move || progress.join_and_clear());
let tick_thread = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(200));
for pb in &bars {
if pb.is_finished() {
return;
}
pb.tick();
} | start_time: timestamp,
pb_thread,
tick_thread,
name,
}
}
pub fn finish(mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
self.tick_thread.join().unwrap();
self.pb_thread.join().unwrap()?;
Ok(())
}
pub fn end_build(
self,
timestamp: Timestamp,
event: EndBuildEvent,
) -> Result<(), io::Error> {
let duration = (timestamp - self.start_time).to_std().unwrap();
let duration = format_duration(duration);
let msg = match event.result {
Ok(()) => format!(
"{} {} in {}",
style("Finished").bold().green(),
style(&self.name).yellow(),
style(duration).cyan(),
),
Err(err) => format!(
"{} {} after {}: {}",
style("Failed").bold().red(),
style(&self.name).yellow(),
style(duration).cyan(),
err
),
};
for task in &self.tasks {
task.pb.set_style(Console::style_idle());
}
self.tasks[0].pb.println(&msg);
self.finish()
}
pub fn begin_task(
&mut self,
timestamp: Timestamp,
event: BeginTaskEvent,
) -> Result<(), io::Error> {
let mut task = &mut self.tasks[event.id];
task.start = timestamp;
let name = event.task.to_string();
task.pb.reset_elapsed();
task.pb.set_style(Console::style_running());
task.pb.set_message(&name);
task.name = name;
Ok(())
}
pub fn end_task(
&mut self,
timestamp: Timestamp,
event: EndTaskEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
let duration = (timestamp - task.start).to_std().unwrap();
let duration = format_duration(duration);
if let Err(err) = event.result {
writeln!(
&mut task.buf,
"{} after {}: {}",
style("Task failed").bold().red(),
style(duration).cyan(),
style(err).red(),
)?;
task.pb.println(format!(
"> {}\n{}",
style(&task.name).bold().red(),
String::from_utf8_lossy(&task.buf),
));
}
task.buf.clear();
task.pb.set_style(Console::style_idle());
Ok(())
}
pub fn delete(
&mut self,
_timestamp: Timestamp,
event: DeleteEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.set_style(Console::style_running());
task.pb.set_message(&format!("Deleted {}", event.resource));
if let Err(err) = event.result {
task.pb.println(format!(
"{} to delete `{}`: {}",
style("Failed").bold().red(),
style(event.resource).yellow(),
err
));
}
Ok(())
}
pub fn checksum_error(
&mut self,
_timestamp: Timestamp,
event: ChecksumErrorEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.println(format!(
"Failed to compute checksum for {} ({})",
event.resource, event.error
));
Ok(())
}
}
/// Logs events to a console.
#[derive(Default)]
pub struct Console {
// Delay creation of the inner state until we receive our first BeginBuild
// event. This lets us handle any number of threads.
inner: Option<Inner>,
}
impl Console {
fn style_idle() -> ProgressStyle {
ProgressStyle::default_spinner().template("{prefix:.bold.dim} 🚶")
}
fn style_running() -> ProgressStyle {
ProgressStyle::default_spinner().template(&format!(
"{{prefix:.bold.dim}} 🏃 {} {{wide_msg}}",
style("{elapsed}").dim()
))
}
pub fn new() -> Self {
// Delay initialization until we receive a BeginBuild event.
Self::default()
}
}
impl EventHandler for Console {
type Error = io::Error;
fn call(
&mut self,
timestamp: Timestamp,
event: Event,
) -> Result<(), Self::Error> {
match event {
Event::BeginBuild(event) => {
if self.inner.is_none() {
self.inner =
Some(Inner::new(event.threads, event.name, timestamp));
}
}
Event::EndBuild(event) => {
if let Some(inner) = self.inner.take() {
inner.end_build(timestamp, event)?;
}
}
Event::BeginTask(event) => {
if let Some(inner) = &mut self.inner {
inner.begin_task(timestamp, event)?;
}
}
Event::TaskOutput(event) => {
if let Some(inner) = &mut self.inner {
inner.tasks[event.id].buf.extend(event.chunk);
}
}
Event::EndTask(event) => {
if let Some(inner) = &mut self.inner {
inner.end_task(timestamp, event)?;
}
}
Event::Delete(event) => {
if let Some(inner) = &mut self.inner {
inner.delete(timestamp, event)?;
}
}
Event::ChecksumError(event) => {
if let Some(inner) = &mut self.inner {
inner.checksum_error(timestamp, event)?;
}
}
}
Ok(())
}
fn finish(&mut self) -> Result<(), Self::Error> {
if let Some(inner) = self.inner.take() {
inner.finish()?;
}
Ok(())
}
} | });
Inner {
tasks, | random_line_split |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::io::{self, Write};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use console::style;
use humantime::format_duration;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use super::{
BeginTaskEvent, ChecksumErrorEvent, DeleteEvent, EndBuildEvent,
EndTaskEvent, Event, EventHandler, Timestamp,
};
#[derive(Clone)]
struct TaskState {
/// Time the task started.
start: Timestamp,
/// Progress bar associated with this task.
pb: ProgressBar,
/// String of the task being executed.
name: String,
/// Buffer of output for the task.
buf: Vec<u8>,
}
impl TaskState {
pub fn new(start: Timestamp, pb: ProgressBar) -> Self {
TaskState {
start,
pb,
name: String::new(),
buf: Vec::new(),
}
}
}
/// Calculates the number of spaces a number takes up. Useful for padding
/// decimal numbers.
fn num_width(mut max_value: usize) -> usize {
let mut count = 0;
while max_value > 0 {
max_value /= 10;
count += 1;
}
count
}
/// "Inner" that lives as long as a single build. This is created and destroyed
/// for `BeginBuildEvent`s and `EndBuildEvent`s respectively.
struct Inner {
// Vector of in-flight tasks.
tasks: Vec<TaskState>,
// Time at which the build started. This is used to calculate the duration
// of the build when it finishes.
start_time: Timestamp,
// Progress bar thread.
pb_thread: JoinHandle<Result<(), io::Error>>,
// Continuously updates each of the progress bars.
tick_thread: JoinHandle<()>,
// Name of the build.
name: String,
}
impl Inner {
pub fn new(threads: usize, name: String, timestamp: Timestamp) -> Self {
// Give a bogus start time. This will be changed as we receive events.
let mut tasks = Vec::with_capacity(threads);
let mut bars = Vec::with_capacity(threads);
let progress = MultiProgress::new();
for i in 0..threads {
let pb = progress.add(ProgressBar::new_spinner());
pb.set_style(Console::style_idle());
pb.set_prefix(&format!(
"[{:>width$}]",
i + 1,
width = num_width(threads)
));
pb.set_message(&style("Idle").dim().to_string());
// Clone the progress bar handle so we can update them later.
bars.push(pb.clone());
tasks.push(TaskState::new(timestamp, pb));
}
let pb_thread = thread::spawn(move || progress.join_and_clear());
let tick_thread = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(200));
for pb in &bars {
if pb.is_finished() {
return;
}
pb.tick();
}
});
Inner {
tasks,
start_time: timestamp,
pb_thread,
tick_thread,
name,
}
}
pub fn finish(mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
self.tick_thread.join().unwrap();
self.pb_thread.join().unwrap()?;
Ok(())
}
pub fn end_build(
self,
timestamp: Timestamp,
event: EndBuildEvent,
) -> Result<(), io::Error> | for task in &self.tasks {
task.pb.set_style(Console::style_idle());
}
self.tasks[0].pb.println(&msg);
self.finish()
}
pub fn begin_task(
&mut self,
timestamp: Timestamp,
event: BeginTaskEvent,
) -> Result<(), io::Error> {
let mut task = &mut self.tasks[event.id];
task.start = timestamp;
let name = event.task.to_string();
task.pb.reset_elapsed();
task.pb.set_style(Console::style_running());
task.pb.set_message(&name);
task.name = name;
Ok(())
}
pub fn end_task(
&mut self,
timestamp: Timestamp,
event: EndTaskEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
let duration = (timestamp - task.start).to_std().unwrap();
let duration = format_duration(duration);
if let Err(err) = event.result {
writeln!(
&mut task.buf,
"{} after {}: {}",
style("Task failed").bold().red(),
style(duration).cyan(),
style(err).red(),
)?;
task.pb.println(format!(
"> {}\n{}",
style(&task.name).bold().red(),
String::from_utf8_lossy(&task.buf),
));
}
task.buf.clear();
task.pb.set_style(Console::style_idle());
Ok(())
}
pub fn delete(
&mut self,
_timestamp: Timestamp,
event: DeleteEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.set_style(Console::style_running());
task.pb.set_message(&format!("Deleted {}", event.resource));
if let Err(err) = event.result {
task.pb.println(format!(
"{} to delete `{}`: {}",
style("Failed").bold().red(),
style(event.resource).yellow(),
err
));
}
Ok(())
}
pub fn checksum_error(
&mut self,
_timestamp: Timestamp,
event: ChecksumErrorEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.println(format!(
"Failed to compute checksum for {} ({})",
event.resource, event.error
));
Ok(())
}
}
/// Logs events to a console.
#[derive(Default)]
pub struct Console {
// Delay creation of the inner state until we receive our first BeginBuild
// event. This lets us handle any number of threads.
inner: Option<Inner>,
}
impl Console {
fn style_idle() -> ProgressStyle {
ProgressStyle::default_spinner().template("{prefix:.bold.dim} 🚶")
}
fn style_running() -> ProgressStyle {
ProgressStyle::default_spinner().template(&format!(
"{{prefix:.bold.dim}} 🏃 {} {{wide_msg}}",
style("{elapsed}").dim()
))
}
pub fn new() -> Self {
// Delay initialization until we receive a BeginBuild event.
Self::default()
}
}
impl EventHandler for Console {
type Error = io::Error;
fn call(
&mut self,
timestamp: Timestamp,
event: Event,
) -> Result<(), Self::Error> {
match event {
Event::BeginBuild(event) => {
if self.inner.is_none() {
self.inner =
Some(Inner::new(event.threads, event.name, timestamp));
}
}
Event::EndBuild(event) => {
if let Some(inner) = self.inner.take() {
inner.end_build(timestamp, event)?;
}
}
Event::BeginTask(event) => {
if let Some(inner) = &mut self.inner {
inner.begin_task(timestamp, event)?;
}
}
Event::TaskOutput(event) => {
if let Some(inner) = &mut self.inner {
inner.tasks[event.id].buf.extend(event.chunk);
}
}
Event::EndTask(event) => {
if let Some(inner) = &mut self.inner {
inner.end_task(timestamp, event)?;
}
}
Event::Delete(event) => {
if let Some(inner) = &mut self.inner {
inner.delete(timestamp, event)?;
}
}
Event::ChecksumError(event) => {
if let Some(inner) = &mut self.inner {
inner.checksum_error(timestamp, event)?;
}
}
}
Ok(())
}
fn finish(&mut self) -> Result<(), Self::Error> {
if let Some(inner) = self.inner.take() {
inner.finish()?;
}
Ok(())
}
}
| {
let duration = (timestamp - self.start_time).to_std().unwrap();
let duration = format_duration(duration);
let msg = match event.result {
Ok(()) => format!(
"{} {} in {}",
style("Finished").bold().green(),
style(&self.name).yellow(),
style(duration).cyan(),
),
Err(err) => format!(
"{} {} after {}: {}",
style("Failed").bold().red(),
style(&self.name).yellow(),
style(duration).cyan(),
err
),
};
| identifier_body |
console.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::io::{self, Write};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use console::style;
use humantime::format_duration;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use super::{
BeginTaskEvent, ChecksumErrorEvent, DeleteEvent, EndBuildEvent,
EndTaskEvent, Event, EventHandler, Timestamp,
};
#[derive(Clone)]
struct TaskState {
/// Time the task started.
start: Timestamp,
/// Progress bar associated with this task.
pb: ProgressBar,
/// String of the task being executed.
name: String,
/// Buffer of output for the task.
buf: Vec<u8>,
}
impl TaskState {
pub fn new(start: Timestamp, pb: ProgressBar) -> Self {
TaskState {
start,
pb,
name: String::new(),
buf: Vec::new(),
}
}
}
/// Calculates the number of spaces a number takes up. Useful for padding
/// decimal numbers.
fn num_width(mut max_value: usize) -> usize {
let mut count = 0;
while max_value > 0 {
max_value /= 10;
count += 1;
}
count
}
/// "Inner" that lives as long as a single build. This is created and destroyed
/// for `BeginBuildEvent`s and `EndBuildEvent`s respectively.
struct Inner {
// Vector of in-flight tasks.
tasks: Vec<TaskState>,
// Time at which the build started. This is used to calculate the duration
// of the build when it finishes.
start_time: Timestamp,
// Progress bar thread.
pb_thread: JoinHandle<Result<(), io::Error>>,
// Continuously updates each of the progress bars.
tick_thread: JoinHandle<()>,
// Name of the build.
name: String,
}
impl Inner {
pub fn new(threads: usize, name: String, timestamp: Timestamp) -> Self {
// Give a bogus start time. This will be changed as we receive events.
let mut tasks = Vec::with_capacity(threads);
let mut bars = Vec::with_capacity(threads);
let progress = MultiProgress::new();
for i in 0..threads {
let pb = progress.add(ProgressBar::new_spinner());
pb.set_style(Console::style_idle());
pb.set_prefix(&format!(
"[{:>width$}]",
i + 1,
width = num_width(threads)
));
pb.set_message(&style("Idle").dim().to_string());
// Clone the progress bar handle so we can update them later.
bars.push(pb.clone());
tasks.push(TaskState::new(timestamp, pb));
}
let pb_thread = thread::spawn(move || progress.join_and_clear());
let tick_thread = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(200));
for pb in &bars {
if pb.is_finished() {
return;
}
pb.tick();
}
});
Inner {
tasks,
start_time: timestamp,
pb_thread,
tick_thread,
name,
}
}
pub fn finish(mut self) -> Result<(), io::Error> {
for task in self.tasks.iter_mut() {
task.pb
.finish_with_message(&style("Done").dim().to_string());
}
self.tick_thread.join().unwrap();
self.pb_thread.join().unwrap()?;
Ok(())
}
pub fn end_build(
self,
timestamp: Timestamp,
event: EndBuildEvent,
) -> Result<(), io::Error> {
let duration = (timestamp - self.start_time).to_std().unwrap();
let duration = format_duration(duration);
let msg = match event.result {
Ok(()) => format!(
"{} {} in {}",
style("Finished").bold().green(),
style(&self.name).yellow(),
style(duration).cyan(),
),
Err(err) => format!(
"{} {} after {}: {}",
style("Failed").bold().red(),
style(&self.name).yellow(),
style(duration).cyan(),
err
),
};
for task in &self.tasks {
task.pb.set_style(Console::style_idle());
}
self.tasks[0].pb.println(&msg);
self.finish()
}
pub fn begin_task(
&mut self,
timestamp: Timestamp,
event: BeginTaskEvent,
) -> Result<(), io::Error> {
let mut task = &mut self.tasks[event.id];
task.start = timestamp;
let name = event.task.to_string();
task.pb.reset_elapsed();
task.pb.set_style(Console::style_running());
task.pb.set_message(&name);
task.name = name;
Ok(())
}
pub fn end_task(
&mut self,
timestamp: Timestamp,
event: EndTaskEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
let duration = (timestamp - task.start).to_std().unwrap();
let duration = format_duration(duration);
if let Err(err) = event.result {
writeln!(
&mut task.buf,
"{} after {}: {}",
style("Task failed").bold().red(),
style(duration).cyan(),
style(err).red(),
)?;
task.pb.println(format!(
"> {}\n{}",
style(&task.name).bold().red(),
String::from_utf8_lossy(&task.buf),
));
}
task.buf.clear();
task.pb.set_style(Console::style_idle());
Ok(())
}
pub fn delete(
&mut self,
_timestamp: Timestamp,
event: DeleteEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.set_style(Console::style_running());
task.pb.set_message(&format!("Deleted {}", event.resource));
if let Err(err) = event.result {
task.pb.println(format!(
"{} to delete `{}`: {}",
style("Failed").bold().red(),
style(event.resource).yellow(),
err
));
}
Ok(())
}
pub fn checksum_error(
&mut self,
_timestamp: Timestamp,
event: ChecksumErrorEvent,
) -> Result<(), io::Error> {
let task = &mut self.tasks[event.id];
task.pb.println(format!(
"Failed to compute checksum for {} ({})",
event.resource, event.error
));
Ok(())
}
}
/// Logs events to a console.
#[derive(Default)]
pub struct Console {
// Delay creation of the inner state until we receive our first BeginBuild
// event. This lets us handle any number of threads.
inner: Option<Inner>,
}
impl Console {
fn style_idle() -> ProgressStyle {
ProgressStyle::default_spinner().template("{prefix:.bold.dim} 🚶")
}
fn style_running() -> ProgressStyle {
ProgressStyle::default_spinner().template(&format!(
"{{prefix:.bold.dim}} 🏃 {} {{wide_msg}}",
style("{elapsed}").dim()
))
}
pub fn new() -> Self {
// Delay initialization until we receive a BeginBuild event.
Self::default()
}
}
impl EventHandler for Console {
type Error = io::Error;
fn call(
&mut self,
timestamp: Timestamp,
event: Event,
) -> Result<(), Self::Error> {
match event {
Event::BeginBuild(event) => {
if self.inner.is_none() {
self.inner =
Some(Inner::new(event.threads, event.name, timestamp));
}
}
Event::EndBuild(event) => {
if let Some(inner) = self.inner.take() {
inner.end_build(timestamp, event)?;
}
}
Event::BeginTask(event) => {
if let Some(inner) = &mut self.inner {
inner.begin_task(timestamp, event)?;
}
}
Event::TaskOutput(event) => {
if let Some(inner) = &mut self.inner {
| }
Event::EndTask(event) => {
if let Some(inner) = &mut self.inner {
inner.end_task(timestamp, event)?;
}
}
Event::Delete(event) => {
if let Some(inner) = &mut self.inner {
inner.delete(timestamp, event)?;
}
}
Event::ChecksumError(event) => {
if let Some(inner) = &mut self.inner {
inner.checksum_error(timestamp, event)?;
}
}
}
Ok(())
}
fn finish(&mut self) -> Result<(), Self::Error> {
if let Some(inner) = self.inner.take() {
inner.finish()?;
}
Ok(())
}
}
| inner.tasks[event.id].buf.extend(event.chunk);
}
| conditional_block |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T:?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
let v: $T = Default::default();
let size: usize = align_of_val::<$T>(&v);
assert_eq!(size, $size);
})
}
#[test]
fn align_of_val_test1() {
struct A;
let a: A = A;
let size: usize = align_of_val::<A>(&a);
assert_eq!(size, 1);
}
#[test]
fn align_of_val_test2() |
}
| {
align_of_val_test!( (u8), 1 );
align_of_val_test!( (u8, u16), 2 );
align_of_val_test!( (u8, u16, u32), 4 );
align_of_val_test!( (u8, u16, u32, u64), 8 );
} | identifier_body |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T:?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
let v: $T = Default::default();
let size: usize = align_of_val::<$T>(&v);
assert_eq!(size, $size);
})
}
#[test]
fn align_of_val_test1() {
struct A;
let a: A = A;
let size: usize = align_of_val::<A>(&a);
assert_eq!(size, 1);
}
#[test]
fn | () {
align_of_val_test!( (u8), 1 );
align_of_val_test!( (u8, u16), 2 );
align_of_val_test!( (u8, u16, u32), 4 );
align_of_val_test!( (u8, u16, u32, u64), 8 );
}
}
| align_of_val_test2 | identifier_name |
align_of_val.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::mem::align_of_val;
use core::default::Default;
// pub fn align_of_val<T:?Sized>(val: &T) -> usize {
// unsafe { intrinsics::min_align_of_val(val) }
// }
macro_rules! align_of_val_test {
($T:ty, $size:expr) => ({
let v: $T = Default::default();
let size: usize = align_of_val::<$T>(&v);
assert_eq!(size, $size);
})
}
#[test]
fn align_of_val_test1() {
struct A;
let a: A = A;
let size: usize = align_of_val::<A>(&a);
assert_eq!(size, 1);
}
#[test]
fn align_of_val_test2() {
align_of_val_test!( (u8), 1 );
align_of_val_test!( (u8, u16), 2 );
align_of_val_test!( (u8, u16, u32), 4 ); | align_of_val_test!( (u8, u16, u32, u64), 8 );
}
} | random_line_split |
|
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode; | pub use self::packet_identifier::PacketIdentifier;
pub use self::protocol_level::ProtocolLevel;
pub use self::protocol_name::ProtocolName;
pub use self::topic_name::TopicNameHeader;
mod connect_ack_flags;
mod connect_flags;
mod connect_ret_code;
mod keep_alive;
mod packet_identifier;
pub mod protocol_level;
mod protocol_name;
mod topic_name;
/// Errors while decoding variable header
#[derive(Debug, thiserror::Error)]
pub enum VariableHeaderError {
#[error(transparent)]
IoError(#[from] io::Error),
#[error("invalid reserved flags")]
InvalidReservedFlag,
#[error(transparent)]
FromUtf8Error(#[from] FromUtf8Error),
#[error(transparent)]
TopicNameError(#[from] TopicNameError),
#[error("invalid protocol version")]
InvalidProtocolVersion,
}
impl From<TopicNameDecodeError> for VariableHeaderError {
fn from(err: TopicNameDecodeError) -> VariableHeaderError {
match err {
TopicNameDecodeError::IoError(e) => Self::IoError(e),
TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e),
}
}
} | pub use self::keep_alive::KeepAlive; | random_line_split |
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode;
pub use self::keep_alive::KeepAlive;
pub use self::packet_identifier::PacketIdentifier;
pub use self::protocol_level::ProtocolLevel;
pub use self::protocol_name::ProtocolName;
pub use self::topic_name::TopicNameHeader;
mod connect_ack_flags;
mod connect_flags;
mod connect_ret_code;
mod keep_alive;
mod packet_identifier;
pub mod protocol_level;
mod protocol_name;
mod topic_name;
/// Errors while decoding variable header
#[derive(Debug, thiserror::Error)]
pub enum VariableHeaderError {
#[error(transparent)]
IoError(#[from] io::Error),
#[error("invalid reserved flags")]
InvalidReservedFlag,
#[error(transparent)]
FromUtf8Error(#[from] FromUtf8Error),
#[error(transparent)]
TopicNameError(#[from] TopicNameError),
#[error("invalid protocol version")]
InvalidProtocolVersion,
}
impl From<TopicNameDecodeError> for VariableHeaderError {
fn | (err: TopicNameDecodeError) -> VariableHeaderError {
match err {
TopicNameDecodeError::IoError(e) => Self::IoError(e),
TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e),
}
}
}
| from | identifier_name |
mod.rs | //! Variable header in MQTT
use std::io;
use std::string::FromUtf8Error;
use crate::topic_name::{TopicNameDecodeError, TopicNameError};
pub use self::connect_ack_flags::ConnackFlags;
pub use self::connect_flags::ConnectFlags;
pub use self::connect_ret_code::ConnectReturnCode;
pub use self::keep_alive::KeepAlive;
pub use self::packet_identifier::PacketIdentifier;
pub use self::protocol_level::ProtocolLevel;
pub use self::protocol_name::ProtocolName;
pub use self::topic_name::TopicNameHeader;
mod connect_ack_flags;
mod connect_flags;
mod connect_ret_code;
mod keep_alive;
mod packet_identifier;
pub mod protocol_level;
mod protocol_name;
mod topic_name;
/// Errors while decoding variable header
#[derive(Debug, thiserror::Error)]
pub enum VariableHeaderError {
#[error(transparent)]
IoError(#[from] io::Error),
#[error("invalid reserved flags")]
InvalidReservedFlag,
#[error(transparent)]
FromUtf8Error(#[from] FromUtf8Error),
#[error(transparent)]
TopicNameError(#[from] TopicNameError),
#[error("invalid protocol version")]
InvalidProtocolVersion,
}
impl From<TopicNameDecodeError> for VariableHeaderError {
fn from(err: TopicNameDecodeError) -> VariableHeaderError |
}
| {
match err {
TopicNameDecodeError::IoError(e) => Self::IoError(e),
TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e),
}
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
| // track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
} | // log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
| random_line_split |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String |
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => |
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn transform(aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| {" seven"} | conditional_block |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// no-pretty-expanded
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
use std::thread::Thread;
fn print_complements() {
let all = [Blue, Red, Yellow];
for aa in &all {
for bb in &all {
println!("{:?} + {:?} -> {:?}", *aa, *bb, transform(*aa, *bb));
}
}
}
#[derive(Copy)]
enum Color {
Red,
Yellow,
Blue,
}
impl fmt::Debug for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Color>) -> String {
let mut out = String::new();
for col in &set {
out.push(' ');
out.push_str(&format!("{:?}", col));
}
out
}
fn show_digit(nn: uint) -> &'static str {
match nn {
0 => {" zero"}
1 => {" one"}
2 => {" two"}
3 => {" three"}
4 => {" four"}
5 => {" five"}
6 => {" six"}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
_ => {panic!("expected digits from 0 to 9...")}
}
}
struct Number(uint);
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = vec![];
let Number(mut num) = *self;
if num == 0 { out.push(show_digit(0)) };
while num!= 0 {
let dig = num % 10;
num = num / 10;
let s = show_digit(dig);
out.push(s);
}
for s in out.iter().rev() {
try!(write!(f, "{}", s))
}
Ok(())
}
}
fn | (aa: Color, bb: Color) -> Color {
match (aa, bb) {
(Red, Red ) => { Red }
(Red, Yellow) => { Blue }
(Red, Blue ) => { Yellow }
(Yellow, Red ) => { Blue }
(Yellow, Yellow) => { Yellow }
(Yellow, Blue ) => { Red }
(Blue, Red ) => { Yellow }
(Blue, Yellow) => { Red }
(Blue, Blue ) => { Blue }
}
}
fn creature(
name: uint,
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
loop {
// ask for a pairing
to_rendezvous.send(CreatureInfo {name: name, color: color}).unwrap();
// log and change, or quit
match rendezvous.next() {
Some(other_creature) => {
color = transform(color, other_creature.color);
// track some statistics
creatures_met += 1;
if other_creature.name == name {
evil_clones_met += 1;
}
}
None => break
}
}
// log creatures met and evil clones of self
let report = format!("{}{:?}", creatures_met, Number(evil_clones_met));
to_rendezvous_log.send(report).unwrap();
}
fn rendezvous(nn: uint, set: Vec<Color>) {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let to_creature: Vec<Sender<CreatureInfo>> =
set.iter().enumerate().map(|(ii, &col)| {
// create each creature as a listener with a port, and
// give us a channel to talk to each
let to_rendezvous = to_rendezvous.clone();
let to_rendezvous_log = to_rendezvous_log.clone();
let (to_creature, from_rendezvous) = channel();
Thread::spawn(move|| {
creature(ii,
col,
from_rendezvous,
to_rendezvous,
to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatures_met += 2;
to_creature[fst_creature.name].send(snd_creature).unwrap();
to_creature[snd_creature.name].send(fst_creature).unwrap();
}
// tell each creature to stop
drop(to_creature);
// print each color in the set
println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::os::getenv("RUST_BENCH").is_some() {
200000
} else {
std::os::args()
.get(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600u)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue));
}
| transform | identifier_name |
iter.rs | use std::mem;
struct | {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
}
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
// Iterator that generates: 0, 1 and 2
let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
}
| Fibonacci | identifier_name |
iter.rs | use std::mem;
struct Fibonacci {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> |
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() {
// Iterator that generates: 0, 1 and 2
let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
}
| {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
} | identifier_body |
iter.rs | use std::mem;
struct Fibonacci {
curr: uint,
next: uint,
}
// Implement 'Iterator' for 'Fibonacci'
impl Iterator<uint> for Fibonacci {
// The 'Iterator' trait only requires the 'next' method to be defined. The
// return type is 'Option<T>', 'None' is returned when the 'Iterator' is
// over, otherwise the next value is returned wrapped in 'Some'
fn next(&mut self) -> Option<uint> {
let new_next = self.curr + self.next;
let new_curr = mem::replace(&mut self.next, new_next);
// 'Some' is always returned, this is an infinite value generator
Some(mem::replace(&mut self.curr, new_curr))
}
}
// Returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 1, next: 1 }
}
fn main() { | let mut sequence = range(0u, 3);
println!("Four consecutive `next` calls on range(0, 3)")
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
println!("> {}", sequence.next());
// The for construct will iterate an 'Iterator' until it returns 'None'.
// Every 'Some' value is unwrapped and bound to a variable.
println!("Iterate over range(0, 3) using for");
for i in range(0u, 3) {
println!("> {}", i);
}
// The 'take(n)' method will reduce an iterator to its first 'n' terms,
// which is pretty useful for infinite value generators
println!("The first four terms of the Fibonacci sequence are: ");
for i in fibonacci().take(4) {
println!("> {}", i);
}
// The'skip(n)' method will shorten an iterator by dropping its first 'n'
// terms
println!("The next four terms of the Fibonacci sequence are: ");
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u, 3, 3, 7];
// The 'iter' method produces an 'Iterator' over an array/slice
println!("Iterate the following array {}", array.as_slice());
for i in array.iter() {
println!("> {}", i);
}
} | // Iterator that generates: 0, 1 and 2 | random_line_split |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else { | }
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
|
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
| conditional_block |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c", | "htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
} | "cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c", | random_line_split |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn main() { | let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
|
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES { | identifier_body |
build.rs | // Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(feature = "serde")]
use bindgen;
use fs_utils::copy::copy_directory;
use glob::glob;
use std::env;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
// these need to be kept in sync with the htslib Makefile
const FILES: &[&str] = &[
"kfunc.c",
"kstring.c",
"bcf_sr_sort.c",
"bgzf.c",
"errmod.c",
"faidx.c",
"header.c",
"hfile.c",
"hts.c",
"hts_expr.c",
"hts_os.c",
"md5.c",
"multipart.c",
"probaln.c",
"realn.c",
"regidx.c",
"region.c",
"sam.c",
"synced_bcf_reader.c",
"vcf_sweep.c",
"tbx.c",
"textutils.c",
"thread_pool.c",
"vcf.c",
"vcfutils.c",
"cram/cram_codecs.c",
"cram/cram_decode.c",
"cram/cram_encode.c",
"cram/cram_external.c",
"cram/cram_index.c",
"cram/cram_io.c",
"cram/cram_stats.c",
"cram/mFILE.c",
"cram/open_trace_file.c",
"cram/pooled_alloc.c",
"cram/string_alloc.c",
"htscodecs/htscodecs/arith_dynamic.c",
"htscodecs/htscodecs/fqzcomp_qual.c",
"htscodecs/htscodecs/htscodecs.c",
"htscodecs/htscodecs/pack.c",
"htscodecs/htscodecs/rANS_static4x16pr.c",
"htscodecs/htscodecs/rANS_static.c",
"htscodecs/htscodecs/rle.c",
"htscodecs/htscodecs/tokenise_name3.c",
];
fn m | ) {
let out = PathBuf::from(env::var("OUT_DIR").unwrap());
let htslib_copy = out.join("htslib");
if htslib_copy.exists() {
std::fs::remove_dir_all(htslib_copy).unwrap();
}
copy_directory("htslib", &out).unwrap();
// In build.rs cfg(target_os) does not give the target when cross-compiling;
// instead use the environment variable supplied by cargo, which does.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut cfg = cc::Build::new();
let mut lib_list = "".to_string();
// default files
let out_htslib = out.join("htslib");
let htslib = PathBuf::from("htslib");
for f in FILES {
let c_file = out_htslib.join(f);
cfg.file(&c_file);
println!("cargo:rerun-if-changed={}", htslib.join(f).display());
}
cfg.include(out.join("htslib"));
let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok();
if want_static {
cfg.warnings(false).static_flag(true).pic(true);
} else {
cfg.warnings(false).static_flag(false).pic(true);
}
if let Ok(z_inc) = env::var("DEP_Z_INCLUDE") {
cfg.include(z_inc);
lib_list += " -lz";
}
// We build a config.h ourselves, rather than rely on Makefile or./configure
let mut config_lines = vec![
"/* Default config.h generated by build.rs */",
"#define HAVE_DRAND48 1",
];
let use_bzip2 = env::var("CARGO_FEATURE_BZIP2").is_ok();
if use_bzip2 {
if let Ok(inc) = env::var("DEP_BZIP2_ROOT")
.map(PathBuf::from)
.map(|path| path.join("include"))
{
cfg.include(inc);
lib_list += " -lbz2";
config_lines.push("#define HAVE_LIBBZ2 1");
}
}
let use_libdeflate = env::var("CARGO_FEATURE_LIBDEFLATE").is_ok();
if use_libdeflate {
if let Ok(inc) = env::var("DEP_LIBDEFLATE_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -ldeflate";
config_lines.push("#define HAVE_LIBDEFLATE 1");
} else {
panic!("no DEP_LIBDEFLATE_INCLUDE");
}
}
let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok();
if use_lzma {
if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -llzma";
config_lines.push("#define HAVE_LIBBZ2 1");
config_lines.push("#ifndef __APPLE__");
config_lines.push("#define HAVE_LZMA_H 1");
config_lines.push("#endif");
}
}
let use_curl = env::var("CARGO_FEATURE_CURL").is_ok();
if use_curl {
if let Ok(inc) = env::var("DEP_CURL_INCLUDE").map(PathBuf::from) {
cfg.include(inc);
lib_list += " -lcurl";
config_lines.push("#define HAVE_LIBCURL 1");
cfg.file("htslib/hfile_libcurl.c");
println!("cargo:rerun-if-changed=htslib/hfile_libcurl.c");
if target_os == "macos" {
// Use builtin MacOS CommonCrypto HMAC
config_lines.push("#define HAVE_COMMONCRYPTO 1");
} else if let Ok(inc) = env::var("DEP_OPENSSL_INCLUDE").map(PathBuf::from) {
// Must use hmac from libcrypto in openssl
cfg.include(inc);
config_lines.push("#define HAVE_HMAC 1");
} else {
panic!("No OpenSSL dependency -- need OpenSSL includes");
}
}
}
let use_gcs = env::var("CARGO_FEATURE_GCS").is_ok();
if use_gcs {
config_lines.push("#define ENABLE_GCS 1");
cfg.file("htslib/hfile_gcs.c");
println!("cargo:rerun-if-changed=htslib/hfile_gcs.c");
}
let use_s3 = env::var("CARGO_FEATURE_S3").is_ok();
if use_s3 {
config_lines.push("#define ENABLE_S3 1");
cfg.file("htslib/hfile_s3.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3.c");
cfg.file("htslib/hfile_s3_write.c");
println!("cargo:rerun-if-changed=htslib/hfile_s3_write.c");
}
// write out config.h which controls the options htslib will use
{
let mut f = std::fs::File::create(out.join("htslib").join("config.h")).unwrap();
for l in config_lines {
writeln!(&mut f, "{}", l).unwrap();
}
}
// write out version.h
{
let version = std::process::Command::new(out.join("htslib").join("version.sh"))
.output()
.expect("failed to execute process");
let version_str = std::str::from_utf8(&version.stdout).unwrap().trim();
let mut f = std::fs::File::create(out.join("htslib").join("version.h")).unwrap();
writeln!(&mut f, "#define HTS_VERSION_TEXT \"{}\"", version_str).unwrap();
}
// write out htscodecs/htscodecs/version.h
{
let mut f = std::fs::File::create(
out.join("htslib")
.join("htscodecs")
.join("htscodecs")
.join("version.h"),
)
.unwrap();
// FIXME, using a dummy. Not sure why this should be a separate version from htslib itself.
writeln!(&mut f, "#define HTSCODECS_VERSION_TEXT \"rust-htslib\"").unwrap();
}
// write out config_vars.h which is used to expose compiler parameters via
// hts_test_feature() in hts.c. We partially fill in these values.
{
let tool = cfg.get_compiler();
let mut f = std::fs::File::create(out.join("htslib").join("config_vars.h")).unwrap();
writeln!(&mut f, "#define HTS_CC {:?}", tool.cc_env()).unwrap();
writeln!(&mut f, "#define HTS_CPPFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_CFLAGS {:?}", tool.cflags_env()).unwrap();
writeln!(&mut f, "#define HTS_LDFLAGS \"\"").unwrap();
writeln!(&mut f, "#define HTS_LIBS \"{}\"", lib_list).unwrap();
}
cfg.file("wrapper.c");
cfg.compile("hts");
// If bindgen is enabled, use it
#[cfg(feature = "bindgen")]
{
bindgen::Builder::default()
.header("wrapper.h")
.generate_comments(false)
.blacklist_function("strtold")
.blacklist_type("max_align_t")
.generate()
.expect("Unable to generate bindings.")
.write_to_file(out.join("bindings.rs"))
.expect("Could not write bindings.");
}
// If no bindgen, use pre-built bindings
#[cfg(not(feature = "bindgen"))]
if target_os == "macos" {
fs::copy("osx_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=osx_prebuilt_bindings.rs");
} else {
fs::copy("linux_prebuilt_bindings.rs", out.join("bindings.rs"))
.expect("couldn't copy prebuilt bindings");
println!("cargo:rerun-if-changed=linux_prebuilt_bindings.rs");
}
let include = out.join("include");
fs::create_dir_all(&include).unwrap();
if include.join("htslib").exists() {
fs::remove_dir_all(include.join("htslib")).expect("remove exist include dir");
}
copy_directory(out.join("htslib").join("htslib"), &include).unwrap();
println!("cargo:root={}", out.display());
println!("cargo:include={}", include.display());
println!("cargo:libdir={}", out.display());
println!("cargo:rerun-if-changed=wrapper.c");
println!("cargo:rerun-if-changed=wrapper.h");
let globs = std::iter::empty()
.chain(glob("htslib/*.[h]").unwrap())
.chain(glob("htslib/cram/*.[h]").unwrap())
.chain(glob("htslib/htslib/*.h").unwrap())
.chain(glob("htslib/os/*.[h]").unwrap())
.filter_map(Result::ok);
for htsfile in globs {
println!("cargo:rerun-if-changed={}", htsfile.display());
}
// Note: config.h is a function of the cargo features. Any feature change will
// cause build.rs to re-run, so don't re-run on that change.
//println!("cargo:rerun-if-changed=htslib/config.h");
}
| ain( | identifier_name |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト!/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
b.iter(|| quote_plus("/a/テスト!/", &[b'/']));
}
#[bench]
fn bench_unquot | cher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(),
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
});
}
| e(b: &mut Ben | identifier_name |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト!/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
b.iter(|| quote_plus("/a/テスト!/", &[b'/']));
}
#[bench]
fn bench_unquote(b: &mut Bencher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(), | } | query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
}); | random_line_split |
lib.rs | /* Copyright (C) 2015 Yutaka Kamei */
#![feature(test)]
extern crate urlparse;
extern crate test;
use urlparse::*;
use test::Bencher;
#[bench]
fn bench_quote(b: &mut Bencher) {
b.iter(|| quote("/a/テスト!/", &[b'/']));
}
#[bench]
fn bench_quote_plus(b: &mut Bencher) {
| fn bench_unquote(b: &mut Bencher) {
b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_unquote_plus(b: &mut Bencher) {
b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/"));
}
#[bench]
fn bench_parse_qs(b: &mut Bencher) {
b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%E3%83%88&e=utf-8"));
}
#[bench]
fn bench_urlparse(b: &mut Bencher) {
b.iter(|| urlparse("http://Example.com:8080/foo?filter=%28%21%28cn%3Dbar%29%29"));
}
#[bench]
fn bench_urlunparse(b: &mut Bencher) {
b.iter(|| {
let url = Url::new();
let url = Url{
scheme: "http".to_string(),
netloc: "www.example.com".to_string(),
path: "/foo".to_string(),
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()),
.. url};
urlunparse(url)
});
}
| b.iter(|| quote_plus("/a/テスト !/", &[b'/']));
}
#[bench]
| identifier_body |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using =!handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() | y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
}
| {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x, | identifier_body |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using =!handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn | () {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
}
| capture_gl_frame | identifier_name |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently
// modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
let using =!handle.is_null();
if using |
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
}
| {
dlclose(handle);
} | conditional_block |
linux_gl_hooks.rs | #![cfg(target_os = "linux")]
#[link(name = "dl")]
extern "C" {}
use crate::gl;
use const_cstr::const_cstr;
use lazy_static::lazy_static;
use libc::{c_char, c_int, c_ulong, c_void};
use libc_print::libc_println;
use log::*;
use std::ffi::CString;
use std::sync::Once;
use std::time::SystemTime;
///////////////////////////////////////////
// libdl definition & link instructions
///////////////////////////////////////////
#[allow(unused)]
pub const RTLD_LAZY: c_int = 0x00001;
#[allow(unused)]
pub const RTLD_NOW: c_int = 0x00002;
#[allow(unused)]
pub const RTLD_NOLOAD: c_int = 0x0004;
#[allow(unused)]
pub const RTLD_DEFAULT: *const c_void = 0x00000 as *const c_void;
#[allow(unused)]
pub const RTLD_NEXT: *const c_void = (-1 as isize) as *const c_void;
extern "C" {
pub fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
pub fn dlclose(handle: *const c_void);
}
///////////////////////////////////////////
// lazily-opened libGL handle
///////////////////////////////////////////
struct LibHandle {
addr: *const c_void,
}
unsafe impl std::marker::Sync for LibHandle {}
lazy_static! {
static ref libGLHandle: LibHandle = {
use const_cstr::*;
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_LAZY);
if handle.is_null() {
panic!("could not dlopen libGL.so.1")
}
LibHandle { addr: handle }
};
}
///////////////////////////////////////////
// glXGetProcAddressARB wrapper
///////////////////////////////////////////
lazy_static! {
static ref glXGetProcAddressARB: unsafe extern "C" fn(name: *const c_char) -> *const c_void = unsafe {
let addr = dlsym(
libGLHandle.addr,
const_cstr!("glXGetProcAddressARB").as_ptr(),
);
if addr.is_null() {
panic!("libGL.so.1 does not contain glXGetProcAddressARB")
}
std::mem::transmute(addr)
};
}
unsafe fn get_glx_proc_address(rustName: &str) -> *const () {
let name = CString::new(rustName).unwrap();
let addr = glXGetProcAddressARB(name.as_ptr());
info!("glXGetProcAddressARB({}) = {:x}", rustName, addr as isize);
addr as *const ()
}
lazy_static! {
static ref startTime: SystemTime = SystemTime::now();
}
///////////////////////////////////////////
// dlopen hook
///////////////////////////////////////////
hook_ld! {
"dl" => fn dlopen(filename: *const c_char, flags: c_int) -> *const c_void {
let res = dlopen::next(filename, flags);
hook_if_needed();
res
}
}
///////////////////////////////////////////
// glXSwapBuffers hook
///////////////////////////////////////////
hook_dynamic! {
get_glx_proc_address => {
fn glXSwapBuffers(display: *const c_void, drawable: c_ulong) -> () {
if super::SETTINGS.in_test && display == 0xDEADBEEF as *const c_void {
libc_println!("caught dead beef");
std::process::exit(0);
}
info!(
"[{:08}] swapping buffers! (display=0x{:X}, drawable=0x{:X})",
startTime.elapsed().unwrap().as_millis(),
display as isize,
drawable as isize
);
capture_gl_frame();
glXSwapBuffers::next(display, drawable)
}
fn glXQueryVersion(display: *const c_void, major: *mut c_int, minor: *mut c_int) -> c_int {
// useless hook, just here to demonstrate we can do multiple hooks if needed
let ret = glXQueryVersion::next(display, major, minor);
if ret == 1 {
info!("GLX server version {}.{}", *major, *minor);
}
ret
}
}
}
/// Returns true if libGL.so.1 was loaded in this process,
/// either by ld-linux on startup (if linked with -lGL),
/// or by dlopen() afterwards.
unsafe fn is_using_opengl() -> bool {
// RTLD_NOLOAD lets us check if a library is already loaded.
// FIXME: we actually do need to call dlclose here, apparently | let using =!handle.is_null();
if using {
dlclose(handle);
}
using
}
static HOOK_SWAPBUFFERS_ONCE: Once = Once::new();
/// If libGL.so.1 was loaded, and only once in the lifetime
/// of this process, hook libGL functions for libcapsule usage.
unsafe fn hook_if_needed() {
if is_using_opengl() {
HOOK_SWAPBUFFERS_ONCE.call_once(|| {
info!("libGL usage detected, hooking OpenGL");
glXSwapBuffers::enable_hook();
glXQueryVersion::enable_hook();
})
}
}
pub fn initialize() {
unsafe { hook_if_needed() }
}
lazy_static! {
static ref frame_buffer: Vec<u8> = {
let num_bytes = (1920 * 1080 * 4) as usize;
let mut data = Vec::<u8>::with_capacity(num_bytes);
data.resize(num_bytes, 0);
data
};
}
static mut frame_index: i64 = 0;
unsafe fn capture_gl_frame() {
let cc = gl::get_capture_context(get_glx_proc_address);
cc.capture_frame();
let x: gl::GLint = 0;
let y: gl::GLint = 0;
let width: gl::GLsizei = 400;
let height: gl::GLsizei = 400;
let bytes_per_pixel: usize = 4;
let bytes_per_frame: usize = width as usize * height as usize * bytes_per_pixel;
let mut viewport = Vec::<gl::GLint>::with_capacity(4);
viewport.resize(4, 0);
cc.funcs
.glGetIntegerv(gl::GL_VIEWPORT, std::mem::transmute(viewport.as_ptr()));
info!("viewport: {:?}", viewport);
cc.funcs.glReadPixels(
x,
y,
width,
height,
gl::GL_RGBA,
gl::GL_UNSIGNED_BYTE,
std::mem::transmute(frame_buffer.as_ptr()),
);
let mut num_black = 0;
for y in 0..height {
for x in 0..width {
let i = (y * width + x) as usize;
let (r, g, b) = (
frame_buffer[i * 4],
frame_buffer[i * 4 + 1],
frame_buffer[i * 4 + 2],
);
if r == 0 && g == 0 && b == 0 {
num_black += 1;
}
}
}
info!("[frame {}] {} black pixels", frame_index, num_black);
frame_index += 1;
if frame_index < 200 {
use std::fs::File;
use std::io::prelude::*;
let name = format!("frame-{}x{}-{}.raw", width, height, frame_index);
let mut file = File::create(&name).unwrap();
file.write_all(&frame_buffer.as_slice()[..bytes_per_frame])
.unwrap();
info!("{} written", name)
}
} | // modules are reference-counted.
let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY); | random_line_split |
pseudo_element.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/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool |
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() &&!self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() &&!self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| {
if !self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
} | identifier_body |
pseudo_element.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/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if!self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed | pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() &&!self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn skip_item_based_display_fixup(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() &&!self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
} | /// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`. | random_line_split |
pseudo_element.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/. */
//! Gecko's definition of a pseudo-element.
//!
//! Note that a few autogenerated bits of this live in
//! `pseudo_element_definition.mako.rs`. If you touch that file, you probably
//! need to update the checked-in files for Servo.
use cssparser::{ToCss, serialize_identifier};
use gecko_bindings::structs::{self, CSSPseudoElementType};
use properties::{ComputedValues, PropertyFlags};
use properties::longhands::display::computed_value as display;
use selector_parser::{NonTSPseudoClass, PseudoElementCascadeType, SelectorImpl};
use std::fmt;
use string_cache::Atom;
include!(concat!(env!("OUT_DIR"), "/gecko/pseudo_element_definition.rs"));
impl ::selectors::parser::PseudoElement for PseudoElement {
type Impl = SelectorImpl;
fn supports_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
if!self.supports_user_action_state() {
return false;
}
return pseudo_class.is_safe_user_action_state();
}
}
impl PseudoElement {
/// Returns the kind of cascade type that a given pseudo is going to use.
///
/// In Gecko we only compute ::before and ::after eagerly. We save the rules
/// for anonymous boxes separately, so we resolve them as precomputed
/// pseudos.
///
/// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
pub fn cascade_type(&self) -> PseudoElementCascadeType {
if self.is_eager() {
debug_assert!(!self.is_anon_box());
return PseudoElementCascadeType::Eager
}
if self.is_precomputed() {
return PseudoElementCascadeType::Precomputed
}
PseudoElementCascadeType::Lazy
}
/// Whether the pseudo-element should inherit from the default computed
/// values instead of from the parent element.
///
/// This is not the common thing, but there are some pseudos (namely:
/// ::backdrop), that shouldn't inherit from the parent element.
pub fn inherits_from_default_values(&self) -> bool {
matches!(*self, PseudoElement::Backdrop)
}
/// Gets the canonical index of this eagerly-cascaded pseudo-element.
#[inline]
pub fn eager_index(&self) -> usize {
EAGER_PSEUDOS.iter().position(|p| p == self)
.expect("Not an eager pseudo")
}
/// Creates a pseudo-element from an eager index.
#[inline]
pub fn from_eager_index(i: usize) -> Self {
EAGER_PSEUDOS[i].clone()
}
/// Whether the current pseudo element is ::before or ::after.
#[inline]
pub fn is_before_or_after(&self) -> bool {
self.is_before() || self.is_after()
}
/// Whether this pseudo-element is the ::before pseudo.
#[inline]
pub fn is_before(&self) -> bool {
*self == PseudoElement::Before
}
/// Whether this pseudo-element is the ::after pseudo.
#[inline]
pub fn is_after(&self) -> bool {
*self == PseudoElement::After
}
/// Whether this pseudo-element is ::first-letter.
#[inline]
pub fn is_first_letter(&self) -> bool {
*self == PseudoElement::FirstLetter
}
/// Whether this pseudo-element is ::first-line.
#[inline]
pub fn is_first_line(&self) -> bool {
*self == PseudoElement::FirstLine
}
/// Whether this pseudo-element is ::-moz-fieldset-content.
#[inline]
pub fn is_fieldset_content(&self) -> bool {
*self == PseudoElement::FieldsetContent
}
/// Whether this pseudo-element is lazily-cascaded.
#[inline]
pub fn is_lazy(&self) -> bool {
!self.is_eager() &&!self.is_precomputed()
}
/// Whether this pseudo-element is web-exposed.
pub fn exposed_in_non_ua_sheets(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_UA_SHEET_ONLY) == 0
}
/// Whether this pseudo-element supports user action selectors.
pub fn supports_user_action_state(&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_SUPPORTS_USER_ACTION_STATE)!= 0
}
/// Whether this pseudo-element skips flex/grid container display-based
/// fixup.
#[inline]
pub fn | (&self) -> bool {
(self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0
}
/// Whether this pseudo-element is precomputed.
#[inline]
pub fn is_precomputed(&self) -> bool {
self.is_anon_box() &&!self.is_tree_pseudo_element()
}
/// Covert non-canonical pseudo-element to canonical one, and keep a
/// canonical one as it is.
pub fn canonical(&self) -> PseudoElement {
match *self {
PseudoElement::MozPlaceholder => PseudoElement::Placeholder,
_ => self.clone(),
}
}
/// Property flag that properties must have to apply to this pseudo-element.
#[inline]
pub fn property_restriction(&self) -> Option<PropertyFlags> {
match *self {
PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER),
PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE),
PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER),
_ => None,
}
}
/// Whether this pseudo-element should actually exist if it has
/// the given styles.
pub fn should_exist(&self, style: &ComputedValues) -> bool
{
let display = style.get_box().clone_display();
if display == display::T::none {
return false;
}
if self.is_before_or_after() && style.ineffective_content_property() {
return false;
}
true
}
}
| skip_item_based_display_fixup | identifier_name |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn get_a(&self) -> &String {
&self.a
}
}
impl UseString for Demo {}
impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() |
}
fn main() {}
| {
let d = Demo { a: "test".to_string() };
d.use_string();
} | identifier_body |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn get_a(&self) -> &String {
&self.a
}
}
| impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() {
let d = Demo { a: "test".to_string() };
d.use_string();
}
}
fn main() {} | impl UseString for Demo {} | random_line_split |
constrain-trait.rs | // run-rustfix
// check-only
#[derive(Debug)]
struct Demo {
a: String
}
trait GetString {
fn get_a(&self) -> &String;
}
trait UseString: std::fmt::Debug {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
trait UseString2 {
fn use_string(&self) {
println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found
}
}
impl GetString for Demo {
fn | (&self) -> &String {
&self.a
}
}
impl UseString for Demo {}
impl UseString2 for Demo {}
#[cfg(test)]
mod tests {
use crate::{Demo, UseString};
#[test]
fn it_works() {
let d = Demo { a: "test".to_string() };
d.use_string();
}
}
fn main() {}
| get_a | identifier_name |
block_header.rs | use Encode;
use VarInt;
#[derive(Debug, Encode, PartialEq)]
/// 4 version int32_t Block version information (note, this is signed)
/// 32 prev_block char[32] The hash value of the previous block this particular block references
/// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of all transactions related to this block
/// 4 timestamp uint32_t A timestamp recording when this block was created (Will overflow in 2106[2])
/// 4 bits uint32_t The calculated difficulty target being used for this block
/// 4 nonce uint32_t The nonce used to generate this block… to allow variations of the header and compute different hashes
/// 1 txn_count var_int Number of transaction entries, this value is always 0
pub struct Bl |
pub version: i32,
pub prev_block: [u8; 32],
pub merkle_root: [u8; 32],
pub timestamp: u32,
pub bits: u32,
pub nonce: u32,
/// txn_count is a var_int on the wire
pub txn_count: VarInt,
}
| ockHeader { | identifier_name |
block_header.rs | use Encode;
use VarInt;
#[derive(Debug, Encode, PartialEq)]
/// 4 version int32_t Block version information (note, this is signed)
/// 32 prev_block char[32] The hash value of the previous block this particular block references
/// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of all transactions related to this block
/// 4 timestamp uint32_t A timestamp recording when this block was created (Will overflow in 2106[2])
/// 4 bits uint32_t The calculated difficulty target being used for this block
/// 4 nonce uint32_t The nonce used to generate this block… to allow variations of the header and compute different hashes
/// 1 txn_count var_int Number of transaction entries, this value is always 0
pub struct BlockHeader {
pub version: i32,
pub prev_block: [u8; 32],
pub merkle_root: [u8; 32],
pub timestamp: u32,
pub bits: u32,
pub nonce: u32,
/// txn_count is a var_int on the wire | } | pub txn_count: VarInt, | random_line_split |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.clone());
GeXY::new(model, x, y);
}
}
/// X = Y + C
pub struct EqXYC;
impl EqXYC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
// TODO merge or at least intersect domains
LeXYC::new(model.clone(), x.clone(), y.clone(), c);
GeXYC::new(model, x, y, c);
}
}
/// X = C
pub struct EqXC;
impl EqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
// TODO merge
LeXC::new(model.clone(), x.clone(), c);
GeXC::new(model, x, c);
}
}
/// X!= Y
pub struct NeqXY;
impl NeqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
NeqXYCxy::new(model, x, y, 0);
}
}
/// X!= Y + C
pub struct NeqXYC;
impl NeqXYC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
NeqXYCxy::new(model, x, y, c);
}
}
/// X!= C
pub struct NeqXC;
#[allow(unused_variable)]
impl NeqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
x.remove(c);
}
}
struct NeqXYCxy : Prop {
c: int
}
impl NeqXYCxy {
fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) |
fn x(&self) -> Rc<FDVar> {
self.vars.get(0).clone()
}
fn y(&self) -> Rc<FDVar> {
self.vars.get(1).clone()
}
}
impl Propagator for NeqXYCxy {
fn id(&self) -> uint {
self.id
}
fn model(&self) -> Weak<Mod> {
self.model.clone()
}
fn events(&self) -> Vec<(uint, Event)> {
vec![(self.y().id, Ins), (self.x().id, Ins)]
}
fn propagate(&self) -> Vec<uint> {
if self.x().is_instanciated() {
self.unregister();
self.y().remove(self.x().min() - self.c)
}
else if self.y().is_instanciated() {
self.unregister();
self.x().remove(self.y().min() + self.c)
} else {
vec![]
}
}
}
#[cfg(test)]
mod tests;
| {
let id = model.propagators.borrow().len();
let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c};
let p = Rc::new((box this) as Box<Propagator>);
model.add_prop(p);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.