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
promote.rs
use crate::{api_client, common::ui::{Status, UIReader, UIWriter, UI}, error::{Error, Result}, hcore::{package::PackageIdent, ChannelIdent}, PRODUCT, VERSION}; use reqwest::StatusCode; use std::str::FromStr; fn is_ident(s: &str) -> bool { PackageIdent::from_str(s).is_ok() } fn in_origin(ident: &str, origin: Option<&str>) -> bool {
pub fn get_ident_list(ui: &mut UI, group_status: &api_client::SchedulerResponse, origin: Option<&str>, interactive: bool) -> Result<Vec<String>> { let mut idents: Vec<String> = group_status.projects .iter() .cloned() .filter(|p| p.state == "Success" && in_origin(&p.ident, origin)) .map(|p| p.ident) .collect(); if idents.is_empty() ||!interactive { return Ok(idents); } let prelude = "# This is the list of package identifiers that will be processed.\n# You may \ edit this file and remove any packages that you do\n# not want to apply to the \ specified channel.\n" .to_string(); idents.insert(0, prelude); idents = idents.iter().map(|s| format!("{}\n", s)).collect(); Ok(ui.edit(&idents)? .split('\n') .filter(|s| is_ident(s)) .map(str::to_string) .collect()) } async fn get_group_status(bldr_url: &str, group_id: u64) -> Result<api_client::SchedulerResponse> { let api_client = api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?; let group_status = api_client.get_schedule(group_id as i64, true) .await .map_err(Error::ScheduleStatus)?; Ok(group_status) } #[allow(clippy::too_many_arguments)] pub async fn start(ui: &mut UI, bldr_url: &str, group_id: &str, channel: &ChannelIdent, origin: Option<&str>, interactive: bool, verbose: bool, token: &str, promote: bool) -> Result<()> { let api_client = api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?; let (promoted_demoted, promoting_demoting, to_from, changing_status, changed_status) = if promote { ("promoted", "Promoting", "to", Status::Promoting, Status::Promoted) } else { ("demoted", "Demoting", "from", Status::Demoting, Status::Demoted) }; let gid = match group_id.parse::<u64>() { Ok(g) => g, Err(e) => { ui.fatal(format!("Failed to parse group id: {}", e))?; return Err(Error::ParseIntError(e)); } }; let group_status = get_group_status(bldr_url, gid).await?; let idents = get_ident_list(ui, &group_status, origin, interactive)?; if idents.is_empty() { ui.warn("No matching packages found")?; return Ok(()); } if verbose { println!("Packages being {}:", promoted_demoted); for ident in idents.iter() { println!(" {}", ident) } } let question = format!("{} {} package(s) {} channel '{}'. Continue?", promoting_demoting, idents.len(), to_from, channel); if!ui.prompt_yes_no(&question, Some(true))? { ui.fatal("Aborted")?; return Ok(()); } ui.status(changing_status, format!("job group {} {} channel '{}'", group_id, to_from, channel))?; match api_client.job_group_promote_or_demote(gid, &idents, channel, token, promote) .await { Ok(_) => { ui.status(changed_status, format!("job group {} {} channel '{}'", group_id, to_from, channel))?; } Err(api_client::Error::APIError(StatusCode::UNPROCESSABLE_ENTITY, _)) => { return Err(Error::JobGroupPromoteOrDemoteUnprocessable(promote)); } Err(e) => { return Err(Error::JobGroupPromoteOrDemote(e, promote)); } }; Ok(()) } #[cfg(test)] mod test { use super::get_ident_list; use crate::{api_client::{Project, SchedulerResponse}, common::ui::UI}; fn sample_project_list() -> Vec<Project> { let project1 = Project { name: "Project1".to_string(), ident: "core/project1/1.0.0/20180101000000".to_string(), state: "Success".to_string(), job_id: "12345678".to_string(), target: "x86_64-linux".to_string(), }; let project2 = Project { name: "Project2".to_string(), ident: "core/project2/1.0.0/20180101000000".to_string(), state: "Success".to_string(), job_id: "12345678".to_string(), target: "x86_64-linux".to_string(), }; vec![project1, project2] } #[test] fn test_get_ident_list() { let mut ui = UI::with_sinks(); let group_status = SchedulerResponse { id: "12345678".to_string(), state: "Finished".to_string(), projects: sample_project_list(), created_at: "Properly formated timestamp".to_string(), project_name: "Test Project".to_string(), target: "x86_64-linux".to_string(), }; let ident_list = get_ident_list(&mut ui, &group_status, Some("core"), false).expect("Error fetching \ ident list"); assert_eq!(ident_list, ["core/project1/1.0.0/20180101000000", "core/project2/1.0.0/20180101000000",]) } }
origin.map_or(true, |o| PackageIdent::from_str(ident).unwrap().origin == o) }
random_line_split
promote.rs
use crate::{api_client, common::ui::{Status, UIReader, UIWriter, UI}, error::{Error, Result}, hcore::{package::PackageIdent, ChannelIdent}, PRODUCT, VERSION}; use reqwest::StatusCode; use std::str::FromStr; fn is_ident(s: &str) -> bool { PackageIdent::from_str(s).is_ok() } fn in_origin(ident: &str, origin: Option<&str>) -> bool { origin.map_or(true, |o| PackageIdent::from_str(ident).unwrap().origin == o) } pub fn
(ui: &mut UI, group_status: &api_client::SchedulerResponse, origin: Option<&str>, interactive: bool) -> Result<Vec<String>> { let mut idents: Vec<String> = group_status.projects .iter() .cloned() .filter(|p| p.state == "Success" && in_origin(&p.ident, origin)) .map(|p| p.ident) .collect(); if idents.is_empty() ||!interactive { return Ok(idents); } let prelude = "# This is the list of package identifiers that will be processed.\n# You may \ edit this file and remove any packages that you do\n# not want to apply to the \ specified channel.\n" .to_string(); idents.insert(0, prelude); idents = idents.iter().map(|s| format!("{}\n", s)).collect(); Ok(ui.edit(&idents)? .split('\n') .filter(|s| is_ident(s)) .map(str::to_string) .collect()) } async fn get_group_status(bldr_url: &str, group_id: u64) -> Result<api_client::SchedulerResponse> { let api_client = api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?; let group_status = api_client.get_schedule(group_id as i64, true) .await .map_err(Error::ScheduleStatus)?; Ok(group_status) } #[allow(clippy::too_many_arguments)] pub async fn start(ui: &mut UI, bldr_url: &str, group_id: &str, channel: &ChannelIdent, origin: Option<&str>, interactive: bool, verbose: bool, token: &str, promote: bool) -> Result<()> { let api_client = api_client::Client::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::APIClient)?; let (promoted_demoted, promoting_demoting, to_from, changing_status, changed_status) = if promote { ("promoted", "Promoting", "to", Status::Promoting, Status::Promoted) } else { ("demoted", "Demoting", "from", Status::Demoting, Status::Demoted) }; let gid = match group_id.parse::<u64>() { Ok(g) => g, Err(e) => { ui.fatal(format!("Failed to parse group id: {}", e))?; return Err(Error::ParseIntError(e)); } }; let group_status = get_group_status(bldr_url, gid).await?; let idents = get_ident_list(ui, &group_status, origin, interactive)?; if idents.is_empty() { ui.warn("No matching packages found")?; return Ok(()); } if verbose { println!("Packages being {}:", promoted_demoted); for ident in idents.iter() { println!(" {}", ident) } } let question = format!("{} {} package(s) {} channel '{}'. Continue?", promoting_demoting, idents.len(), to_from, channel); if!ui.prompt_yes_no(&question, Some(true))? { ui.fatal("Aborted")?; return Ok(()); } ui.status(changing_status, format!("job group {} {} channel '{}'", group_id, to_from, channel))?; match api_client.job_group_promote_or_demote(gid, &idents, channel, token, promote) .await { Ok(_) => { ui.status(changed_status, format!("job group {} {} channel '{}'", group_id, to_from, channel))?; } Err(api_client::Error::APIError(StatusCode::UNPROCESSABLE_ENTITY, _)) => { return Err(Error::JobGroupPromoteOrDemoteUnprocessable(promote)); } Err(e) => { return Err(Error::JobGroupPromoteOrDemote(e, promote)); } }; Ok(()) } #[cfg(test)] mod test { use super::get_ident_list; use crate::{api_client::{Project, SchedulerResponse}, common::ui::UI}; fn sample_project_list() -> Vec<Project> { let project1 = Project { name: "Project1".to_string(), ident: "core/project1/1.0.0/20180101000000".to_string(), state: "Success".to_string(), job_id: "12345678".to_string(), target: "x86_64-linux".to_string(), }; let project2 = Project { name: "Project2".to_string(), ident: "core/project2/1.0.0/20180101000000".to_string(), state: "Success".to_string(), job_id: "12345678".to_string(), target: "x86_64-linux".to_string(), }; vec![project1, project2] } #[test] fn test_get_ident_list() { let mut ui = UI::with_sinks(); let group_status = SchedulerResponse { id: "12345678".to_string(), state: "Finished".to_string(), projects: sample_project_list(), created_at: "Properly formated timestamp".to_string(), project_name: "Test Project".to_string(), target: "x86_64-linux".to_string(), }; let ident_list = get_ident_list(&mut ui, &group_status, Some("core"), false).expect("Error fetching \ ident list"); assert_eq!(ident_list, ["core/project1/1.0.0/20180101000000", "core/project2/1.0.0/20180101000000",]) } }
get_ident_list
identifier_name
effect.rs
use types::monster::StatType; use base::statmod::StatModifiers; use types::monster::ExperienceType; use base::runner::BattleFlagsType; use base::runner::{BattleEffects, BattleState}; use calculate::lingering::LingeringType; #[derive(Debug, PartialEq)] pub enum Effect { Damage(Damage), Switch(Switch), Retreat(Retreat), Modifier(Modifier), ExperienceGain(ExperienceGain), FlagsChange(FlagsChange), LingeringAdd(LingeringAdd), LingeringChange(LingeringChange), // Status(StatusId), // Ability(AbilityId), // Miss, //, None(NoneReason), } #[derive(Debug, PartialEq)] pub struct Damage { pub party: usize, // pub active: usize, pub member: usize, // pub meta: DamageMeta, // } impl Damage { pub fn amount(&self) -> StatType { self.meta.amount } pub fn party(&self) -> usize { self.party } pub fn member(&self) -> usize { self.member } pub fn critical(&self) -> bool { self.meta.critical } pub fn type_bonus(&self) -> f32 { self.meta.type_bonus } } #[derive(Debug, PartialEq)] pub struct DamageMeta { pub amount: StatType, // pub type_bonus: f32, // pub critical: bool, // // pub recoil: bool, // } #[derive(Debug, PartialEq)] pub struct Switch { pub party: usize, pub member: usize, pub target: usize, } #[derive(Debug, PartialEq)] pub struct Retreat { pub party: usize, pub active: usize, } #[derive(Debug, PartialEq)] pub struct Modifier { party: usize, active: usize, modifiers: StatModifiers, } impl Modifier { pub fn new(party: usize, active: usize, modifiers: StatModifiers) -> Self { Modifier { party: party, active: active, modifiers: modifiers } } pub fn party(&self) -> usize { self.party } pub fn active(&self) -> usize { self.active } pub fn modifiers(&self) -> &StatModifiers { &self.modifiers } } #[derive(Debug, PartialEq)] pub struct ExperienceGain { pub party: usize, pub member: usize, pub amount: ExperienceType, // Original level of the party member. pub level: u8, } impl ExperienceGain { pub fn new(party: usize, member: usize, amount: ExperienceType, level: u8) -> Self { ExperienceGain { party: party, member: member, amount: amount, level: level, } } } #[derive(Debug, PartialEq)] pub enum NoneReason { None, Miss, Escape, Turn, } #[derive(Debug, PartialEq)] pub struct FlagsChange { pub flags: BattleFlagsType, } pub trait Lingering { /// Creates an effect. Returns `true` to terminate further effects. fn effect(&self, effects: &mut BattleEffects, state: &BattleState) -> bool; /// Updates the underlying object's state. Returns `true` to active an effect. ///
/// Returns `true` by default. /// fn state_change(&mut self) -> bool { true } // TODO: Effects may be activated upon creation. /// Activates after the object was created. fn after_create(&mut self, state: &BattleState); /// Activates at the end of a turn. Returns `true` to change state. /// /// Returns `false` by default. /// fn after_turn(&self) -> bool { false } } #[derive(Debug, PartialEq)] pub struct LingeringAdd { pub lingering: LingeringType, } #[derive(Debug, PartialEq)] pub struct LingeringChange { pub index: usize, }
random_line_split
effect.rs
use types::monster::StatType; use base::statmod::StatModifiers; use types::monster::ExperienceType; use base::runner::BattleFlagsType; use base::runner::{BattleEffects, BattleState}; use calculate::lingering::LingeringType; #[derive(Debug, PartialEq)] pub enum Effect { Damage(Damage), Switch(Switch), Retreat(Retreat), Modifier(Modifier), ExperienceGain(ExperienceGain), FlagsChange(FlagsChange), LingeringAdd(LingeringAdd), LingeringChange(LingeringChange), // Status(StatusId), // Ability(AbilityId), // Miss, //, None(NoneReason), } #[derive(Debug, PartialEq)] pub struct Damage { pub party: usize, // pub active: usize, pub member: usize, // pub meta: DamageMeta, // } impl Damage { pub fn amount(&self) -> StatType { self.meta.amount } pub fn party(&self) -> usize { self.party } pub fn member(&self) -> usize { self.member } pub fn critical(&self) -> bool { self.meta.critical } pub fn type_bonus(&self) -> f32 { self.meta.type_bonus } } #[derive(Debug, PartialEq)] pub struct DamageMeta { pub amount: StatType, // pub type_bonus: f32, // pub critical: bool, // // pub recoil: bool, // } #[derive(Debug, PartialEq)] pub struct Switch { pub party: usize, pub member: usize, pub target: usize, } #[derive(Debug, PartialEq)] pub struct Retreat { pub party: usize, pub active: usize, } #[derive(Debug, PartialEq)] pub struct Modifier { party: usize, active: usize, modifiers: StatModifiers, } impl Modifier { pub fn new(party: usize, active: usize, modifiers: StatModifiers) -> Self { Modifier { party: party, active: active, modifiers: modifiers } } pub fn party(&self) -> usize { self.party } pub fn active(&self) -> usize { self.active } pub fn modifiers(&self) -> &StatModifiers { &self.modifiers } } #[derive(Debug, PartialEq)] pub struct
{ pub party: usize, pub member: usize, pub amount: ExperienceType, // Original level of the party member. pub level: u8, } impl ExperienceGain { pub fn new(party: usize, member: usize, amount: ExperienceType, level: u8) -> Self { ExperienceGain { party: party, member: member, amount: amount, level: level, } } } #[derive(Debug, PartialEq)] pub enum NoneReason { None, Miss, Escape, Turn, } #[derive(Debug, PartialEq)] pub struct FlagsChange { pub flags: BattleFlagsType, } pub trait Lingering { /// Creates an effect. Returns `true` to terminate further effects. fn effect(&self, effects: &mut BattleEffects, state: &BattleState) -> bool; /// Updates the underlying object's state. Returns `true` to active an effect. /// /// Returns `true` by default. /// fn state_change(&mut self) -> bool { true } // TODO: Effects may be activated upon creation. /// Activates after the object was created. fn after_create(&mut self, state: &BattleState); /// Activates at the end of a turn. Returns `true` to change state. /// /// Returns `false` by default. /// fn after_turn(&self) -> bool { false } } #[derive(Debug, PartialEq)] pub struct LingeringAdd { pub lingering: LingeringType, } #[derive(Debug, PartialEq)] pub struct LingeringChange { pub index: usize, }
ExperienceGain
identifier_name
effect.rs
use types::monster::StatType; use base::statmod::StatModifiers; use types::monster::ExperienceType; use base::runner::BattleFlagsType; use base::runner::{BattleEffects, BattleState}; use calculate::lingering::LingeringType; #[derive(Debug, PartialEq)] pub enum Effect { Damage(Damage), Switch(Switch), Retreat(Retreat), Modifier(Modifier), ExperienceGain(ExperienceGain), FlagsChange(FlagsChange), LingeringAdd(LingeringAdd), LingeringChange(LingeringChange), // Status(StatusId), // Ability(AbilityId), // Miss, //, None(NoneReason), } #[derive(Debug, PartialEq)] pub struct Damage { pub party: usize, // pub active: usize, pub member: usize, // pub meta: DamageMeta, // } impl Damage { pub fn amount(&self) -> StatType { self.meta.amount } pub fn party(&self) -> usize { self.party } pub fn member(&self) -> usize { self.member } pub fn critical(&self) -> bool { self.meta.critical } pub fn type_bonus(&self) -> f32 { self.meta.type_bonus } } #[derive(Debug, PartialEq)] pub struct DamageMeta { pub amount: StatType, // pub type_bonus: f32, // pub critical: bool, // // pub recoil: bool, // } #[derive(Debug, PartialEq)] pub struct Switch { pub party: usize, pub member: usize, pub target: usize, } #[derive(Debug, PartialEq)] pub struct Retreat { pub party: usize, pub active: usize, } #[derive(Debug, PartialEq)] pub struct Modifier { party: usize, active: usize, modifiers: StatModifiers, } impl Modifier { pub fn new(party: usize, active: usize, modifiers: StatModifiers) -> Self { Modifier { party: party, active: active, modifiers: modifiers } } pub fn party(&self) -> usize { self.party } pub fn active(&self) -> usize { self.active } pub fn modifiers(&self) -> &StatModifiers { &self.modifiers } } #[derive(Debug, PartialEq)] pub struct ExperienceGain { pub party: usize, pub member: usize, pub amount: ExperienceType, // Original level of the party member. pub level: u8, } impl ExperienceGain { pub fn new(party: usize, member: usize, amount: ExperienceType, level: u8) -> Self { ExperienceGain { party: party, member: member, amount: amount, level: level, } } } #[derive(Debug, PartialEq)] pub enum NoneReason { None, Miss, Escape, Turn, } #[derive(Debug, PartialEq)] pub struct FlagsChange { pub flags: BattleFlagsType, } pub trait Lingering { /// Creates an effect. Returns `true` to terminate further effects. fn effect(&self, effects: &mut BattleEffects, state: &BattleState) -> bool; /// Updates the underlying object's state. Returns `true` to active an effect. /// /// Returns `true` by default. /// fn state_change(&mut self) -> bool
// TODO: Effects may be activated upon creation. /// Activates after the object was created. fn after_create(&mut self, state: &BattleState); /// Activates at the end of a turn. Returns `true` to change state. /// /// Returns `false` by default. /// fn after_turn(&self) -> bool { false } } #[derive(Debug, PartialEq)] pub struct LingeringAdd { pub lingering: LingeringType, } #[derive(Debug, PartialEq)] pub struct LingeringChange { pub index: usize, }
{ true }
identifier_body
iris.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. use itertools::Itertools; use std::collections::HashMap; use std::iter::repeat; use std::num::ParseFloatError; use std::str::FromStr; static DATA: &'static str = include_str!("iris.data"); #[derive(Clone, Debug)] struct Iris { name: String, data: [f32; 4], } #[derive(Clone, Debug)] enum ParseError { Numeric(ParseFloatError), Other(&'static str), } impl From<ParseFloatError> for ParseError { fn from(err: ParseFloatError) -> Self { ParseError::Numeric(err) } } /// Parse an Iris from a comma-separated line impl FromStr for Iris { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut iris = Iris { name: "".into(), data: [0.; 4] }; let mut parts = s.split(",").map(str::trim); // using Iterator::by_ref() for (index, part) in parts.by_ref().take(4).enumerate() { iris.data[index] = part.parse::<f32>()?; } if let Some(name) = parts.next() { iris.name = name.into(); } else { return Err(ParseError::Other("Missing name")) } Ok(iris) } } fn main() { // using Itertools::fold_results to create the result of parsing let irises = DATA.lines() .map(str::parse) .fold_results(Vec::new(), |mut v, iris: Iris| { v.push(iris); v }); let mut irises = match irises { Err(e) => { println!("Error parsing: {:?}", e); std::process::exit(1); } Ok(data) => data, }; // Sort them and group them irises.sort_by(|a, b| Ord::cmp(&a.name, &b.name)); // using Iterator::cycle() let mut plot_symbols = "+ox".chars().cycle(); let mut symbolmap = HashMap::new(); // using Itertools::group_by for (species, species_group) in &irises.iter().group_by(|iris| &iris.name) { // assign a plot symbol symbolmap.entry(species).or_insert_with(|| { plot_symbols.next().unwrap() }); println!("{} (symbol={})", species, symbolmap[species]); for iris in species_group { // using Itertools::format for lazy formatting println!("{:>3.1}", iris.data.iter().format(", ")); } } // Look at all combinations of the four columns // // See https://en.wikipedia.org/wiki/Iris_flower_data_set // let n = 30; // plot size let mut plot = vec![' '; n * n]; // using Itertools::tuple_combinations for (a, b) in (0..4).tuple_combinations() { println!("Column {} vs {}:", a, b); // Clear plot // // using std::iter::repeat; // using Itertools::set_from
data.iter() .map(|iris| iris.data[col]) .minmax() .into_option() .expect("Can't find min/max of empty iterator") }; let (min_x, max_x) = min_max(&irises, a); let (min_y, max_y) = min_max(&irises, b); // Plot the data points let round_to_grid = |x, min, max| ((x - min) / (max - min) * ((n - 1) as f32)) as usize; let flip = |ix| n - 1 - ix; // reverse axis direction for iris in &irises { let ix = round_to_grid(iris.data[a], min_x, max_x); let iy = flip(round_to_grid(iris.data[b], min_y, max_y)); plot[n * iy + ix] = symbolmap[&iris.name]; } // render plot // // using Itertools::join for line in plot.chunks(n) { println!("{}", line.iter().join(" ")) } } }
plot.iter_mut().set_from(repeat(' ')); // using Itertools::minmax let min_max = |data: &[Iris], col| {
random_line_split
iris.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. use itertools::Itertools; use std::collections::HashMap; use std::iter::repeat; use std::num::ParseFloatError; use std::str::FromStr; static DATA: &'static str = include_str!("iris.data"); #[derive(Clone, Debug)] struct Iris { name: String, data: [f32; 4], } #[derive(Clone, Debug)] enum ParseError { Numeric(ParseFloatError), Other(&'static str), } impl From<ParseFloatError> for ParseError { fn
(err: ParseFloatError) -> Self { ParseError::Numeric(err) } } /// Parse an Iris from a comma-separated line impl FromStr for Iris { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut iris = Iris { name: "".into(), data: [0.; 4] }; let mut parts = s.split(",").map(str::trim); // using Iterator::by_ref() for (index, part) in parts.by_ref().take(4).enumerate() { iris.data[index] = part.parse::<f32>()?; } if let Some(name) = parts.next() { iris.name = name.into(); } else { return Err(ParseError::Other("Missing name")) } Ok(iris) } } fn main() { // using Itertools::fold_results to create the result of parsing let irises = DATA.lines() .map(str::parse) .fold_results(Vec::new(), |mut v, iris: Iris| { v.push(iris); v }); let mut irises = match irises { Err(e) => { println!("Error parsing: {:?}", e); std::process::exit(1); } Ok(data) => data, }; // Sort them and group them irises.sort_by(|a, b| Ord::cmp(&a.name, &b.name)); // using Iterator::cycle() let mut plot_symbols = "+ox".chars().cycle(); let mut symbolmap = HashMap::new(); // using Itertools::group_by for (species, species_group) in &irises.iter().group_by(|iris| &iris.name) { // assign a plot symbol symbolmap.entry(species).or_insert_with(|| { plot_symbols.next().unwrap() }); println!("{} (symbol={})", species, symbolmap[species]); for iris in species_group { // using Itertools::format for lazy formatting println!("{:>3.1}", iris.data.iter().format(", ")); } } // Look at all combinations of the four columns // // See https://en.wikipedia.org/wiki/Iris_flower_data_set // let n = 30; // plot size let mut plot = vec![' '; n * n]; // using Itertools::tuple_combinations for (a, b) in (0..4).tuple_combinations() { println!("Column {} vs {}:", a, b); // Clear plot // // using std::iter::repeat; // using Itertools::set_from plot.iter_mut().set_from(repeat(' ')); // using Itertools::minmax let min_max = |data: &[Iris], col| { data.iter() .map(|iris| iris.data[col]) .minmax() .into_option() .expect("Can't find min/max of empty iterator") }; let (min_x, max_x) = min_max(&irises, a); let (min_y, max_y) = min_max(&irises, b); // Plot the data points let round_to_grid = |x, min, max| ((x - min) / (max - min) * ((n - 1) as f32)) as usize; let flip = |ix| n - 1 - ix; // reverse axis direction for iris in &irises { let ix = round_to_grid(iris.data[a], min_x, max_x); let iy = flip(round_to_grid(iris.data[b], min_y, max_y)); plot[n * iy + ix] = symbolmap[&iris.name]; } // render plot // // using Itertools::join for line in plot.chunks(n) { println!("{}", line.iter().join(" ")) } } }
from
identifier_name
iris.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. use itertools::Itertools; use std::collections::HashMap; use std::iter::repeat; use std::num::ParseFloatError; use std::str::FromStr; static DATA: &'static str = include_str!("iris.data"); #[derive(Clone, Debug)] struct Iris { name: String, data: [f32; 4], } #[derive(Clone, Debug)] enum ParseError { Numeric(ParseFloatError), Other(&'static str), } impl From<ParseFloatError> for ParseError { fn from(err: ParseFloatError) -> Self { ParseError::Numeric(err) } } /// Parse an Iris from a comma-separated line impl FromStr for Iris { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut iris = Iris { name: "".into(), data: [0.; 4] }; let mut parts = s.split(",").map(str::trim); // using Iterator::by_ref() for (index, part) in parts.by_ref().take(4).enumerate() { iris.data[index] = part.parse::<f32>()?; } if let Some(name) = parts.next() { iris.name = name.into(); } else { return Err(ParseError::Other("Missing name")) } Ok(iris) } } fn main() { // using Itertools::fold_results to create the result of parsing let irises = DATA.lines() .map(str::parse) .fold_results(Vec::new(), |mut v, iris: Iris| { v.push(iris); v }); let mut irises = match irises { Err(e) =>
Ok(data) => data, }; // Sort them and group them irises.sort_by(|a, b| Ord::cmp(&a.name, &b.name)); // using Iterator::cycle() let mut plot_symbols = "+ox".chars().cycle(); let mut symbolmap = HashMap::new(); // using Itertools::group_by for (species, species_group) in &irises.iter().group_by(|iris| &iris.name) { // assign a plot symbol symbolmap.entry(species).or_insert_with(|| { plot_symbols.next().unwrap() }); println!("{} (symbol={})", species, symbolmap[species]); for iris in species_group { // using Itertools::format for lazy formatting println!("{:>3.1}", iris.data.iter().format(", ")); } } // Look at all combinations of the four columns // // See https://en.wikipedia.org/wiki/Iris_flower_data_set // let n = 30; // plot size let mut plot = vec![' '; n * n]; // using Itertools::tuple_combinations for (a, b) in (0..4).tuple_combinations() { println!("Column {} vs {}:", a, b); // Clear plot // // using std::iter::repeat; // using Itertools::set_from plot.iter_mut().set_from(repeat(' ')); // using Itertools::minmax let min_max = |data: &[Iris], col| { data.iter() .map(|iris| iris.data[col]) .minmax() .into_option() .expect("Can't find min/max of empty iterator") }; let (min_x, max_x) = min_max(&irises, a); let (min_y, max_y) = min_max(&irises, b); // Plot the data points let round_to_grid = |x, min, max| ((x - min) / (max - min) * ((n - 1) as f32)) as usize; let flip = |ix| n - 1 - ix; // reverse axis direction for iris in &irises { let ix = round_to_grid(iris.data[a], min_x, max_x); let iy = flip(round_to_grid(iris.data[b], min_y, max_y)); plot[n * iy + ix] = symbolmap[&iris.name]; } // render plot // // using Itertools::join for line in plot.chunks(n) { println!("{}", line.iter().join(" ")) } } }
{ println!("Error parsing: {:?}", e); std::process::exit(1); }
conditional_block
toggle.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. //! Runs a network with a service that is frequently switched on / off and that generates //! transactions in `after_commit` hook. // cspell:ignore noprobe use exonum::{helpers::Height, merkledb::ObjectHash, runtime::SnapshotExt}; use exonum_rust_runtime::{ spec::{Deploy, Spec}, DefaultInstance, }; use futures::{ channel::oneshot, future::{self, Either, RemoteHandle}, FutureExt, }; use reqwest::Client; use structopt::StructOpt; use tokio::time::delay_for; use std::{fmt, time::Duration}; use exonum_soak_tests::{ services::{MainConfig, MainService, MainServiceInterface, TogglingSupervisor}, NetworkBuilder, RunHandle, }; struct ApiStats { ok_answers: usize, erroneous_answers: usize, } impl fmt::Debug for ApiStats { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let mut debug_struct = formatter.debug_struct("ApiStats"); debug_struct .field("ok_answers", &self.ok_answers) .field("erroneous_answers", &self.erroneous_answers); let all_answers = self.ok_answers + self.erroneous_answers; if all_answers > 0 { let ok_fraction = self.ok_answers as f64 / all_answers as f64; debug_struct.field("ok_fraction", &ok_fraction); } debug_struct.finish() } } /// Periodically probes the node HTTP API, recording the number of times the response was /// successful and erroneous. `cancel_rx` is used to signal probe termination. async fn probe_api(url: &str, mut cancel_rx: oneshot::Receiver<()>) -> ApiStats { const API_TIMEOUT: Duration = Duration::from_millis(50); async fn send_request(client: &Client, url: &str) -> anyhow::Result<()> { let response: String = client .get(url) .timeout(API_TIMEOUT) .send() .await? .error_for_status()? .json() .await?; assert_eq!(response, "pong"); Ok(()) } let mut stats = ApiStats { ok_answers: 0, erroneous_answers: 0, }; loop { let selected = future::select(&mut cancel_rx, delay_for(API_TIMEOUT)).await; if let Either::Left(_) = selected { // We've received the cancellation signal; we're done. break; } // NB: reusing `Client` among requests makes it cache responses, which is the last thing // we want in this test. if let Err(e) = send_request(&Client::new(), url).await { log::info!("Call to node API resulted in an error: {}", e); stats.erroneous_answers += 1; } else { log::trace!("Successfully called node API"); stats.ok_answers += 1; } } stats } #[derive(Debug)] struct ApiProbe { cancel_tx: oneshot::Sender<()>, stats: RemoteHandle<ApiStats>, } impl ApiProbe { fn new(url: &'static str) -> Self { let (cancel_tx, cancel_rx) = oneshot::channel(); let (stats_task, stats) = probe_api(url, cancel_rx).remote_handle(); tokio::spawn(stats_task); Self { cancel_tx, stats } } async fn get(self) -> ApiStats { drop(self.cancel_tx); self.stats.await } } /// Runs a network with a service that is frequently switched on / off and that generates /// transactions in `after_commit` hook. #[derive(Debug, StructOpt)] #[structopt(name = "toggle", set_term_width = 80)] struct Args { /// Number of nodes in the network. #[structopt(name = "nodes", default_value = "4")] node_count: u16, /// Blockchain height to reach. If not specified, the test will run infinitely. #[structopt(name = "max-height", long, short = "H")] max_height: Option<u64>, /// Disable HTTP API probing. #[structopt(name = "noprobe", long)] no_probe: bool, } fn create_nodes(node_count: u16) -> Vec<RunHandle> { let config = MainConfig { generate_tx_in_after_commit: true, }; let main_service = Spec::new(MainService).with_instance( MainService::INSTANCE_ID, MainService::INSTANCE_NAME, config, ); let supervisor = Spec::new(TogglingSupervisor).with_default_instance(); let mut set_api = false; NetworkBuilder::new(node_count, 2_000) .modify_config(|node_cfg| { // Enable public HTTP server for a single node. if!set_api { node_cfg.api.public_api_address = Some("127.0.0.1:8080".parse().unwrap()); set_api = true; } // Slightly enlarge intervals between blocks. node_cfg.consensus.first_round_timeout *= 2; node_cfg.consensus.min_propose_timeout *= 2; node_cfg.consensus.max_propose_timeout *= 2; }) .init_node(|genesis, rt| { supervisor.clone().deploy(genesis, rt); main_service.clone().deploy(genesis, rt); }) .build() } #[tokio::main] async fn main() { exonum::crypto::init(); exonum::helpers::init_logger().ok(); let args = Args::from_args(); println!("Running test with {:?}", args); let nodes = create_nodes(args.node_count); let probes = if args.no_probe { None } else { let supervisor_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/supervisor/ping"); let main_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/main/ping"); Some((supervisor_probe, main_probe)) }; loop { let height = nodes[0].blockchain().last_block().height; println!("Blockchain height: {:?}", height); if args.max_height.map_or(false, |max| height >= Height(max)) { break; } delay_for(Duration::from_secs(1)).await; } let snapshot = nodes[0].blockchain().snapshot(); let core_schema = snapshot.for_core(); let transactions = core_schema.transactions(); let transactions_pool = core_schema.transactions_pool(); let height = core_schema.height(); let keys = future::join_all(nodes.into_iter().map(RunHandle::join)).await; let mut committed_timestamps = 0; for (node_i, keys) in keys.into_iter().enumerate() { let timestamps = (1..=height.0) .filter_map(|i| match i % 5 { 0 | 4 => Some(Height(i)), _ => None, }) .map(|i| (i, keys.timestamp(MainService::INSTANCE_ID, i))); for (i, timestamp) in timestamps { let tx_hash = timestamp.object_hash(); if transactions.contains(&tx_hash) &&!transactions_pool.contains(&tx_hash) { committed_timestamps += 1; } else { println!( "Did not commit transaction for node {} at height {:?}", node_i, i ); } } } let committed_txs = core_schema.transactions_len(); println!("Total committed transactions: {}", committed_txs); assert_eq!( committed_timestamps, committed_txs, "There are unknown transactions on the blockchain" ); if let Some((supervisor_probe, main_probe)) = probes { println!( "Supervisor availability: {:#?}", supervisor_probe.get().await ); println!("Main service availability: {:#?}", main_probe.get().await); } } #[cfg(test)] mod tests { use super::*; use std::time::Instant; /// Checks that the node functions after an HTTP server reboot. #[tokio::test] async fn basic_workflow_is_functional() { const EXPECTED_HEIGHT: Height = Height(5); const MAX_WAIT: Duration = Duration::from_secs(10); let node = create_nodes(1).pop().unwrap();
break; } else if Instant::now() - start_time > MAX_WAIT { panic!("Node did not achieve {:?}", EXPECTED_HEIGHT); } delay_for(MAX_WAIT / 20).await; } node.join().await; } }
let start_time = Instant::now(); loop { let last_block = node.blockchain().last_block(); if last_block.height > EXPECTED_HEIGHT {
random_line_split
toggle.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. //! Runs a network with a service that is frequently switched on / off and that generates //! transactions in `after_commit` hook. // cspell:ignore noprobe use exonum::{helpers::Height, merkledb::ObjectHash, runtime::SnapshotExt}; use exonum_rust_runtime::{ spec::{Deploy, Spec}, DefaultInstance, }; use futures::{ channel::oneshot, future::{self, Either, RemoteHandle}, FutureExt, }; use reqwest::Client; use structopt::StructOpt; use tokio::time::delay_for; use std::{fmt, time::Duration}; use exonum_soak_tests::{ services::{MainConfig, MainService, MainServiceInterface, TogglingSupervisor}, NetworkBuilder, RunHandle, }; struct ApiStats { ok_answers: usize, erroneous_answers: usize, } impl fmt::Debug for ApiStats { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let mut debug_struct = formatter.debug_struct("ApiStats"); debug_struct .field("ok_answers", &self.ok_answers) .field("erroneous_answers", &self.erroneous_answers); let all_answers = self.ok_answers + self.erroneous_answers; if all_answers > 0 { let ok_fraction = self.ok_answers as f64 / all_answers as f64; debug_struct.field("ok_fraction", &ok_fraction); } debug_struct.finish() } } /// Periodically probes the node HTTP API, recording the number of times the response was /// successful and erroneous. `cancel_rx` is used to signal probe termination. async fn probe_api(url: &str, mut cancel_rx: oneshot::Receiver<()>) -> ApiStats { const API_TIMEOUT: Duration = Duration::from_millis(50); async fn send_request(client: &Client, url: &str) -> anyhow::Result<()> { let response: String = client .get(url) .timeout(API_TIMEOUT) .send() .await? .error_for_status()? .json() .await?; assert_eq!(response, "pong"); Ok(()) } let mut stats = ApiStats { ok_answers: 0, erroneous_answers: 0, }; loop { let selected = future::select(&mut cancel_rx, delay_for(API_TIMEOUT)).await; if let Either::Left(_) = selected { // We've received the cancellation signal; we're done. break; } // NB: reusing `Client` among requests makes it cache responses, which is the last thing // we want in this test. if let Err(e) = send_request(&Client::new(), url).await { log::info!("Call to node API resulted in an error: {}", e); stats.erroneous_answers += 1; } else { log::trace!("Successfully called node API"); stats.ok_answers += 1; } } stats } #[derive(Debug)] struct ApiProbe { cancel_tx: oneshot::Sender<()>, stats: RemoteHandle<ApiStats>, } impl ApiProbe { fn new(url: &'static str) -> Self { let (cancel_tx, cancel_rx) = oneshot::channel(); let (stats_task, stats) = probe_api(url, cancel_rx).remote_handle(); tokio::spawn(stats_task); Self { cancel_tx, stats } } async fn
(self) -> ApiStats { drop(self.cancel_tx); self.stats.await } } /// Runs a network with a service that is frequently switched on / off and that generates /// transactions in `after_commit` hook. #[derive(Debug, StructOpt)] #[structopt(name = "toggle", set_term_width = 80)] struct Args { /// Number of nodes in the network. #[structopt(name = "nodes", default_value = "4")] node_count: u16, /// Blockchain height to reach. If not specified, the test will run infinitely. #[structopt(name = "max-height", long, short = "H")] max_height: Option<u64>, /// Disable HTTP API probing. #[structopt(name = "noprobe", long)] no_probe: bool, } fn create_nodes(node_count: u16) -> Vec<RunHandle> { let config = MainConfig { generate_tx_in_after_commit: true, }; let main_service = Spec::new(MainService).with_instance( MainService::INSTANCE_ID, MainService::INSTANCE_NAME, config, ); let supervisor = Spec::new(TogglingSupervisor).with_default_instance(); let mut set_api = false; NetworkBuilder::new(node_count, 2_000) .modify_config(|node_cfg| { // Enable public HTTP server for a single node. if!set_api { node_cfg.api.public_api_address = Some("127.0.0.1:8080".parse().unwrap()); set_api = true; } // Slightly enlarge intervals between blocks. node_cfg.consensus.first_round_timeout *= 2; node_cfg.consensus.min_propose_timeout *= 2; node_cfg.consensus.max_propose_timeout *= 2; }) .init_node(|genesis, rt| { supervisor.clone().deploy(genesis, rt); main_service.clone().deploy(genesis, rt); }) .build() } #[tokio::main] async fn main() { exonum::crypto::init(); exonum::helpers::init_logger().ok(); let args = Args::from_args(); println!("Running test with {:?}", args); let nodes = create_nodes(args.node_count); let probes = if args.no_probe { None } else { let supervisor_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/supervisor/ping"); let main_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/main/ping"); Some((supervisor_probe, main_probe)) }; loop { let height = nodes[0].blockchain().last_block().height; println!("Blockchain height: {:?}", height); if args.max_height.map_or(false, |max| height >= Height(max)) { break; } delay_for(Duration::from_secs(1)).await; } let snapshot = nodes[0].blockchain().snapshot(); let core_schema = snapshot.for_core(); let transactions = core_schema.transactions(); let transactions_pool = core_schema.transactions_pool(); let height = core_schema.height(); let keys = future::join_all(nodes.into_iter().map(RunHandle::join)).await; let mut committed_timestamps = 0; for (node_i, keys) in keys.into_iter().enumerate() { let timestamps = (1..=height.0) .filter_map(|i| match i % 5 { 0 | 4 => Some(Height(i)), _ => None, }) .map(|i| (i, keys.timestamp(MainService::INSTANCE_ID, i))); for (i, timestamp) in timestamps { let tx_hash = timestamp.object_hash(); if transactions.contains(&tx_hash) &&!transactions_pool.contains(&tx_hash) { committed_timestamps += 1; } else { println!( "Did not commit transaction for node {} at height {:?}", node_i, i ); } } } let committed_txs = core_schema.transactions_len(); println!("Total committed transactions: {}", committed_txs); assert_eq!( committed_timestamps, committed_txs, "There are unknown transactions on the blockchain" ); if let Some((supervisor_probe, main_probe)) = probes { println!( "Supervisor availability: {:#?}", supervisor_probe.get().await ); println!("Main service availability: {:#?}", main_probe.get().await); } } #[cfg(test)] mod tests { use super::*; use std::time::Instant; /// Checks that the node functions after an HTTP server reboot. #[tokio::test] async fn basic_workflow_is_functional() { const EXPECTED_HEIGHT: Height = Height(5); const MAX_WAIT: Duration = Duration::from_secs(10); let node = create_nodes(1).pop().unwrap(); let start_time = Instant::now(); loop { let last_block = node.blockchain().last_block(); if last_block.height > EXPECTED_HEIGHT { break; } else if Instant::now() - start_time > MAX_WAIT { panic!("Node did not achieve {:?}", EXPECTED_HEIGHT); } delay_for(MAX_WAIT / 20).await; } node.join().await; } }
get
identifier_name
toggle.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. //! Runs a network with a service that is frequently switched on / off and that generates //! transactions in `after_commit` hook. // cspell:ignore noprobe use exonum::{helpers::Height, merkledb::ObjectHash, runtime::SnapshotExt}; use exonum_rust_runtime::{ spec::{Deploy, Spec}, DefaultInstance, }; use futures::{ channel::oneshot, future::{self, Either, RemoteHandle}, FutureExt, }; use reqwest::Client; use structopt::StructOpt; use tokio::time::delay_for; use std::{fmt, time::Duration}; use exonum_soak_tests::{ services::{MainConfig, MainService, MainServiceInterface, TogglingSupervisor}, NetworkBuilder, RunHandle, }; struct ApiStats { ok_answers: usize, erroneous_answers: usize, } impl fmt::Debug for ApiStats { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
} /// Periodically probes the node HTTP API, recording the number of times the response was /// successful and erroneous. `cancel_rx` is used to signal probe termination. async fn probe_api(url: &str, mut cancel_rx: oneshot::Receiver<()>) -> ApiStats { const API_TIMEOUT: Duration = Duration::from_millis(50); async fn send_request(client: &Client, url: &str) -> anyhow::Result<()> { let response: String = client .get(url) .timeout(API_TIMEOUT) .send() .await? .error_for_status()? .json() .await?; assert_eq!(response, "pong"); Ok(()) } let mut stats = ApiStats { ok_answers: 0, erroneous_answers: 0, }; loop { let selected = future::select(&mut cancel_rx, delay_for(API_TIMEOUT)).await; if let Either::Left(_) = selected { // We've received the cancellation signal; we're done. break; } // NB: reusing `Client` among requests makes it cache responses, which is the last thing // we want in this test. if let Err(e) = send_request(&Client::new(), url).await { log::info!("Call to node API resulted in an error: {}", e); stats.erroneous_answers += 1; } else { log::trace!("Successfully called node API"); stats.ok_answers += 1; } } stats } #[derive(Debug)] struct ApiProbe { cancel_tx: oneshot::Sender<()>, stats: RemoteHandle<ApiStats>, } impl ApiProbe { fn new(url: &'static str) -> Self { let (cancel_tx, cancel_rx) = oneshot::channel(); let (stats_task, stats) = probe_api(url, cancel_rx).remote_handle(); tokio::spawn(stats_task); Self { cancel_tx, stats } } async fn get(self) -> ApiStats { drop(self.cancel_tx); self.stats.await } } /// Runs a network with a service that is frequently switched on / off and that generates /// transactions in `after_commit` hook. #[derive(Debug, StructOpt)] #[structopt(name = "toggle", set_term_width = 80)] struct Args { /// Number of nodes in the network. #[structopt(name = "nodes", default_value = "4")] node_count: u16, /// Blockchain height to reach. If not specified, the test will run infinitely. #[structopt(name = "max-height", long, short = "H")] max_height: Option<u64>, /// Disable HTTP API probing. #[structopt(name = "noprobe", long)] no_probe: bool, } fn create_nodes(node_count: u16) -> Vec<RunHandle> { let config = MainConfig { generate_tx_in_after_commit: true, }; let main_service = Spec::new(MainService).with_instance( MainService::INSTANCE_ID, MainService::INSTANCE_NAME, config, ); let supervisor = Spec::new(TogglingSupervisor).with_default_instance(); let mut set_api = false; NetworkBuilder::new(node_count, 2_000) .modify_config(|node_cfg| { // Enable public HTTP server for a single node. if!set_api { node_cfg.api.public_api_address = Some("127.0.0.1:8080".parse().unwrap()); set_api = true; } // Slightly enlarge intervals between blocks. node_cfg.consensus.first_round_timeout *= 2; node_cfg.consensus.min_propose_timeout *= 2; node_cfg.consensus.max_propose_timeout *= 2; }) .init_node(|genesis, rt| { supervisor.clone().deploy(genesis, rt); main_service.clone().deploy(genesis, rt); }) .build() } #[tokio::main] async fn main() { exonum::crypto::init(); exonum::helpers::init_logger().ok(); let args = Args::from_args(); println!("Running test with {:?}", args); let nodes = create_nodes(args.node_count); let probes = if args.no_probe { None } else { let supervisor_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/supervisor/ping"); let main_probe = ApiProbe::new("http://127.0.0.1:8080/api/services/main/ping"); Some((supervisor_probe, main_probe)) }; loop { let height = nodes[0].blockchain().last_block().height; println!("Blockchain height: {:?}", height); if args.max_height.map_or(false, |max| height >= Height(max)) { break; } delay_for(Duration::from_secs(1)).await; } let snapshot = nodes[0].blockchain().snapshot(); let core_schema = snapshot.for_core(); let transactions = core_schema.transactions(); let transactions_pool = core_schema.transactions_pool(); let height = core_schema.height(); let keys = future::join_all(nodes.into_iter().map(RunHandle::join)).await; let mut committed_timestamps = 0; for (node_i, keys) in keys.into_iter().enumerate() { let timestamps = (1..=height.0) .filter_map(|i| match i % 5 { 0 | 4 => Some(Height(i)), _ => None, }) .map(|i| (i, keys.timestamp(MainService::INSTANCE_ID, i))); for (i, timestamp) in timestamps { let tx_hash = timestamp.object_hash(); if transactions.contains(&tx_hash) &&!transactions_pool.contains(&tx_hash) { committed_timestamps += 1; } else { println!( "Did not commit transaction for node {} at height {:?}", node_i, i ); } } } let committed_txs = core_schema.transactions_len(); println!("Total committed transactions: {}", committed_txs); assert_eq!( committed_timestamps, committed_txs, "There are unknown transactions on the blockchain" ); if let Some((supervisor_probe, main_probe)) = probes { println!( "Supervisor availability: {:#?}", supervisor_probe.get().await ); println!("Main service availability: {:#?}", main_probe.get().await); } } #[cfg(test)] mod tests { use super::*; use std::time::Instant; /// Checks that the node functions after an HTTP server reboot. #[tokio::test] async fn basic_workflow_is_functional() { const EXPECTED_HEIGHT: Height = Height(5); const MAX_WAIT: Duration = Duration::from_secs(10); let node = create_nodes(1).pop().unwrap(); let start_time = Instant::now(); loop { let last_block = node.blockchain().last_block(); if last_block.height > EXPECTED_HEIGHT { break; } else if Instant::now() - start_time > MAX_WAIT { panic!("Node did not achieve {:?}", EXPECTED_HEIGHT); } delay_for(MAX_WAIT / 20).await; } node.join().await; } }
{ let mut debug_struct = formatter.debug_struct("ApiStats"); debug_struct .field("ok_answers", &self.ok_answers) .field("erroneous_answers", &self.erroneous_answers); let all_answers = self.ok_answers + self.erroneous_answers; if all_answers > 0 { let ok_fraction = self.ok_answers as f64 / all_answers as f64; debug_struct.field("ok_fraction", &ok_fraction); } debug_struct.finish() }
identifier_body
enter_vars.rs
use tableau::tables::Table; pub fn enter_var_pivot_optimal(table: &Table) -> usize { let table_rows = table.get_rows(); let last_row_index = table_rows.len() - 1; // Select the most negative cell in the objective function row. let mut column_index = 0; for i in 0..table_rows[last_row_index].len() - 1 { if table_rows[last_row_index][i] < table_rows[last_row_index][column_index]
} column_index } pub fn enter_var_pivot_feasible(table: &Table, row: usize, begin_column: usize) -> Option<usize> { let table_rows = table.get_rows(); // Select the positive cell furthest to the left. for i in 0..begin_column { if table_rows[row][i].is_sign_positive() && table_rows[row][i] > 0.0 { return Some(i); } } None }
{ column_index = i; }
conditional_block
enter_vars.rs
use tableau::tables::Table; pub fn enter_var_pivot_optimal(table: &Table) -> usize
pub fn enter_var_pivot_feasible(table: &Table, row: usize, begin_column: usize) -> Option<usize> { let table_rows = table.get_rows(); // Select the positive cell furthest to the left. for i in 0..begin_column { if table_rows[row][i].is_sign_positive() && table_rows[row][i] > 0.0 { return Some(i); } } None }
{ let table_rows = table.get_rows(); let last_row_index = table_rows.len() - 1; // Select the most negative cell in the objective function row. let mut column_index = 0; for i in 0..table_rows[last_row_index].len() - 1 { if table_rows[last_row_index][i] < table_rows[last_row_index][column_index] { column_index = i; } } column_index }
identifier_body
enter_vars.rs
use tableau::tables::Table; pub fn enter_var_pivot_optimal(table: &Table) -> usize { let table_rows = table.get_rows(); let last_row_index = table_rows.len() - 1; // Select the most negative cell in the objective function row. let mut column_index = 0; for i in 0..table_rows[last_row_index].len() - 1 { if table_rows[last_row_index][i] < table_rows[last_row_index][column_index] { column_index = i;
} pub fn enter_var_pivot_feasible(table: &Table, row: usize, begin_column: usize) -> Option<usize> { let table_rows = table.get_rows(); // Select the positive cell furthest to the left. for i in 0..begin_column { if table_rows[row][i].is_sign_positive() && table_rows[row][i] > 0.0 { return Some(i); } } None }
} } column_index
random_line_split
enter_vars.rs
use tableau::tables::Table; pub fn
(table: &Table) -> usize { let table_rows = table.get_rows(); let last_row_index = table_rows.len() - 1; // Select the most negative cell in the objective function row. let mut column_index = 0; for i in 0..table_rows[last_row_index].len() - 1 { if table_rows[last_row_index][i] < table_rows[last_row_index][column_index] { column_index = i; } } column_index } pub fn enter_var_pivot_feasible(table: &Table, row: usize, begin_column: usize) -> Option<usize> { let table_rows = table.get_rows(); // Select the positive cell furthest to the left. for i in 0..begin_column { if table_rows[row][i].is_sign_positive() && table_rows[row][i] > 0.0 { return Some(i); } } None }
enter_var_pivot_optimal
identifier_name
mod.rs
// Copyright (c) 2015 Chris Palmer <[email protected]> // Use of this source code is governed by the GPLv3 license that can be // found in the LICENSE file. use std::io::prelude::*; use std::io::BufReader; use std::fs::File; pub fn
(path_str: &str) -> Vec<String> { let mut file_vec: Vec<String> = Vec::new(); let f = File::open(path_str).unwrap(); let reader = BufReader::new(f); for line in reader.lines() { file_vec.push(line.unwrap()); } file_vec } pub fn get_version() -> &'static str { "1.0.0" } pub fn get_name() -> &'static str { "file_compare" } pub fn get_author() -> &'static str { "red-oxide <https://github.com/red-oxide/file_compare>" } pub fn get_about() -> &'static str { "compare two files to see if lines in first file exist in the second file" }
read_to_vec
identifier_name
mod.rs
// Copyright (c) 2015 Chris Palmer <[email protected]> // Use of this source code is governed by the GPLv3 license that can be // found in the LICENSE file. use std::io::prelude::*; use std::io::BufReader; use std::fs::File; pub fn read_to_vec(path_str: &str) -> Vec<String> {
for line in reader.lines() { file_vec.push(line.unwrap()); } file_vec } pub fn get_version() -> &'static str { "1.0.0" } pub fn get_name() -> &'static str { "file_compare" } pub fn get_author() -> &'static str { "red-oxide <https://github.com/red-oxide/file_compare>" } pub fn get_about() -> &'static str { "compare two files to see if lines in first file exist in the second file" }
let mut file_vec: Vec<String> = Vec::new(); let f = File::open(path_str).unwrap(); let reader = BufReader::new(f);
random_line_split
mod.rs
// Copyright (c) 2015 Chris Palmer <[email protected]> // Use of this source code is governed by the GPLv3 license that can be // found in the LICENSE file. use std::io::prelude::*; use std::io::BufReader; use std::fs::File; pub fn read_to_vec(path_str: &str) -> Vec<String> { let mut file_vec: Vec<String> = Vec::new(); let f = File::open(path_str).unwrap(); let reader = BufReader::new(f); for line in reader.lines() { file_vec.push(line.unwrap()); } file_vec } pub fn get_version() -> &'static str { "1.0.0" } pub fn get_name() -> &'static str
pub fn get_author() -> &'static str { "red-oxide <https://github.com/red-oxide/file_compare>" } pub fn get_about() -> &'static str { "compare two files to see if lines in first file exist in the second file" }
{ "file_compare" }
identifier_body
main.rs
use std::collections::VecDeque; use std::io::{self, Write}; fn haar_level(f: Vec<f64>) -> (Vec<f64>, Vec<f64>){ let mut a: Vec<f64> = Vec::new(); let mut d: Vec<f64> = Vec::new(); let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let n : usize = f.len() / 2; for i in 0..n { a.push(base*(f[2*i] + f[2*i+1])); d.push(base*(f[2*i] - f[2*i+1])); } (a, d) } fn
(f: Vec<f64>) -> VecDeque<Vec<f64>> { let n = (f.len() as f64).log2().trunc() as u32; println!("n {}", n); let mut a: Vec<f64> = Vec::new(); let m = 2u32.pow(n) as usize; for i in 0..m { a.push(f[i]); } let mut res : VecDeque<Vec<f64>> = VecDeque::new(); while a.len() > 1 { let (newa, d) = haar_level(a); a = newa; res.push_front(d); } res.push_front(a); res } fn inverse_haar_level(a: Vec<f64>, d: Vec<f64>) -> Vec<f64> { let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let mut res : Vec<f64> = Vec::new(); for i in 0..a.len() { res.push(base*(a[i] + d[i])); res.push(base*(a[i] - d[i])); } res } fn inverse_haar(h: VecDeque<Vec<f64>>) -> Vec<f64> { let mut an = h[0].clone(); for i in 1..h.len() { an = inverse_haar_level( an, h[i].clone() ); } an } fn print(d : Vec<f64>, end: bool) { print!("[ "); for i in &d { print!("{}, ", i); } print!(" ] "); if end { print!("\n"); } io::stdout().flush().unwrap(); } fn print2(d : VecDeque<Vec<f64>>) { print!("[ "); for i in d { print(i, false); } print!(" ]\n"); io::stdout().flush().unwrap(); } fn main() { let data : Vec<f64> = vec![4.,6.,10.,12.,8.,6.,5.,5.]; print(data.clone(), true); let res = haar(data); print2(res.clone()); print(inverse_haar(res.clone()), true); }
haar
identifier_name
main.rs
use std::collections::VecDeque; use std::io::{self, Write}; fn haar_level(f: Vec<f64>) -> (Vec<f64>, Vec<f64>){ let mut a: Vec<f64> = Vec::new(); let mut d: Vec<f64> = Vec::new(); let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let n : usize = f.len() / 2; for i in 0..n { a.push(base*(f[2*i] + f[2*i+1])); d.push(base*(f[2*i] - f[2*i+1])); } (a, d) } fn haar(f: Vec<f64>) -> VecDeque<Vec<f64>> { let n = (f.len() as f64).log2().trunc() as u32; println!("n {}", n); let mut a: Vec<f64> = Vec::new(); let m = 2u32.pow(n) as usize; for i in 0..m { a.push(f[i]); } let mut res : VecDeque<Vec<f64>> = VecDeque::new(); while a.len() > 1 { let (newa, d) = haar_level(a); a = newa; res.push_front(d); } res.push_front(a); res } fn inverse_haar_level(a: Vec<f64>, d: Vec<f64>) -> Vec<f64> { let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let mut res : Vec<f64> = Vec::new(); for i in 0..a.len() { res.push(base*(a[i] + d[i])); res.push(base*(a[i] - d[i])); } res } fn inverse_haar(h: VecDeque<Vec<f64>>) -> Vec<f64> { let mut an = h[0].clone(); for i in 1..h.len() { an = inverse_haar_level( an, h[i].clone() ); } an } fn print(d : Vec<f64>, end: bool) { print!("[ "); for i in &d { print!("{}, ", i); } print!(" ] "); if end
io::stdout().flush().unwrap(); } fn print2(d : VecDeque<Vec<f64>>) { print!("[ "); for i in d { print(i, false); } print!(" ]\n"); io::stdout().flush().unwrap(); } fn main() { let data : Vec<f64> = vec![4.,6.,10.,12.,8.,6.,5.,5.]; print(data.clone(), true); let res = haar(data); print2(res.clone()); print(inverse_haar(res.clone()), true); }
{ print!("\n"); }
conditional_block
main.rs
use std::collections::VecDeque; use std::io::{self, Write}; fn haar_level(f: Vec<f64>) -> (Vec<f64>, Vec<f64>){ let mut a: Vec<f64> = Vec::new(); let mut d: Vec<f64> = Vec::new(); let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let n : usize = f.len() / 2; for i in 0..n { a.push(base*(f[2*i] + f[2*i+1])); d.push(base*(f[2*i] - f[2*i+1])); } (a, d) } fn haar(f: Vec<f64>) -> VecDeque<Vec<f64>> { let n = (f.len() as f64).log2().trunc() as u32; println!("n {}", n); let mut a: Vec<f64> = Vec::new(); let m = 2u32.pow(n) as usize; for i in 0..m { a.push(f[i]); } let mut res : VecDeque<Vec<f64>> = VecDeque::new(); while a.len() > 1 { let (newa, d) = haar_level(a); a = newa; res.push_front(d); } res.push_front(a); res } fn inverse_haar_level(a: Vec<f64>, d: Vec<f64>) -> Vec<f64> { let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let mut res : Vec<f64> = Vec::new(); for i in 0..a.len() { res.push(base*(a[i] + d[i])); res.push(base*(a[i] - d[i])); } res } fn inverse_haar(h: VecDeque<Vec<f64>>) -> Vec<f64> { let mut an = h[0].clone(); for i in 1..h.len() { an = inverse_haar_level( an, h[i].clone() ); } an } fn print(d : Vec<f64>, end: bool) { print!("[ "); for i in &d { print!("{}, ", i); } print!(" ] "); if end { print!("\n"); } io::stdout().flush().unwrap(); } fn print2(d : VecDeque<Vec<f64>>) { print!("[ "); for i in d {
} fn main() { let data : Vec<f64> = vec![4.,6.,10.,12.,8.,6.,5.,5.]; print(data.clone(), true); let res = haar(data); print2(res.clone()); print(inverse_haar(res.clone()), true); }
print(i, false); } print!(" ]\n"); io::stdout().flush().unwrap();
random_line_split
main.rs
use std::collections::VecDeque; use std::io::{self, Write}; fn haar_level(f: Vec<f64>) -> (Vec<f64>, Vec<f64>){ let mut a: Vec<f64> = Vec::new(); let mut d: Vec<f64> = Vec::new(); let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let n : usize = f.len() / 2; for i in 0..n { a.push(base*(f[2*i] + f[2*i+1])); d.push(base*(f[2*i] - f[2*i+1])); } (a, d) } fn haar(f: Vec<f64>) -> VecDeque<Vec<f64>> { let n = (f.len() as f64).log2().trunc() as u32; println!("n {}", n); let mut a: Vec<f64> = Vec::new(); let m = 2u32.pow(n) as usize; for i in 0..m { a.push(f[i]); } let mut res : VecDeque<Vec<f64>> = VecDeque::new(); while a.len() > 1 { let (newa, d) = haar_level(a); a = newa; res.push_front(d); } res.push_front(a); res } fn inverse_haar_level(a: Vec<f64>, d: Vec<f64>) -> Vec<f64> { let base : f64 = 1.0f64 / 2.0f64.powf(0.5f64); let mut res : Vec<f64> = Vec::new(); for i in 0..a.len() { res.push(base*(a[i] + d[i])); res.push(base*(a[i] - d[i])); } res } fn inverse_haar(h: VecDeque<Vec<f64>>) -> Vec<f64> { let mut an = h[0].clone(); for i in 1..h.len() { an = inverse_haar_level( an, h[i].clone() ); } an } fn print(d : Vec<f64>, end: bool) { print!("[ "); for i in &d { print!("{}, ", i); } print!(" ] "); if end { print!("\n"); } io::stdout().flush().unwrap(); } fn print2(d : VecDeque<Vec<f64>>) { print!("[ "); for i in d { print(i, false); } print!(" ]\n"); io::stdout().flush().unwrap(); } fn main()
{ let data : Vec<f64> = vec![4.,6.,10.,12.,8.,6.,5.,5.]; print(data.clone(), true); let res = haar(data); print2(res.clone()); print(inverse_haar(res.clone()), true); }
identifier_body
select_ok.rs
extern crate futures; use futures::future::*; #[test] fn ignore_err() { let v = vec![ err(1).boxed(), err(2).boxed(), ok(3).boxed(), ok(4).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 3); assert!(v.len() == 1); let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 4); assert!(v.len() == 0); } #[test] fn last_err()
{ let v = vec![ ok(1).boxed(), err(2).boxed(), err(3).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 1); assert!(v.len() == 2); let i = select_ok(v).wait().err().unwrap(); assert_eq!(i, 3); }
identifier_body
select_ok.rs
extern crate futures; use futures::future::*; #[test] fn ignore_err() { let v = vec![ err(1).boxed(), err(2).boxed(), ok(3).boxed(), ok(4).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 3); assert!(v.len() == 1);
let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 4); assert!(v.len() == 0); } #[test] fn last_err() { let v = vec![ ok(1).boxed(), err(2).boxed(), err(3).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 1); assert!(v.len() == 2); let i = select_ok(v).wait().err().unwrap(); assert_eq!(i, 3); }
random_line_split
select_ok.rs
extern crate futures; use futures::future::*; #[test] fn ignore_err() { let v = vec![ err(1).boxed(), err(2).boxed(), ok(3).boxed(), ok(4).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 3); assert!(v.len() == 1); let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 4); assert!(v.len() == 0); } #[test] fn
() { let v = vec![ ok(1).boxed(), err(2).boxed(), err(3).boxed(), ]; let (i, v) = select_ok(v).wait().ok().unwrap(); assert_eq!(i, 1); assert!(v.len() == 2); let i = select_ok(v).wait().err().unwrap(); assert_eq!(i, 3); }
last_err
identifier_name
root.rs
. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based rooted value. //! - `DomRoot<T>`: a stack-based reference to a rooted DOM object. //! - `Dom<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `Dom<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `DomRoot<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `DomRoot<T>`. //! use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{DomObject, Reflector}; use crate::dom::bindings::trace::trace_reflector; use crate::dom::bindings::trace::JSTraceable; use crate::dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use mitochondria::OnceCell; use script_layout_interface::TrustedNodeAddress; use std::cell::{Cell, UnsafeCell}; use std::default::Default; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::mem; use std::ops::Deref; use std::ptr; use style::thread_state; /// A rooted value. #[allow(unrooted_must_root)] #[allow_unrooted_interior] pub struct Root<T: StableTraceObject> { /// The value to root. value: T, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T> Root<T> where T: StableTraceObject +'static, { /// Create a new stack-bounded root for the provided value. /// It cannot outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. #[allow(unrooted_must_root)] unsafe fn new(value: T) -> Self { debug_assert!(thread_state::get().is_script()); STACK_ROOTS.with(|ref root_list| { let root_list = &*root_list.get().unwrap(); root_list.root(value.stable_trace_object()); Root { value, root_list } }) } } /// Represents values that can be rooted through a stable address that will /// not change for their whole lifetime. pub unsafe trait StableTraceObject { /// Returns a stable trace object which address won't change for the whole /// lifetime of the value. fn stable_trace_object(&self) -> *const dyn JSTraceable; } unsafe impl<T> StableTraceObject for Dom<T> where T: DomObject, { fn stable_trace_object<'a>(&'a self) -> *const dyn JSTraceable { // The JSTraceable impl for Reflector doesn't actually do anything, // so we need this shenanigan to actually trace the reflector of the // T pointer in Dom<T>. #[allow(unrooted_must_root)] struct ReflectorStackRoot(Reflector); unsafe impl JSTraceable for ReflectorStackRoot { unsafe fn trace(&self, tracer: *mut JSTracer) { trace_reflector(tracer, "on stack", &self.0); } } unsafe { &*(self.reflector() as *const Reflector as *const ReflectorStackRoot) } } } impl<T> Deref for Root<T> where T: Deref + StableTraceObject, { type Target = <T as Deref>::Target; fn deref(&self) -> &Self::Target { debug_assert!(thread_state::get().is_script()); &self.value } } impl<T> Drop for Root<T> where T: StableTraceObject, { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self.value.stable_trace_object()); } } } /// A rooted reference to a DOM object. pub type DomRoot<T> = Root<Dom<T>>; impl<T: Castable> DomRoot<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U> where U: Castable, T: DerivedFrom<U>, { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>> where U: DerivedFrom<T>, { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: DomObject> DomRoot<T> { /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> DomRoot<T> { unsafe { DomRoot::new(Dom::from_ref(unrooted)) } } } impl<T> MallocSizeOf for DomRoot<T> where T: DomObject + MallocSizeOf, { fn
(&self, ops: &mut MallocSizeOfOps) -> usize { (**self).size_of(ops) } } impl<T> PartialEq for DomRoot<T> where T: DomObject, { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl<T> Clone for DomRoot<T> where T: DomObject, { fn clone(&self) -> DomRoot<T> { DomRoot::from_ref(&*self) } } unsafe impl<T> JSTraceable for DomRoot<T> where T: DomObject, { unsafe fn trace(&self, _: *mut JSTracer) { // Already traced. } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const dyn JSTraceable>>, } thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = Cell::new(None)); pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>); impl<'a> ThreadLocalStackRoots<'a> { pub fn new(roots: &'a RootCollection) -> Self { STACK_ROOTS.with(|ref r| r.set(Some(roots))); ThreadLocalStackRoots(PhantomData) } } impl<'a> Drop for ThreadLocalStackRoots<'a> { fn drop(&mut self) { STACK_ROOTS.with(|ref r| r.set(None)); } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(thread_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]), } } /// Starts tracking a trace object. unsafe fn root(&self, object: *const dyn JSTraceable) { debug_assert!(thread_state::get().is_script()); (*self.roots.get()).push(object); } /// Stops tracking a trace object, asserting if it isn't found. unsafe fn unroot(&self, object: *const dyn JSTraceable) { debug_assert!(thread_state::get().is_script()); let roots = &mut *self.roots.get(); match roots.iter().rposition(|r| *r == object) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { debug!("tracing stack roots"); STACK_ROOTS.with(|ref collection| { let collection = &*(*collection.get().unwrap()).roots.get(); for root in collection { (**root).trace(tracer); } }); } /// Get a slice of references to DOM objects. pub trait DomSlice<T> where T: JSTraceable + DomObject, { /// Returns the slice of `T` references. fn r(&self) -> &[&T]; } impl<T> DomSlice<T> for [Dom<T>] where T: JSTraceable + DomObject, { #[inline] fn r(&self) -> &[&T] { let _ = mem::transmute::<Dom<T>, &T>; unsafe { &*(self as *const [Dom<T>] as *const [&T]) } } } /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `Dom<T>` /// on the stack, the `Dom<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct Dom<T> { ptr: ptr::NonNull<T>, } // Dom<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> MallocSizeOf for Dom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 } } impl<T> Dom<T> { /// Returns `LayoutDom<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl<T: DomObject> Dom<T> { /// Create a Dom<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: ptr::NonNull::from(obj), } } } impl<T: DomObject> Deref for Dom<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(thread_state::get().is_script()); // We can only have &Dom<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &*self.ptr.as_ptr() } } } unsafe impl<T: DomObject> JSTraceable for Dom<T> { unsafe fn trace(&self, trc: *mut JSTracer) { let trace_string; let trace_info = if cfg!(debug_assertions) { trace_string = format!("for {} on heap", ::std::any::type_name::<T>()); &trace_string[..] } else { "for DOM object on heap" }; trace_reflector(trc, trace_info, (*self.ptr.as_ptr()).reflector()); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutDom<T> { ptr: ptr::NonNull<T>, } impl<T: Castable> LayoutDom<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutDom<U> where U: Castable, T: DerivedFrom<U>, { debug_assert!(thread_state::get().is_layout()); let ptr: *mut T = self.ptr.as_ptr(); LayoutDom { ptr: unsafe { ptr::NonNull::new_unchecked(ptr as *mut U) }, } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutDom<U>> where U: DerivedFrom<T>, { debug_assert!(thread_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>() { let ptr: *mut T = self.ptr.as_ptr(); Some(LayoutDom { ptr: ptr::NonNull::new_unchecked(ptr as *mut U), }) } else { None } } } } impl<T: DomObject> LayoutDom<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(thread_state::get().is_layout()); (*self.ptr.as_ptr()).reflector().get_jsobject().get() } } impl<T> Copy for LayoutDom<T> {} impl<T> PartialEq for Dom<T> { fn eq(&self, other: &Dom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<'a, T: DomObject> PartialEq<&'a T> for Dom<T> { fn eq(&self, other: &&'a T) -> bool { *self == Dom::from_ref(*other) } } impl<T> Eq for Dom<T> {} impl<T> PartialEq for LayoutDom<T> { fn eq(&self, other: &LayoutDom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<T> Eq for LayoutDom<T> {} impl<T> Hash for Dom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Hash for LayoutDom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Clone for Dom<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: self.ptr.clone(), } } } impl<T> Clone for LayoutDom<T> { #[inline] fn clone(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl LayoutDom<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutDom<Node> { debug_assert!(thread_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutDom { ptr: ptr::NonNull::new_unchecked(addr as *const Node as *mut Node), } } } /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`. Essentially a `Cell<Dom<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutDom<T: DomObject> { val: UnsafeCell<Dom<T>>, } impl<T: DomObject> MutDom<T> { /// Create a new `MutDom`. pub fn new(initial: &T) -> MutDom<T> { debug_assert!(thread_state::get().is_script()); MutDom { val: UnsafeCell::new(Dom::from_ref(initial)), } } /// Set this `MutDom` to the given value. pub fn set(&self, val: &T) { debug_assert!(thread_state::get().is_script()); unsafe { *self.val.get() = Dom::from_ref(val); } } /// Get the value in this `MutDom`. pub fn get(&self) -> DomRoot<T> { debug_assert!(thread_state::get().is_script()); unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) } } } impl<T: DomObject> MallocSizeOf for MutDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } impl<T: DomObject> PartialEq for MutDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<Dom<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableDom<T: DomObject> { ptr: UnsafeCell<Option<Dom<T>>>, } impl<T: DomObject> MutNullableDom<T> { /// Create a new `MutNullableDom`. pub fn new(initial: Option<&T>) -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(initial.map(Dom::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> DomRoot<T> where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> { debug_assert!(thread_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<DomRoot<T>> { debug_assert!(thread_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) } } /// Set this `MutNullableDom` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(thread_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| Dom::from_ref(p)); } } /// Gets the current value out of this object and sets it to `None`. pub fn take(&self) -> Option<DomRoot<T>> { let value = self.get(); self.set(None); value } } impl<T: DomObject> PartialEq for MutNullableDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(Dom::from_ref) } } } impl<T: DomObject> Default for MutNullableDom<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(None), } } } impl<T: DomObject> MallocSizeOf for MutNullableDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } /// A holder that allows to lazily initialize the value only once /// `Dom<T>`, using OnceCell /// Essentially a `OnceCell<Dom<T>>`. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] pub struct DomOnceCell<T: DomObject> { ptr: OnceCell<Dom<T>>, } impl<T> DomOnceCell<T> where T: DomObject, { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. #[allow(unrooted_must_root)] pub fn init_once<F>(&self, cb: F) -> &T where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); &self.ptr.init_once(|| Dom::from_ref(&cb())) } } impl<T: DomObject> Default for DomOnceCell<T> { #[allow(unrooted_must_root)] fn default() -> DomOnceCell<T> { debug_assert!(thread_state::get().is_script()); DomOnceCell { ptr: OnceCell::new(), } } } impl<T: DomObject> MallocSizeOf for DomOnceCell<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } #[allow(unrooted_must_root)] unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> { unsafe fn trace(&self, trc: *mut JSTracer) { if let Some(ptr) = self.ptr.as_ref() { ptr.trace(trc); } } } impl<T: DomObject> LayoutDom<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(thread_state::get().is_layout()); self.ptr.as_ptr() } } /// Helper trait for safer manipulations of `Option<Heap<T>>` values. pub trait OptionalHeapSetter { type Value; /// Update this optional heap value with a new value. fn set(&mut self, v: Option<Self::Value>); } impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> where Heap<T>: Default, { type Value = T; fn set(&mut self, v: Option<T>) { let v = match v { None => { *self = None; return; }, Some(v) => v, }; if self.is_none() { *self
size_of
identifier_name
root.rs
v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based rooted value. //! - `DomRoot<T>`: a stack-based reference to a rooted DOM object. //! - `Dom<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `Dom<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `DomRoot<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `DomRoot<T>`. //! use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{DomObject, Reflector}; use crate::dom::bindings::trace::trace_reflector; use crate::dom::bindings::trace::JSTraceable; use crate::dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use mitochondria::OnceCell; use script_layout_interface::TrustedNodeAddress; use std::cell::{Cell, UnsafeCell}; use std::default::Default; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::mem; use std::ops::Deref; use std::ptr; use style::thread_state; /// A rooted value. #[allow(unrooted_must_root)] #[allow_unrooted_interior] pub struct Root<T: StableTraceObject> { /// The value to root. value: T, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T> Root<T> where T: StableTraceObject +'static, { /// Create a new stack-bounded root for the provided value. /// It cannot outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. #[allow(unrooted_must_root)] unsafe fn new(value: T) -> Self { debug_assert!(thread_state::get().is_script()); STACK_ROOTS.with(|ref root_list| { let root_list = &*root_list.get().unwrap(); root_list.root(value.stable_trace_object()); Root { value, root_list } }) } } /// Represents values that can be rooted through a stable address that will /// not change for their whole lifetime. pub unsafe trait StableTraceObject { /// Returns a stable trace object which address won't change for the whole /// lifetime of the value. fn stable_trace_object(&self) -> *const dyn JSTraceable; } unsafe impl<T> StableTraceObject for Dom<T> where T: DomObject, { fn stable_trace_object<'a>(&'a self) -> *const dyn JSTraceable { // The JSTraceable impl for Reflector doesn't actually do anything, // so we need this shenanigan to actually trace the reflector of the // T pointer in Dom<T>. #[allow(unrooted_must_root)] struct ReflectorStackRoot(Reflector); unsafe impl JSTraceable for ReflectorStackRoot { unsafe fn trace(&self, tracer: *mut JSTracer) { trace_reflector(tracer, "on stack", &self.0); } } unsafe { &*(self.reflector() as *const Reflector as *const ReflectorStackRoot) } } } impl<T> Deref for Root<T> where T: Deref + StableTraceObject, { type Target = <T as Deref>::Target; fn deref(&self) -> &Self::Target { debug_assert!(thread_state::get().is_script()); &self.value } } impl<T> Drop for Root<T> where T: StableTraceObject, { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self.value.stable_trace_object()); } } } /// A rooted reference to a DOM object. pub type DomRoot<T> = Root<Dom<T>>; impl<T: Castable> DomRoot<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U> where U: Castable, T: DerivedFrom<U>, { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>> where U: DerivedFrom<T>, { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: DomObject> DomRoot<T> { /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> DomRoot<T> { unsafe { DomRoot::new(Dom::from_ref(unrooted)) } } } impl<T> MallocSizeOf for DomRoot<T> where T: DomObject + MallocSizeOf, { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { (**self).size_of(ops) } } impl<T> PartialEq for DomRoot<T> where T: DomObject, { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl<T> Clone for DomRoot<T> where T: DomObject, { fn clone(&self) -> DomRoot<T> { DomRoot::from_ref(&*self) } } unsafe impl<T> JSTraceable for DomRoot<T> where T: DomObject, { unsafe fn trace(&self, _: *mut JSTracer) { // Already traced. } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const dyn JSTraceable>>, } thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = Cell::new(None)); pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>); impl<'a> ThreadLocalStackRoots<'a> { pub fn new(roots: &'a RootCollection) -> Self { STACK_ROOTS.with(|ref r| r.set(Some(roots))); ThreadLocalStackRoots(PhantomData) } } impl<'a> Drop for ThreadLocalStackRoots<'a> { fn drop(&mut self) { STACK_ROOTS.with(|ref r| r.set(None)); } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(thread_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]), } } /// Starts tracking a trace object. unsafe fn root(&self, object: *const dyn JSTraceable) { debug_assert!(thread_state::get().is_script()); (*self.roots.get()).push(object); } /// Stops tracking a trace object, asserting if it isn't found. unsafe fn unroot(&self, object: *const dyn JSTraceable) { debug_assert!(thread_state::get().is_script()); let roots = &mut *self.roots.get(); match roots.iter().rposition(|r| *r == object) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { debug!("tracing stack roots"); STACK_ROOTS.with(|ref collection| { let collection = &*(*collection.get().unwrap()).roots.get(); for root in collection { (**root).trace(tracer); } }); } /// Get a slice of references to DOM objects. pub trait DomSlice<T> where T: JSTraceable + DomObject, { /// Returns the slice of `T` references. fn r(&self) -> &[&T]; } impl<T> DomSlice<T> for [Dom<T>] where T: JSTraceable + DomObject, { #[inline] fn r(&self) -> &[&T] { let _ = mem::transmute::<Dom<T>, &T>; unsafe { &*(self as *const [Dom<T>] as *const [&T]) } } } /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `Dom<T>` /// on the stack, the `Dom<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct Dom<T> { ptr: ptr::NonNull<T>, } // Dom<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> MallocSizeOf for Dom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 } } impl<T> Dom<T> { /// Returns `LayoutDom<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl<T: DomObject> Dom<T> { /// Create a Dom<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: ptr::NonNull::from(obj), } } } impl<T: DomObject> Deref for Dom<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(thread_state::get().is_script()); // We can only have &Dom<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &*self.ptr.as_ptr() } } } unsafe impl<T: DomObject> JSTraceable for Dom<T> { unsafe fn trace(&self, trc: *mut JSTracer) { let trace_string; let trace_info = if cfg!(debug_assertions) { trace_string = format!("for {} on heap", ::std::any::type_name::<T>()); &trace_string[..] } else { "for DOM object on heap" }; trace_reflector(trc, trace_info, (*self.ptr.as_ptr()).reflector()); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutDom<T> { ptr: ptr::NonNull<T>, } impl<T: Castable> LayoutDom<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutDom<U> where U: Castable, T: DerivedFrom<U>, { debug_assert!(thread_state::get().is_layout()); let ptr: *mut T = self.ptr.as_ptr(); LayoutDom { ptr: unsafe { ptr::NonNull::new_unchecked(ptr as *mut U) }, } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutDom<U>> where U: DerivedFrom<T>, { debug_assert!(thread_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>() { let ptr: *mut T = self.ptr.as_ptr(); Some(LayoutDom { ptr: ptr::NonNull::new_unchecked(ptr as *mut U), }) } else { None } } } } impl<T: DomObject> LayoutDom<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(thread_state::get().is_layout()); (*self.ptr.as_ptr()).reflector().get_jsobject().get() } } impl<T> Copy for LayoutDom<T> {} impl<T> PartialEq for Dom<T> { fn eq(&self, other: &Dom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<'a, T: DomObject> PartialEq<&'a T> for Dom<T> { fn eq(&self, other: &&'a T) -> bool { *self == Dom::from_ref(*other) } } impl<T> Eq for Dom<T> {} impl<T> PartialEq for LayoutDom<T> { fn eq(&self, other: &LayoutDom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<T> Eq for LayoutDom<T> {} impl<T> Hash for Dom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Hash for LayoutDom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Clone for Dom<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: self.ptr.clone(), } } } impl<T> Clone for LayoutDom<T> { #[inline] fn clone(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl LayoutDom<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutDom<Node> { debug_assert!(thread_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutDom {
} /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`. Essentially a `Cell<Dom<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutDom<T: DomObject> { val: UnsafeCell<Dom<T>>, } impl<T: DomObject> MutDom<T> { /// Create a new `MutDom`. pub fn new(initial: &T) -> MutDom<T> { debug_assert!(thread_state::get().is_script()); MutDom { val: UnsafeCell::new(Dom::from_ref(initial)), } } /// Set this `MutDom` to the given value. pub fn set(&self, val: &T) { debug_assert!(thread_state::get().is_script()); unsafe { *self.val.get() = Dom::from_ref(val); } } /// Get the value in this `MutDom`. pub fn get(&self) -> DomRoot<T> { debug_assert!(thread_state::get().is_script()); unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) } } } impl<T: DomObject> MallocSizeOf for MutDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } impl<T: DomObject> PartialEq for MutDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<Dom<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableDom<T: DomObject> { ptr: UnsafeCell<Option<Dom<T>>>, } impl<T: DomObject> MutNullableDom<T> { /// Create a new `MutNullableDom`. pub fn new(initial: Option<&T>) -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(initial.map(Dom::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> DomRoot<T> where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> { debug_assert!(thread_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<DomRoot<T>> { debug_assert!(thread_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) } } /// Set this `MutNullableDom` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(thread_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| Dom::from_ref(p)); } } /// Gets the current value out of this object and sets it to `None`. pub fn take(&self) -> Option<DomRoot<T>> { let value = self.get(); self.set(None); value } } impl<T: DomObject> PartialEq for MutNullableDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(Dom::from_ref) } } } impl<T: DomObject> Default for MutNullableDom<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(None), } } } impl<T: DomObject> MallocSizeOf for MutNullableDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } /// A holder that allows to lazily initialize the value only once /// `Dom<T>`, using OnceCell /// Essentially a `OnceCell<Dom<T>>`. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] pub struct DomOnceCell<T: DomObject> { ptr: OnceCell<Dom<T>>, } impl<T> DomOnceCell<T> where T: DomObject, { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. #[allow(unrooted_must_root)] pub fn init_once<F>(&self, cb: F) -> &T where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); &self.ptr.init_once(|| Dom::from_ref(&cb())) } } impl<T: DomObject> Default for DomOnceCell<T> { #[allow(unrooted_must_root)] fn default() -> DomOnceCell<T> { debug_assert!(thread_state::get().is_script()); DomOnceCell { ptr: OnceCell::new(), } } } impl<T: DomObject> MallocSizeOf for DomOnceCell<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } #[allow(unrooted_must_root)] unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> { unsafe fn trace(&self, trc: *mut JSTracer) { if let Some(ptr) = self.ptr.as_ref() { ptr.trace(trc); } } } impl<T: DomObject> LayoutDom<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(thread_state::get().is_layout()); self.ptr.as_ptr() } } /// Helper trait for safer manipulations of `Option<Heap<T>>` values. pub trait OptionalHeapSetter { type Value; /// Update this optional heap value with a new value. fn set(&mut self, v: Option<Self::Value>); } impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> where Heap<T>: Default, { type Value = T; fn set(&mut self, v: Option<T>) { let v = match v { None => { *self = None; return; }, Some(v) => v, }; if self.is_none() { *self = Some
ptr: ptr::NonNull::new_unchecked(addr as *const Node as *mut Node), } }
random_line_split
root.rs
. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Smart pointers for the JS-managed DOM objects. //! //! The DOM is made up of DOM objects whose lifetime is entirely controlled by //! the whims of the SpiderMonkey garbage collector. The types in this module //! are designed to ensure that any interactions with said Rust types only //! occur on values that will remain alive the entire time. //! //! Here is a brief overview of the important types: //! //! - `Root<T>`: a stack-based rooted value. //! - `DomRoot<T>`: a stack-based reference to a rooted DOM object. //! - `Dom<T>`: a reference to a DOM object that can automatically be traced by //! the GC when encountered as a field of a Rust structure. //! //! `Dom<T>` does not allow access to their inner value without explicitly //! creating a stack-based root via the `root` method. This returns a `DomRoot<T>`, //! which causes the JS-owned value to be uncollectable for the duration of the //! `Root` object's lifetime. A reference to the object can then be obtained //! from the `Root` object. These references are not allowed to outlive their //! originating `DomRoot<T>`. //! use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{DomObject, Reflector}; use crate::dom::bindings::trace::trace_reflector; use crate::dom::bindings::trace::JSTraceable; use crate::dom::node::Node; use js::jsapi::{Heap, JSObject, JSTracer}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use mitochondria::OnceCell; use script_layout_interface::TrustedNodeAddress; use std::cell::{Cell, UnsafeCell}; use std::default::Default; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::mem; use std::ops::Deref; use std::ptr; use style::thread_state; /// A rooted value. #[allow(unrooted_must_root)] #[allow_unrooted_interior] pub struct Root<T: StableTraceObject> { /// The value to root. value: T, /// List that ensures correct dynamic root ordering root_list: *const RootCollection, } impl<T> Root<T> where T: StableTraceObject +'static, { /// Create a new stack-bounded root for the provided value. /// It cannot outlive its associated `RootCollection`, and it gives /// out references which cannot outlive this new `Root`. #[allow(unrooted_must_root)] unsafe fn new(value: T) -> Self { debug_assert!(thread_state::get().is_script()); STACK_ROOTS.with(|ref root_list| { let root_list = &*root_list.get().unwrap(); root_list.root(value.stable_trace_object()); Root { value, root_list } }) } } /// Represents values that can be rooted through a stable address that will /// not change for their whole lifetime. pub unsafe trait StableTraceObject { /// Returns a stable trace object which address won't change for the whole /// lifetime of the value. fn stable_trace_object(&self) -> *const dyn JSTraceable; } unsafe impl<T> StableTraceObject for Dom<T> where T: DomObject, { fn stable_trace_object<'a>(&'a self) -> *const dyn JSTraceable { // The JSTraceable impl for Reflector doesn't actually do anything, // so we need this shenanigan to actually trace the reflector of the // T pointer in Dom<T>. #[allow(unrooted_must_root)] struct ReflectorStackRoot(Reflector); unsafe impl JSTraceable for ReflectorStackRoot { unsafe fn trace(&self, tracer: *mut JSTracer) { trace_reflector(tracer, "on stack", &self.0); } } unsafe { &*(self.reflector() as *const Reflector as *const ReflectorStackRoot) } } } impl<T> Deref for Root<T> where T: Deref + StableTraceObject, { type Target = <T as Deref>::Target; fn deref(&self) -> &Self::Target { debug_assert!(thread_state::get().is_script()); &self.value } } impl<T> Drop for Root<T> where T: StableTraceObject, { fn drop(&mut self) { unsafe { (*self.root_list).unroot(self.value.stable_trace_object()); } } } /// A rooted reference to a DOM object. pub type DomRoot<T> = Root<Dom<T>>; impl<T: Castable> DomRoot<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U> where U: Castable, T: DerivedFrom<U>, { unsafe { mem::transmute(root) } } /// Cast a DOM object root downwards to one of the interfaces it might implement. pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>> where U: DerivedFrom<T>, { if root.is::<U>() { Some(unsafe { mem::transmute(root) }) } else { None } } } impl<T: DomObject> DomRoot<T> { /// Generate a new root from a reference pub fn from_ref(unrooted: &T) -> DomRoot<T> { unsafe { DomRoot::new(Dom::from_ref(unrooted)) } } } impl<T> MallocSizeOf for DomRoot<T> where T: DomObject + MallocSizeOf, { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { (**self).size_of(ops) } } impl<T> PartialEq for DomRoot<T> where T: DomObject, { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl<T> Clone for DomRoot<T> where T: DomObject, { fn clone(&self) -> DomRoot<T> { DomRoot::from_ref(&*self) } } unsafe impl<T> JSTraceable for DomRoot<T> where T: DomObject, { unsafe fn trace(&self, _: *mut JSTracer) { // Already traced. } } /// A rooting mechanism for reflectors on the stack. /// LIFO is not required. /// /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { roots: UnsafeCell<Vec<*const dyn JSTraceable>>, } thread_local!(static STACK_ROOTS: Cell<Option<*const RootCollection>> = Cell::new(None)); pub struct ThreadLocalStackRoots<'a>(PhantomData<&'a u32>); impl<'a> ThreadLocalStackRoots<'a> { pub fn new(roots: &'a RootCollection) -> Self { STACK_ROOTS.with(|ref r| r.set(Some(roots))); ThreadLocalStackRoots(PhantomData) } } impl<'a> Drop for ThreadLocalStackRoots<'a> { fn drop(&mut self) { STACK_ROOTS.with(|ref r| r.set(None)); } } impl RootCollection { /// Create an empty collection of roots pub fn new() -> RootCollection { debug_assert!(thread_state::get().is_script()); RootCollection { roots: UnsafeCell::new(vec![]), } } /// Starts tracking a trace object. unsafe fn root(&self, object: *const dyn JSTraceable)
/// Stops tracking a trace object, asserting if it isn't found. unsafe fn unroot(&self, object: *const dyn JSTraceable) { debug_assert!(thread_state::get().is_script()); let roots = &mut *self.roots.get(); match roots.iter().rposition(|r| *r == object) { Some(idx) => { roots.remove(idx); }, None => panic!("Can't remove a root that was never rooted!"), } } } /// SM Callback that traces the rooted reflectors pub unsafe fn trace_roots(tracer: *mut JSTracer) { debug!("tracing stack roots"); STACK_ROOTS.with(|ref collection| { let collection = &*(*collection.get().unwrap()).roots.get(); for root in collection { (**root).trace(tracer); } }); } /// Get a slice of references to DOM objects. pub trait DomSlice<T> where T: JSTraceable + DomObject, { /// Returns the slice of `T` references. fn r(&self) -> &[&T]; } impl<T> DomSlice<T> for [Dom<T>] where T: JSTraceable + DomObject, { #[inline] fn r(&self) -> &[&T] { let _ = mem::transmute::<Dom<T>, &T>; unsafe { &*(self as *const [Dom<T>] as *const [&T]) } } } /// A traced reference to a DOM object /// /// This type is critical to making garbage collection work with the DOM, /// but it is very dangerous; if garbage collection happens with a `Dom<T>` /// on the stack, the `Dom<T>` can point to freed memory. /// /// This should only be used as a field in other DOM objects. #[must_root] pub struct Dom<T> { ptr: ptr::NonNull<T>, } // Dom<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // For now, we choose not to follow any such pointers. impl<T> MallocSizeOf for Dom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { 0 } } impl<T> Dom<T> { /// Returns `LayoutDom<T>` containing the same pointer. pub unsafe fn to_layout(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl<T: DomObject> Dom<T> { /// Create a Dom<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: ptr::NonNull::from(obj), } } } impl<T: DomObject> Deref for Dom<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(thread_state::get().is_script()); // We can only have &Dom<T> from a rooted thing, so it's safe to deref // it to &T. unsafe { &*self.ptr.as_ptr() } } } unsafe impl<T: DomObject> JSTraceable for Dom<T> { unsafe fn trace(&self, trc: *mut JSTracer) { let trace_string; let trace_info = if cfg!(debug_assertions) { trace_string = format!("for {} on heap", ::std::any::type_name::<T>()); &trace_string[..] } else { "for DOM object on heap" }; trace_reflector(trc, trace_info, (*self.ptr.as_ptr()).reflector()); } } /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// traits must be implemented on this. #[allow_unrooted_interior] pub struct LayoutDom<T> { ptr: ptr::NonNull<T>, } impl<T: Castable> LayoutDom<T> { /// Cast a DOM object root upwards to one of the interfaces it derives from. pub fn upcast<U>(&self) -> LayoutDom<U> where U: Castable, T: DerivedFrom<U>, { debug_assert!(thread_state::get().is_layout()); let ptr: *mut T = self.ptr.as_ptr(); LayoutDom { ptr: unsafe { ptr::NonNull::new_unchecked(ptr as *mut U) }, } } /// Cast a DOM object downwards to one of the interfaces it might implement. pub fn downcast<U>(&self) -> Option<LayoutDom<U>> where U: DerivedFrom<T>, { debug_assert!(thread_state::get().is_layout()); unsafe { if (*self.unsafe_get()).is::<U>() { let ptr: *mut T = self.ptr.as_ptr(); Some(LayoutDom { ptr: ptr::NonNull::new_unchecked(ptr as *mut U), }) } else { None } } } } impl<T: DomObject> LayoutDom<T> { /// Get the reflector. pub unsafe fn get_jsobject(&self) -> *mut JSObject { debug_assert!(thread_state::get().is_layout()); (*self.ptr.as_ptr()).reflector().get_jsobject().get() } } impl<T> Copy for LayoutDom<T> {} impl<T> PartialEq for Dom<T> { fn eq(&self, other: &Dom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<'a, T: DomObject> PartialEq<&'a T> for Dom<T> { fn eq(&self, other: &&'a T) -> bool { *self == Dom::from_ref(*other) } } impl<T> Eq for Dom<T> {} impl<T> PartialEq for LayoutDom<T> { fn eq(&self, other: &LayoutDom<T>) -> bool { self.ptr.as_ptr() == other.ptr.as_ptr() } } impl<T> Eq for LayoutDom<T> {} impl<T> Hash for Dom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Hash for LayoutDom<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.ptr.as_ptr().hash(state) } } impl<T> Clone for Dom<T> { #[inline] #[allow(unrooted_must_root)] fn clone(&self) -> Dom<T> { debug_assert!(thread_state::get().is_script()); Dom { ptr: self.ptr.clone(), } } } impl<T> Clone for LayoutDom<T> { #[inline] fn clone(&self) -> LayoutDom<T> { debug_assert!(thread_state::get().is_layout()); LayoutDom { ptr: self.ptr.clone(), } } } impl LayoutDom<Node> { /// Create a new JS-owned value wrapped from an address known to be a /// `Node` pointer. pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutDom<Node> { debug_assert!(thread_state::get().is_layout()); let TrustedNodeAddress(addr) = inner; LayoutDom { ptr: ptr::NonNull::new_unchecked(addr as *const Node as *mut Node), } } } /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`. Essentially a `Cell<Dom<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutDom<T: DomObject> { val: UnsafeCell<Dom<T>>, } impl<T: DomObject> MutDom<T> { /// Create a new `MutDom`. pub fn new(initial: &T) -> MutDom<T> { debug_assert!(thread_state::get().is_script()); MutDom { val: UnsafeCell::new(Dom::from_ref(initial)), } } /// Set this `MutDom` to the given value. pub fn set(&self, val: &T) { debug_assert!(thread_state::get().is_script()); unsafe { *self.val.get() = Dom::from_ref(val); } } /// Get the value in this `MutDom`. pub fn get(&self) -> DomRoot<T> { debug_assert!(thread_state::get().is_script()); unsafe { DomRoot::from_ref(&*ptr::read(self.val.get())) } } } impl<T: DomObject> MallocSizeOf for MutDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } impl<T: DomObject> PartialEq for MutDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.val.get() == *other.val.get() } } } impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> { fn eq(&self, other: &T) -> bool { unsafe { **self.val.get() == *other } } } /// A holder that provides interior mutability for GC-managed values such as /// `Dom<T>`, with nullability represented by an enclosing Option wrapper. /// Essentially a `Cell<Option<Dom<T>>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutNullableDom<T: DomObject> { ptr: UnsafeCell<Option<Dom<T>>>, } impl<T: DomObject> MutNullableDom<T> { /// Create a new `MutNullableDom`. pub fn new(initial: Option<&T>) -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(initial.map(Dom::from_ref)), } } /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. pub fn or_init<F>(&self, cb: F) -> DomRoot<T> where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); match self.get() { Some(inner) => inner, None => { let inner = cb(); self.set(Some(&inner)); inner }, } } /// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`. /// For use by layout, which can't use safe types like Temporary. #[allow(unrooted_must_root)] pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> { debug_assert!(thread_state::get().is_layout()); ptr::read(self.ptr.get()).map(|js| js.to_layout()) } /// Get a rooted value out of this object #[allow(unrooted_must_root)] pub fn get(&self) -> Option<DomRoot<T>> { debug_assert!(thread_state::get().is_script()); unsafe { ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o)) } } /// Set this `MutNullableDom` to the given value. pub fn set(&self, val: Option<&T>) { debug_assert!(thread_state::get().is_script()); unsafe { *self.ptr.get() = val.map(|p| Dom::from_ref(p)); } } /// Gets the current value out of this object and sets it to `None`. pub fn take(&self) -> Option<DomRoot<T>> { let value = self.get(); self.set(None); value } } impl<T: DomObject> PartialEq for MutNullableDom<T> { fn eq(&self, other: &Self) -> bool { unsafe { *self.ptr.get() == *other.ptr.get() } } } impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> { fn eq(&self, other: &Option<&T>) -> bool { unsafe { *self.ptr.get() == other.map(Dom::from_ref) } } } impl<T: DomObject> Default for MutNullableDom<T> { #[allow(unrooted_must_root)] fn default() -> MutNullableDom<T> { debug_assert!(thread_state::get().is_script()); MutNullableDom { ptr: UnsafeCell::new(None), } } } impl<T: DomObject> MallocSizeOf for MutNullableDom<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } /// A holder that allows to lazily initialize the value only once /// `Dom<T>`, using OnceCell /// Essentially a `OnceCell<Dom<T>>`. /// /// This should only be used as a field in other DOM objects; see warning /// on `Dom<T>`. #[must_root] pub struct DomOnceCell<T: DomObject> { ptr: OnceCell<Dom<T>>, } impl<T> DomOnceCell<T> where T: DomObject, { /// Retrieve a copy of the current inner value. If it is `None`, it is /// initialized with the result of `cb` first. #[allow(unrooted_must_root)] pub fn init_once<F>(&self, cb: F) -> &T where F: FnOnce() -> DomRoot<T>, { debug_assert!(thread_state::get().is_script()); &self.ptr.init_once(|| Dom::from_ref(&cb())) } } impl<T: DomObject> Default for DomOnceCell<T> { #[allow(unrooted_must_root)] fn default() -> DomOnceCell<T> { debug_assert!(thread_state::get().is_script()); DomOnceCell { ptr: OnceCell::new(), } } } impl<T: DomObject> MallocSizeOf for DomOnceCell<T> { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // See comment on MallocSizeOf for Dom<T>. 0 } } #[allow(unrooted_must_root)] unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> { unsafe fn trace(&self, trc: *mut JSTracer) { if let Some(ptr) = self.ptr.as_ref() { ptr.trace(trc); } } } impl<T: DomObject> LayoutDom<T> { /// Returns an unsafe pointer to the interior of this JS object. This is /// the only method that be safely accessed from layout. (The fact that /// this is unsafe is what necessitates the layout wrappers.) pub unsafe fn unsafe_get(&self) -> *const T { debug_assert!(thread_state::get().is_layout()); self.ptr.as_ptr() } } /// Helper trait for safer manipulations of `Option<Heap<T>>` values. pub trait OptionalHeapSetter { type Value; /// Update this optional heap value with a new value. fn set(&mut self, v: Option<Self::Value>); } impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> where Heap<T>: Default, { type Value = T; fn set(&mut self, v: Option<T>) { let v = match v { None => { *self = None; return; }, Some(v) => v, }; if self.is_none() { *self
{ debug_assert!(thread_state::get().is_script()); (*self.roots.get()).push(object); }
identifier_body
A.rs
fn main(){ let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let n = s.trim().parse::<i32>().unwrap(); let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let a = s.trim().parse::<i32>().unwrap(); let ten = ((n / 10) % 10) * 10 + (n % 10); let hund = ((n / 100) % 10) * 100 + ((n / 10) % 10) * 10 + (n % 10); let hyaku = ((n / 100) % 10) > 5; if ((n / 100) % 100) % 5 == 0
else if hyaku { println!("{}", if a - (hund - 500) >= 0 { "Yes" } else { "No" }); } else { println!("{}", if a - hund >= 0 { "Yes" } else { "No" }); } }
{ println!("{}", if a - ten >= 0 { "Yes" } else { "No" }); }
conditional_block
A.rs
fn main(){ let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let n = s.trim().parse::<i32>().unwrap(); let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let a = s.trim().parse::<i32>().unwrap(); let ten = ((n / 10) % 10) * 10 + (n % 10);
let hund = ((n / 100) % 10) * 100 + ((n / 10) % 10) * 10 + (n % 10); let hyaku = ((n / 100) % 10) > 5; if ((n / 100) % 100) % 5 == 0 { println!("{}", if a - ten >= 0 { "Yes" } else { "No" }); } else if hyaku { println!("{}", if a - (hund - 500) >= 0 { "Yes" } else { "No" }); } else { println!("{}", if a - hund >= 0 { "Yes" } else { "No" }); } }
random_line_split
A.rs
fn
(){ let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let n = s.trim().parse::<i32>().unwrap(); let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let a = s.trim().parse::<i32>().unwrap(); let ten = ((n / 10) % 10) * 10 + (n % 10); let hund = ((n / 100) % 10) * 100 + ((n / 10) % 10) * 10 + (n % 10); let hyaku = ((n / 100) % 10) > 5; if ((n / 100) % 100) % 5 == 0 { println!("{}", if a - ten >= 0 { "Yes" } else { "No" }); } else if hyaku { println!("{}", if a - (hund - 500) >= 0 { "Yes" } else { "No" }); } else { println!("{}", if a - hund >= 0 { "Yes" } else { "No" }); } }
main
identifier_name
A.rs
fn main()
{ let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let n = s.trim().parse::<i32>().unwrap(); let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); let a = s.trim().parse::<i32>().unwrap(); let ten = ((n / 10) % 10) * 10 + (n % 10); let hund = ((n / 100) % 10) * 100 + ((n / 10) % 10) * 10 + (n % 10); let hyaku = ((n / 100) % 10) > 5; if ((n / 100) % 100) % 5 == 0 { println!("{}", if a - ten >= 0 { "Yes" } else { "No" }); } else if hyaku { println!("{}", if a - (hund - 500) >= 0 { "Yes" } else { "No" }); } else { println!("{}", if a - hund >= 0 { "Yes" } else { "No" }); } }
identifier_body
buffer.rs
use buffer::{Content, BufferView, BufferViewAny, BufferType, BufferCreationError}; use uniforms::{AsUniformValue, UniformBlock, UniformValue, LayoutMismatchError}; use program; use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block. #[derive(Debug)] pub struct
<T:?Sized> where T: Content { buffer: BufferView<T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy { /// Uploads data in the uniforms buffer. pub fn new<F>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::new(facade, &data, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } /// Creates an empty buffer. pub fn empty<F>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::empty(facade, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } } impl<T:?Sized> UniformBuffer<T> where T: Content { /// Creates an empty buffer. /// /// # Panic /// /// Panicks if the size passed as parameter is not suitable for the type of data. /// pub fn empty_unsized<F>(facade: &F, size: usize) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::empty_unsized(facade, BufferType::UniformBuffer, size, true)); Ok(UniformBuffer { buffer: buffer, }) } } impl<T:?Sized> Deref for UniformBuffer<T> where T: Content { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<T:?Sized> DerefMut for UniformBuffer<T> where T: Content { fn deref_mut(&mut self) -> &mut BufferView<T> { &mut self.buffer } } impl<'a, T:?Sized> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Content { fn as_uniform_value(&self) -> UniformValue { fn f<T:?Sized>(block: &program::UniformBlock) -> Result<(), LayoutMismatchError> where T: UniformBlock + Content { // TODO: more checks? T::matches(&block.layout, 0) } UniformValue::Block(self.buffer.as_slice_any(), f::<T>) } }
UniformBuffer
identifier_name
buffer.rs
use buffer::{Content, BufferView, BufferViewAny, BufferType, BufferCreationError}; use uniforms::{AsUniformValue, UniformBlock, UniformValue, LayoutMismatchError}; use program; use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block. #[derive(Debug)] pub struct UniformBuffer<T:?Sized> where T: Content { buffer: BufferView<T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy { /// Uploads data in the uniforms buffer. pub fn new<F>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::new(facade, &data, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } /// Creates an empty buffer. pub fn empty<F>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::empty(facade, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } } impl<T:?Sized> UniformBuffer<T> where T: Content { /// Creates an empty buffer. /// /// # Panic /// /// Panicks if the size passed as parameter is not suitable for the type of data. /// pub fn empty_unsized<F>(facade: &F, size: usize) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade
} impl<T:?Sized> Deref for UniformBuffer<T> where T: Content { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<T:?Sized> DerefMut for UniformBuffer<T> where T: Content { fn deref_mut(&mut self) -> &mut BufferView<T> { &mut self.buffer } } impl<'a, T:?Sized> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Content { fn as_uniform_value(&self) -> UniformValue { fn f<T:?Sized>(block: &program::UniformBlock) -> Result<(), LayoutMismatchError> where T: UniformBlock + Content { // TODO: more checks? T::matches(&block.layout, 0) } UniformValue::Block(self.buffer.as_slice_any(), f::<T>) } }
{ let buffer = try!(BufferView::empty_unsized(facade, BufferType::UniformBuffer, size, true)); Ok(UniformBuffer { buffer: buffer, }) }
identifier_body
buffer.rs
use buffer::{Content, BufferView, BufferViewAny, BufferType, BufferCreationError}; use uniforms::{AsUniformValue, UniformBlock, UniformValue, LayoutMismatchError}; use program; use std::ops::{Deref, DerefMut}; use backend::Facade; /// Buffer that contains a uniform block. #[derive(Debug)] pub struct UniformBuffer<T:?Sized> where T: Content { buffer: BufferView<T>, } /// Same as `UniformBuffer` but doesn't contain any information about the type. #[derive(Debug)] pub struct TypelessUniformBuffer { buffer: BufferViewAny, } impl<T> UniformBuffer<T> where T: Copy { /// Uploads data in the uniforms buffer. pub fn new<F>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::new(facade, &data, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } /// Creates an empty buffer. pub fn empty<F>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::empty(facade, BufferType::UniformBuffer, true)); Ok(UniformBuffer { buffer: buffer, }) } } impl<T:?Sized> UniformBuffer<T> where T: Content { /// Creates an empty buffer. /// /// # Panic /// /// Panicks if the size passed as parameter is not suitable for the type of data. /// pub fn empty_unsized<F>(facade: &F, size: usize) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade { let buffer = try!(BufferView::empty_unsized(facade, BufferType::UniformBuffer, size, true)); Ok(UniformBuffer { buffer: buffer, }) } } impl<T:?Sized> Deref for UniformBuffer<T> where T: Content { type Target = BufferView<T>; fn deref(&self) -> &BufferView<T> { &self.buffer } } impl<T:?Sized> DerefMut for UniformBuffer<T> where T: Content { fn deref_mut(&mut self) -> &mut BufferView<T> { &mut self.buffer } } impl<'a, T:?Sized> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Content { fn as_uniform_value(&self) -> UniformValue { fn f<T:?Sized>(block: &program::UniformBlock) -> Result<(), LayoutMismatchError> where T: UniformBlock + Content { // TODO: more checks? T::matches(&block.layout, 0) } UniformValue::Block(self.buffer.as_slice_any(), f::<T>) }
}
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. extern crate multihash; extern crate cid; extern crate unicase; extern crate rlp; extern crate ethcore; extern crate ethcore_bigint as bigint; extern crate ethcore_bytes as bytes; extern crate jsonrpc_core as core; extern crate jsonrpc_http_server as http; pub mod error; mod route; use std::thread; use std::sync::{mpsc, Arc}; use std::net::{SocketAddr, IpAddr}; use core::futures::future::{self, FutureResult}; use core::futures::{self, Future}; use ethcore::client::BlockChainClient; use http::hyper::header::{self, Vary, ContentType}; use http::hyper::{Method, StatusCode}; use http::hyper::{self, server}; use unicase::Ascii; use error::ServerError; use route::Out; pub use http::{AccessControlAllowOrigin, Host, DomainsValidation}; /// Request/response handler pub struct IpfsHandler { /// Allowed CORS domains cors_domains: Option<Vec<AccessControlAllowOrigin>>, /// Hostnames allowed in the `Host` request header allowed_hosts: Option<Vec<Host>>, /// Reference to the Blockchain Client client: Arc<BlockChainClient>, } impl IpfsHandler { pub fn client(&self) -> &BlockChainClient { &*self.client } pub fn new(cors: DomainsValidation<AccessControlAllowOrigin>, hosts: DomainsValidation<Host>, client: Arc<BlockChainClient>) -> Self { IpfsHandler { cors_domains: cors.into(), allowed_hosts: hosts.into(), client: client, } } pub fn on_request(&self, req: hyper::Request) -> (Option<header::AccessControlAllowOrigin>, Out) { match *req.method() { Method::Get | Method::Post => {}, _ => return (None, Out::Bad("Invalid Request")), } if!http::is_host_allowed(&req, &self.allowed_hosts) { return (None, Out::Bad("Disallowed Host header")); } let cors_header = http::cors_header(&req, &self.cors_domains); if cors_header == http::CorsHeader::Invalid { return (None, Out::Bad("Disallowed Origin header")); } let path = req.uri().path(); let query = req.uri().query(); return (cors_header.into(), self.route(path, query)); } } impl server::Service for IpfsHandler { type Request = hyper::Request; type Response = hyper::Response; type Error = hyper::Error; type Future = FutureResult<hyper::Response, hyper::Error>; fn call(&self, request: Self::Request) -> Self::Future { let (cors_header, out) = self.on_request(request); let mut res = match out { Out::OctetStream(bytes) => { hyper::Response::new() .with_status(StatusCode::Ok) .with_header(ContentType::octet_stream()) .with_body(bytes) }, Out::NotFound(reason) => { hyper::Response::new() .with_status(StatusCode::NotFound) .with_header(ContentType::plaintext()) .with_body(reason)
.with_status(StatusCode::BadRequest) .with_header(ContentType::plaintext()) .with_body(reason) } }; if let Some(cors_header) = cors_header { res.headers_mut().set(cors_header); res.headers_mut().set(Vary::Items(vec![Ascii::new("Origin".into())])); } future::ok(res) } } /// Add current interface (default: "127.0.0.1:5001") to list of allowed hosts fn include_current_interface(mut hosts: Vec<Host>, interface: String, port: u16) -> Vec<Host> { hosts.push(match port { 80 => interface, _ => format!("{}:{}", interface, port), }.into()); hosts } #[derive(Debug)] pub struct Listening { close: Option<futures::sync::oneshot::Sender<()>>, thread: Option<thread::JoinHandle<()>>, } impl Drop for Listening { fn drop(&mut self) { self.close.take().unwrap().send(()).unwrap(); let _ = self.thread.take().unwrap().join(); } } pub fn start_server( port: u16, interface: String, cors: DomainsValidation<AccessControlAllowOrigin>, hosts: DomainsValidation<Host>, client: Arc<BlockChainClient> ) -> Result<Listening, ServerError> { let ip: IpAddr = interface.parse().map_err(|_| ServerError::InvalidInterface)?; let addr = SocketAddr::new(ip, port); let hosts: Option<Vec<_>> = hosts.into(); let hosts: DomainsValidation<_> = hosts.map(move |hosts| include_current_interface(hosts, interface, port)).into(); let (close, shutdown_signal) = futures::sync::oneshot::channel::<()>(); let (tx, rx) = mpsc::sync_channel(1); let thread = thread::spawn(move || { let send = |res| tx.send(res).expect("rx end is never dropped; qed"); let server = match server::Http::new().bind(&addr, move || { Ok(IpfsHandler::new(cors.clone(), hosts.clone(), client.clone())) }) { Ok(server) => { send(Ok(())); server }, Err(err) => { send(Err(err)); return; } }; let _ = server.run_until(shutdown_signal.map_err(|_| {})); }); // Wait for server to start successfuly. rx.recv().expect("tx end is never dropped; qed")?; Ok(Listening { close: close.into(), thread: thread.into(), }) }
}, Out::Bad(reason) => { hyper::Response::new()
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. extern crate multihash; extern crate cid; extern crate unicase; extern crate rlp; extern crate ethcore; extern crate ethcore_bigint as bigint; extern crate ethcore_bytes as bytes; extern crate jsonrpc_core as core; extern crate jsonrpc_http_server as http; pub mod error; mod route; use std::thread; use std::sync::{mpsc, Arc}; use std::net::{SocketAddr, IpAddr}; use core::futures::future::{self, FutureResult}; use core::futures::{self, Future}; use ethcore::client::BlockChainClient; use http::hyper::header::{self, Vary, ContentType}; use http::hyper::{Method, StatusCode}; use http::hyper::{self, server}; use unicase::Ascii; use error::ServerError; use route::Out; pub use http::{AccessControlAllowOrigin, Host, DomainsValidation}; /// Request/response handler pub struct IpfsHandler { /// Allowed CORS domains cors_domains: Option<Vec<AccessControlAllowOrigin>>, /// Hostnames allowed in the `Host` request header allowed_hosts: Option<Vec<Host>>, /// Reference to the Blockchain Client client: Arc<BlockChainClient>, } impl IpfsHandler { pub fn
(&self) -> &BlockChainClient { &*self.client } pub fn new(cors: DomainsValidation<AccessControlAllowOrigin>, hosts: DomainsValidation<Host>, client: Arc<BlockChainClient>) -> Self { IpfsHandler { cors_domains: cors.into(), allowed_hosts: hosts.into(), client: client, } } pub fn on_request(&self, req: hyper::Request) -> (Option<header::AccessControlAllowOrigin>, Out) { match *req.method() { Method::Get | Method::Post => {}, _ => return (None, Out::Bad("Invalid Request")), } if!http::is_host_allowed(&req, &self.allowed_hosts) { return (None, Out::Bad("Disallowed Host header")); } let cors_header = http::cors_header(&req, &self.cors_domains); if cors_header == http::CorsHeader::Invalid { return (None, Out::Bad("Disallowed Origin header")); } let path = req.uri().path(); let query = req.uri().query(); return (cors_header.into(), self.route(path, query)); } } impl server::Service for IpfsHandler { type Request = hyper::Request; type Response = hyper::Response; type Error = hyper::Error; type Future = FutureResult<hyper::Response, hyper::Error>; fn call(&self, request: Self::Request) -> Self::Future { let (cors_header, out) = self.on_request(request); let mut res = match out { Out::OctetStream(bytes) => { hyper::Response::new() .with_status(StatusCode::Ok) .with_header(ContentType::octet_stream()) .with_body(bytes) }, Out::NotFound(reason) => { hyper::Response::new() .with_status(StatusCode::NotFound) .with_header(ContentType::plaintext()) .with_body(reason) }, Out::Bad(reason) => { hyper::Response::new() .with_status(StatusCode::BadRequest) .with_header(ContentType::plaintext()) .with_body(reason) } }; if let Some(cors_header) = cors_header { res.headers_mut().set(cors_header); res.headers_mut().set(Vary::Items(vec![Ascii::new("Origin".into())])); } future::ok(res) } } /// Add current interface (default: "127.0.0.1:5001") to list of allowed hosts fn include_current_interface(mut hosts: Vec<Host>, interface: String, port: u16) -> Vec<Host> { hosts.push(match port { 80 => interface, _ => format!("{}:{}", interface, port), }.into()); hosts } #[derive(Debug)] pub struct Listening { close: Option<futures::sync::oneshot::Sender<()>>, thread: Option<thread::JoinHandle<()>>, } impl Drop for Listening { fn drop(&mut self) { self.close.take().unwrap().send(()).unwrap(); let _ = self.thread.take().unwrap().join(); } } pub fn start_server( port: u16, interface: String, cors: DomainsValidation<AccessControlAllowOrigin>, hosts: DomainsValidation<Host>, client: Arc<BlockChainClient> ) -> Result<Listening, ServerError> { let ip: IpAddr = interface.parse().map_err(|_| ServerError::InvalidInterface)?; let addr = SocketAddr::new(ip, port); let hosts: Option<Vec<_>> = hosts.into(); let hosts: DomainsValidation<_> = hosts.map(move |hosts| include_current_interface(hosts, interface, port)).into(); let (close, shutdown_signal) = futures::sync::oneshot::channel::<()>(); let (tx, rx) = mpsc::sync_channel(1); let thread = thread::spawn(move || { let send = |res| tx.send(res).expect("rx end is never dropped; qed"); let server = match server::Http::new().bind(&addr, move || { Ok(IpfsHandler::new(cors.clone(), hosts.clone(), client.clone())) }) { Ok(server) => { send(Ok(())); server }, Err(err) => { send(Err(err)); return; } }; let _ = server.run_until(shutdown_signal.map_err(|_| {})); }); // Wait for server to start successfuly. rx.recv().expect("tx end is never dropped; qed")?; Ok(Listening { close: close.into(), thread: thread.into(), }) }
client
identifier_name
complex.rs
extern crate iron; extern crate session; extern crate rustc_serialize; use iron::prelude::*; use session::*; // To run, $ cargo run --example complex // to use, $ curl "http://localhost:3000/login" // $ curl "http://localhost:3000/show_count" // $ curl "http://localhost:3000/reset_count" // $ curl "http://localhost:3000/clear_allA" #[derive(Debug,RustcEncodable, RustcDecodable)] struct Account { id: usize, name: Option<String>, email: Option<String>, } fn main() { let mut chain = Chain::new(handle); let signing_key = "key-123456"; let expire_seconds = 3600; let connect_str = "redis://localhost"; chain.around(session::Session::new(signing_key, expire_seconds, connect_str)); Iron::new(chain).http("localhost:3000").unwrap(); } fn get_action(req: &Request) -> String { String::from(req.url.path()[0]) } fn handle(req: &mut Request) -> IronResult<Response> { let action = get_action(req); match action.as_str() { "login" => login(req), "clear_all" => clear_all(req), "show_count" => show_count(req), "reset_count" => reset_count(req), _ => Ok(Response::with((iron::status::Ok, "login,logout,show_count,reset_count"))), } } fn login(req: &mut Request) -> IronResult<Response> { let account = match req.get_session::<Account>("account") { Ok(a) => a, Err(_) => { let account = Account { id: 1, name: Some("alex".to_owned()), email: None, }; req.set_session("account", &account).unwrap(); account } }; let content = format!("user:{:?}", &account); Ok(Response::with((iron::status::Ok, content))) } fn clear_all(req: &mut Request) -> IronResult<Response> { req.clear_session().unwrap(); Ok(Response::with((iron::status::Ok, "clear all"))) } fn show_count(req: &mut Request) -> IronResult<Response>
fn reset_count(req: &mut Request) -> IronResult<Response> { req.remove_session("count").unwrap(); Ok(Response::with((iron::status::Ok, "count reset"))) }
{ let mut count = req.get_session::<usize>("count").unwrap_or(0); count += 1; req.set_session("count", &count).unwrap(); Ok(Response::with((iron::status::Ok, format!("count:{}", &count)))) }
identifier_body
complex.rs
extern crate iron; extern crate session; extern crate rustc_serialize; use iron::prelude::*; use session::*; // To run, $ cargo run --example complex // to use, $ curl "http://localhost:3000/login" // $ curl "http://localhost:3000/show_count" // $ curl "http://localhost:3000/reset_count" // $ curl "http://localhost:3000/clear_allA" #[derive(Debug,RustcEncodable, RustcDecodable)] struct Account { id: usize, name: Option<String>, email: Option<String>, } fn
() { let mut chain = Chain::new(handle); let signing_key = "key-123456"; let expire_seconds = 3600; let connect_str = "redis://localhost"; chain.around(session::Session::new(signing_key, expire_seconds, connect_str)); Iron::new(chain).http("localhost:3000").unwrap(); } fn get_action(req: &Request) -> String { String::from(req.url.path()[0]) } fn handle(req: &mut Request) -> IronResult<Response> { let action = get_action(req); match action.as_str() { "login" => login(req), "clear_all" => clear_all(req), "show_count" => show_count(req), "reset_count" => reset_count(req), _ => Ok(Response::with((iron::status::Ok, "login,logout,show_count,reset_count"))), } } fn login(req: &mut Request) -> IronResult<Response> { let account = match req.get_session::<Account>("account") { Ok(a) => a, Err(_) => { let account = Account { id: 1, name: Some("alex".to_owned()), email: None, }; req.set_session("account", &account).unwrap(); account } }; let content = format!("user:{:?}", &account); Ok(Response::with((iron::status::Ok, content))) } fn clear_all(req: &mut Request) -> IronResult<Response> { req.clear_session().unwrap(); Ok(Response::with((iron::status::Ok, "clear all"))) } fn show_count(req: &mut Request) -> IronResult<Response> { let mut count = req.get_session::<usize>("count").unwrap_or(0); count += 1; req.set_session("count", &count).unwrap(); Ok(Response::with((iron::status::Ok, format!("count:{}", &count)))) } fn reset_count(req: &mut Request) -> IronResult<Response> { req.remove_session("count").unwrap(); Ok(Response::with((iron::status::Ok, "count reset"))) }
main
identifier_name
complex.rs
extern crate iron; extern crate session; extern crate rustc_serialize; use iron::prelude::*; use session::*; // To run, $ cargo run --example complex // to use, $ curl "http://localhost:3000/login" // $ curl "http://localhost:3000/show_count" // $ curl "http://localhost:3000/reset_count" // $ curl "http://localhost:3000/clear_allA" #[derive(Debug,RustcEncodable, RustcDecodable)] struct Account { id: usize, name: Option<String>, email: Option<String>, } fn main() { let mut chain = Chain::new(handle); let signing_key = "key-123456"; let expire_seconds = 3600; let connect_str = "redis://localhost"; chain.around(session::Session::new(signing_key, expire_seconds, connect_str)); Iron::new(chain).http("localhost:3000").unwrap(); } fn get_action(req: &Request) -> String { String::from(req.url.path()[0]) } fn handle(req: &mut Request) -> IronResult<Response> { let action = get_action(req); match action.as_str() { "login" => login(req), "clear_all" => clear_all(req), "show_count" => show_count(req), "reset_count" => reset_count(req), _ => Ok(Response::with((iron::status::Ok, "login,logout,show_count,reset_count"))), } } fn login(req: &mut Request) -> IronResult<Response> { let account = match req.get_session::<Account>("account") { Ok(a) => a, Err(_) => { let account = Account { id: 1, name: Some("alex".to_owned()), email: None, }; req.set_session("account", &account).unwrap(); account } }; let content = format!("user:{:?}", &account); Ok(Response::with((iron::status::Ok, content))) } fn clear_all(req: &mut Request) -> IronResult<Response> { req.clear_session().unwrap(); Ok(Response::with((iron::status::Ok, "clear all"))) } fn show_count(req: &mut Request) -> IronResult<Response> { let mut count = req.get_session::<usize>("count").unwrap_or(0); count += 1; req.set_session("count", &count).unwrap(); Ok(Response::with((iron::status::Ok, format!("count:{}", &count)))) } fn reset_count(req: &mut Request) -> IronResult<Response> { req.remove_session("count").unwrap(); Ok(Response::with((iron::status::Ok, "count reset")))
}
random_line_split
actions.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fmt; use std::ops::Deref; use std::ops::DerefMut; use std::sync::Arc; use anyhow::Result; use manifest::DiffEntry; use manifest::DiffType; use manifest::FileMetadata; use manifest::FileType; use manifest::Manifest; use pathmatcher::Matcher; use pathmatcher::XorMatcher; use progress_model::ProgressBar; use types::RepoPathBuf; /// Map of simple actions that needs to be performed to move between revisions without conflicts. #[derive(Debug, Default, Clone, PartialEq)] pub struct ActionMap { map: HashMap<RepoPathBuf, Action>, } /// Basic update action. /// Diff between regular(no conflict checkin) commit generates list of such actions. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Action { Update(UpdateAction), Remove, UpdateExec(bool), } #[derive(Debug, Clone, Copy, PartialEq)] pub struct UpdateAction { pub from: Option<FileMetadata>, pub to: FileMetadata, } impl ActionMap { // This is similar to CheckoutPlan::new // Eventually CheckoutPlan::new will migrate to take (Conflict)ActionMap instead of a Diff and there won't be code duplication pub fn from_diff<D: Iterator<Item = Result<DiffEntry>>>(diff: D) -> Result<Self>
} _ => { if new.file_type!= FileType::GitSubmodule { map.insert( entry.path, Action::Update(UpdateAction::new(Some(old), new)), ); } } } } } } Ok(Self { map }) } pub fn with_sparse_profile_change< M1:'static + Matcher + Send + Sync, M2:'static + Matcher + Send + Sync, >( mut self, old_matcher: M1, new_matcher: M2, old_manifest: &impl Manifest, new_manifest: &impl Manifest, ) -> Result<Self> { let _prog = ProgressBar::register_new("sparse config", 0, ""); // First - remove all the files that were scheduled for update, but actually aren't in new sparse profile let mut result = Ok(()); self.map.retain(|path, action| { if result.is_err() { return true; } if matches!(action, Action::Remove) { return true; } match new_matcher.matches_file(path.as_ref()) { Ok(v) => v, Err(err) => { result = Err(err); true } } }); result?; // Second - handle files in a new manifest, that were affected by sparse profile change let new_matcher = Arc::new(new_matcher); let xor_matcher = XorMatcher::new(old_matcher, new_matcher.clone()); for file in new_manifest.files(xor_matcher) { let file = file?; if new_matcher.matches_file(&file.path)? { match self.map.entry(file.path) { Entry::Vacant(va) => { va.insert(Action::Update(UpdateAction::new(None, file.meta))); } Entry::Occupied(mut oc) => match oc.get() { Action::Remove | Action::Update(_) => {} Action::UpdateExec(_) => { oc.insert(Action::Update(UpdateAction::new(None, file.meta))); } }, } } else { // By definition of xor matcher this means old_matcher.matches_file==true. // Remove it if it existed before. if old_manifest.get(&file.path)?.is_some() { self.map.insert(file.path, Action::Remove); } } } Ok(self) } #[cfg(test)] pub fn empty() -> Self { Self { map: Default::default(), } } } impl Deref for ActionMap { type Target = HashMap<RepoPathBuf, Action>; fn deref(&self) -> &Self::Target { &self.map } } impl DerefMut for ActionMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.map } } impl UpdateAction { pub fn new(from: Option<FileMetadata>, to: FileMetadata) -> Self { Self { from, to } } } impl IntoIterator for ActionMap { type Item = (RepoPathBuf, Action); type IntoIter = <HashMap<RepoPathBuf, Action> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.map.into_iter() } } impl fmt::Display for ActionMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (path, action) in &self.map { match action { Action::Update(up) => write!(f, "up {}=>{}\n", path, up.to.hgid)?, Action::UpdateExec(x) => write!(f, "{} {}\n", if *x { "+x" } else { "-x" }, path)?, Action::Remove => write!(f, "rm {}\n", path)?, } } Ok(()) } } impl Action { pub fn pymerge_action(&self) -> (&'static str, (&'static str, bool), &'static str) { match self { Action::Update(up) => ("g", (pyflags(&up.to.file_type), false), "created/changed"), Action::Remove => ("r", ("", false), "deleted"), Action::UpdateExec(x) => ( "e", (if *x { "x" } else { "" }, false), "update permissions", ), } } } fn pyflags(t: &FileType) -> &'static str { match t { FileType::Symlink => "l", FileType::Regular => "", FileType::Executable => "x", // NOTE: hg does not have git submoduel "type". Is this code path actually used? FileType::GitSubmodule => "", } } #[cfg(test)] mod tests { use std::sync::Arc; use manifest_tree::testutil::make_tree_manifest_from_meta; use manifest_tree::testutil::TestStore; use pathmatcher::TreeMatcher; use types::HgId; use super::*; #[test] fn test_with_sparse_profile_change() -> Result<()> { let store = Arc::new(TestStore::new()); let a = (rp("a"), FileMetadata::regular(hgid(1))); let b = (rp("b"), FileMetadata::regular(hgid(2))); let c = (rp("c"), FileMetadata::regular(hgid(3))); let ab_profile = Arc::new(TreeMatcher::from_rules(["a", "b"].iter())?); let ac_profile = Arc::new(TreeMatcher::from_rules(["a", "c"].iter())?); let old_manifest = make_tree_manifest_from_meta(store.clone(), vec![]); let manifest = make_tree_manifest_from_meta(store, vec![a, b, c]); let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ab_profile.clone(), &old_manifest, &manifest, )?; assert_eq!("", &actions.to_string()); let mut expected_actions = ActionMap::empty(); expected_actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("b"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(10)))), ); actions.map.insert(rp("b"), Action::UpdateExec(true)); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); Ok(()) } fn rp(p: &str) -> RepoPathBuf { RepoPathBuf::from_string(p.to_string()).unwrap() } fn hgid(p: u8) -> HgId { let mut r = HgId::default().into_byte_array(); r[0] = p; HgId::from_byte_array(r) } }
{ let mut map = HashMap::new(); for entry in diff { let entry = entry?; match entry.diff_type { DiffType::LeftOnly(_) => { map.insert(entry.path, Action::Remove); } DiffType::RightOnly(meta) => { if meta.file_type != FileType::GitSubmodule { map.insert(entry.path, Action::Update(UpdateAction::new(None, meta))); } } DiffType::Changed(old, new) => { match (old.hgid == new.hgid, old.file_type, new.file_type) { (true, FileType::Executable, FileType::Regular) => { map.insert(entry.path, Action::UpdateExec(false)); } (true, FileType::Regular, FileType::Executable) => { map.insert(entry.path, Action::UpdateExec(true));
identifier_body
actions.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fmt; use std::ops::Deref; use std::ops::DerefMut; use std::sync::Arc; use anyhow::Result; use manifest::DiffEntry; use manifest::DiffType; use manifest::FileMetadata; use manifest::FileType; use manifest::Manifest; use pathmatcher::Matcher; use pathmatcher::XorMatcher; use progress_model::ProgressBar; use types::RepoPathBuf; /// Map of simple actions that needs to be performed to move between revisions without conflicts. #[derive(Debug, Default, Clone, PartialEq)] pub struct ActionMap { map: HashMap<RepoPathBuf, Action>, } /// Basic update action. /// Diff between regular(no conflict checkin) commit generates list of such actions. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Action { Update(UpdateAction), Remove, UpdateExec(bool), } #[derive(Debug, Clone, Copy, PartialEq)] pub struct UpdateAction { pub from: Option<FileMetadata>, pub to: FileMetadata, } impl ActionMap { // This is similar to CheckoutPlan::new // Eventually CheckoutPlan::new will migrate to take (Conflict)ActionMap instead of a Diff and there won't be code duplication pub fn from_diff<D: Iterator<Item = Result<DiffEntry>>>(diff: D) -> Result<Self> { let mut map = HashMap::new(); for entry in diff { let entry = entry?; match entry.diff_type { DiffType::LeftOnly(_) => { map.insert(entry.path, Action::Remove); } DiffType::RightOnly(meta) => { if meta.file_type!= FileType::GitSubmodule { map.insert(entry.path, Action::Update(UpdateAction::new(None, meta))); } } DiffType::Changed(old, new) => { match (old.hgid == new.hgid, old.file_type, new.file_type) { (true, FileType::Executable, FileType::Regular) => { map.insert(entry.path, Action::UpdateExec(false)); } (true, FileType::Regular, FileType::Executable) => { map.insert(entry.path, Action::UpdateExec(true)); } _ => { if new.file_type!= FileType::GitSubmodule { map.insert( entry.path, Action::Update(UpdateAction::new(Some(old), new)), ); } } } } } } Ok(Self { map }) } pub fn with_sparse_profile_change< M1:'static + Matcher + Send + Sync, M2:'static + Matcher + Send + Sync, >( mut self, old_matcher: M1, new_matcher: M2, old_manifest: &impl Manifest, new_manifest: &impl Manifest, ) -> Result<Self> { let _prog = ProgressBar::register_new("sparse config", 0, ""); // First - remove all the files that were scheduled for update, but actually aren't in new sparse profile let mut result = Ok(()); self.map.retain(|path, action| { if result.is_err() { return true; } if matches!(action, Action::Remove) { return true; } match new_matcher.matches_file(path.as_ref()) { Ok(v) => v, Err(err) => { result = Err(err); true } } }); result?; // Second - handle files in a new manifest, that were affected by sparse profile change let new_matcher = Arc::new(new_matcher); let xor_matcher = XorMatcher::new(old_matcher, new_matcher.clone()); for file in new_manifest.files(xor_matcher) { let file = file?; if new_matcher.matches_file(&file.path)? { match self.map.entry(file.path) { Entry::Vacant(va) => { va.insert(Action::Update(UpdateAction::new(None, file.meta))); } Entry::Occupied(mut oc) => match oc.get() { Action::Remove | Action::Update(_) => {} Action::UpdateExec(_) => { oc.insert(Action::Update(UpdateAction::new(None, file.meta))); } }, } } else { // By definition of xor matcher this means old_matcher.matches_file==true. // Remove it if it existed before. if old_manifest.get(&file.path)?.is_some() { self.map.insert(file.path, Action::Remove); } } } Ok(self) } #[cfg(test)] pub fn empty() -> Self { Self { map: Default::default(), } } } impl Deref for ActionMap { type Target = HashMap<RepoPathBuf, Action>; fn deref(&self) -> &Self::Target { &self.map } } impl DerefMut for ActionMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.map } } impl UpdateAction { pub fn new(from: Option<FileMetadata>, to: FileMetadata) -> Self { Self { from, to } } } impl IntoIterator for ActionMap { type Item = (RepoPathBuf, Action); type IntoIter = <HashMap<RepoPathBuf, Action> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.map.into_iter() } } impl fmt::Display for ActionMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (path, action) in &self.map { match action { Action::Update(up) => write!(f, "up {}=>{}\n", path, up.to.hgid)?, Action::UpdateExec(x) => write!(f, "{} {}\n", if *x { "+x" } else { "-x" }, path)?, Action::Remove => write!(f, "rm {}\n", path)?, } } Ok(()) } } impl Action { pub fn pymerge_action(&self) -> (&'static str, (&'static str, bool), &'static str) { match self { Action::Update(up) => ("g", (pyflags(&up.to.file_type), false), "created/changed"), Action::Remove => ("r", ("", false), "deleted"), Action::UpdateExec(x) => ( "e", (if *x { "x" } else { "" }, false), "update permissions", ), } } } fn pyflags(t: &FileType) -> &'static str { match t { FileType::Symlink => "l", FileType::Regular => "", FileType::Executable => "x", // NOTE: hg does not have git submoduel "type". Is this code path actually used? FileType::GitSubmodule => "", } } #[cfg(test)] mod tests { use std::sync::Arc; use manifest_tree::testutil::make_tree_manifest_from_meta; use manifest_tree::testutil::TestStore; use pathmatcher::TreeMatcher; use types::HgId; use super::*; #[test] fn test_with_sparse_profile_change() -> Result<()> { let store = Arc::new(TestStore::new()); let a = (rp("a"), FileMetadata::regular(hgid(1))); let b = (rp("b"), FileMetadata::regular(hgid(2))); let c = (rp("c"), FileMetadata::regular(hgid(3))); let ab_profile = Arc::new(TreeMatcher::from_rules(["a", "b"].iter())?); let ac_profile = Arc::new(TreeMatcher::from_rules(["a", "c"].iter())?);
let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ab_profile.clone(), &old_manifest, &manifest, )?; assert_eq!("", &actions.to_string()); let mut expected_actions = ActionMap::empty(); expected_actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("b"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(10)))), ); actions.map.insert(rp("b"), Action::UpdateExec(true)); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); Ok(()) } fn rp(p: &str) -> RepoPathBuf { RepoPathBuf::from_string(p.to_string()).unwrap() } fn hgid(p: u8) -> HgId { let mut r = HgId::default().into_byte_array(); r[0] = p; HgId::from_byte_array(r) } }
let old_manifest = make_tree_manifest_from_meta(store.clone(), vec![]); let manifest = make_tree_manifest_from_meta(store, vec![a, b, c]);
random_line_split
actions.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fmt; use std::ops::Deref; use std::ops::DerefMut; use std::sync::Arc; use anyhow::Result; use manifest::DiffEntry; use manifest::DiffType; use manifest::FileMetadata; use manifest::FileType; use manifest::Manifest; use pathmatcher::Matcher; use pathmatcher::XorMatcher; use progress_model::ProgressBar; use types::RepoPathBuf; /// Map of simple actions that needs to be performed to move between revisions without conflicts. #[derive(Debug, Default, Clone, PartialEq)] pub struct ActionMap { map: HashMap<RepoPathBuf, Action>, } /// Basic update action. /// Diff between regular(no conflict checkin) commit generates list of such actions. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Action { Update(UpdateAction), Remove, UpdateExec(bool), } #[derive(Debug, Clone, Copy, PartialEq)] pub struct UpdateAction { pub from: Option<FileMetadata>, pub to: FileMetadata, } impl ActionMap { // This is similar to CheckoutPlan::new // Eventually CheckoutPlan::new will migrate to take (Conflict)ActionMap instead of a Diff and there won't be code duplication pub fn from_diff<D: Iterator<Item = Result<DiffEntry>>>(diff: D) -> Result<Self> { let mut map = HashMap::new(); for entry in diff { let entry = entry?; match entry.diff_type { DiffType::LeftOnly(_) => { map.insert(entry.path, Action::Remove); } DiffType::RightOnly(meta) => { if meta.file_type!= FileType::GitSubmodule { map.insert(entry.path, Action::Update(UpdateAction::new(None, meta))); } } DiffType::Changed(old, new) => { match (old.hgid == new.hgid, old.file_type, new.file_type) { (true, FileType::Executable, FileType::Regular) => { map.insert(entry.path, Action::UpdateExec(false)); } (true, FileType::Regular, FileType::Executable) => { map.insert(entry.path, Action::UpdateExec(true)); } _ => { if new.file_type!= FileType::GitSubmodule { map.insert( entry.path, Action::Update(UpdateAction::new(Some(old), new)), ); } } } } } } Ok(Self { map }) } pub fn with_sparse_profile_change< M1:'static + Matcher + Send + Sync, M2:'static + Matcher + Send + Sync, >( mut self, old_matcher: M1, new_matcher: M2, old_manifest: &impl Manifest, new_manifest: &impl Manifest, ) -> Result<Self> { let _prog = ProgressBar::register_new("sparse config", 0, ""); // First - remove all the files that were scheduled for update, but actually aren't in new sparse profile let mut result = Ok(()); self.map.retain(|path, action| { if result.is_err() { return true; } if matches!(action, Action::Remove) { return true; } match new_matcher.matches_file(path.as_ref()) { Ok(v) => v, Err(err) => { result = Err(err); true } } }); result?; // Second - handle files in a new manifest, that were affected by sparse profile change let new_matcher = Arc::new(new_matcher); let xor_matcher = XorMatcher::new(old_matcher, new_matcher.clone()); for file in new_manifest.files(xor_matcher) { let file = file?; if new_matcher.matches_file(&file.path)? { match self.map.entry(file.path) { Entry::Vacant(va) => { va.insert(Action::Update(UpdateAction::new(None, file.meta))); } Entry::Occupied(mut oc) => match oc.get() { Action::Remove | Action::Update(_) => {} Action::UpdateExec(_) => { oc.insert(Action::Update(UpdateAction::new(None, file.meta))); } }, } } else { // By definition of xor matcher this means old_matcher.matches_file==true. // Remove it if it existed before. if old_manifest.get(&file.path)?.is_some() { self.map.insert(file.path, Action::Remove); } } } Ok(self) } #[cfg(test)] pub fn empty() -> Self { Self { map: Default::default(), } } } impl Deref for ActionMap { type Target = HashMap<RepoPathBuf, Action>; fn deref(&self) -> &Self::Target { &self.map } } impl DerefMut for ActionMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.map } } impl UpdateAction { pub fn
(from: Option<FileMetadata>, to: FileMetadata) -> Self { Self { from, to } } } impl IntoIterator for ActionMap { type Item = (RepoPathBuf, Action); type IntoIter = <HashMap<RepoPathBuf, Action> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.map.into_iter() } } impl fmt::Display for ActionMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (path, action) in &self.map { match action { Action::Update(up) => write!(f, "up {}=>{}\n", path, up.to.hgid)?, Action::UpdateExec(x) => write!(f, "{} {}\n", if *x { "+x" } else { "-x" }, path)?, Action::Remove => write!(f, "rm {}\n", path)?, } } Ok(()) } } impl Action { pub fn pymerge_action(&self) -> (&'static str, (&'static str, bool), &'static str) { match self { Action::Update(up) => ("g", (pyflags(&up.to.file_type), false), "created/changed"), Action::Remove => ("r", ("", false), "deleted"), Action::UpdateExec(x) => ( "e", (if *x { "x" } else { "" }, false), "update permissions", ), } } } fn pyflags(t: &FileType) -> &'static str { match t { FileType::Symlink => "l", FileType::Regular => "", FileType::Executable => "x", // NOTE: hg does not have git submoduel "type". Is this code path actually used? FileType::GitSubmodule => "", } } #[cfg(test)] mod tests { use std::sync::Arc; use manifest_tree::testutil::make_tree_manifest_from_meta; use manifest_tree::testutil::TestStore; use pathmatcher::TreeMatcher; use types::HgId; use super::*; #[test] fn test_with_sparse_profile_change() -> Result<()> { let store = Arc::new(TestStore::new()); let a = (rp("a"), FileMetadata::regular(hgid(1))); let b = (rp("b"), FileMetadata::regular(hgid(2))); let c = (rp("c"), FileMetadata::regular(hgid(3))); let ab_profile = Arc::new(TreeMatcher::from_rules(["a", "b"].iter())?); let ac_profile = Arc::new(TreeMatcher::from_rules(["a", "c"].iter())?); let old_manifest = make_tree_manifest_from_meta(store.clone(), vec![]); let manifest = make_tree_manifest_from_meta(store, vec![a, b, c]); let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ab_profile.clone(), &old_manifest, &manifest, )?; assert_eq!("", &actions.to_string()); let mut expected_actions = ActionMap::empty(); expected_actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = ActionMap::empty().with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("b"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(10)))), ); actions.map.insert(rp("b"), Action::UpdateExec(true)); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); let mut actions = ActionMap::empty(); actions.map.insert( rp("c"), Action::Update(UpdateAction::new(None, FileMetadata::regular(hgid(3)))), ); let actions = actions.with_sparse_profile_change( ab_profile.clone(), ac_profile.clone(), &old_manifest, &manifest, )?; assert_eq!(expected_actions, actions); Ok(()) } fn rp(p: &str) -> RepoPathBuf { RepoPathBuf::from_string(p.to_string()).unwrap() } fn hgid(p: u8) -> HgId { let mut r = HgId::default().into_byte_array(); r[0] = p; HgId::from_byte_array(r) } }
new
identifier_name
notes.rs
use crate::models::Note; use crate::uri_helpers::root_uri; pub fn notes_uri() -> String { let mut uri = root_uri(); if!uri.ends_with("/")
uri.push_str("notes"); uri } pub fn notes_atom_uri() -> String { let mut uri = notes_uri(); uri.push_str(".atom"); uri } pub fn note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri } pub fn edit_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/edit"); uri } pub fn new_note_uri() -> String { let mut uri = notes_uri(); uri.push_str("/new"); uri } pub fn delete_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/delete"); uri }
{ uri.push_str("/"); }
conditional_block
notes.rs
use crate::models::Note; use crate::uri_helpers::root_uri; pub fn notes_uri() -> String { let mut uri = root_uri(); if!uri.ends_with("/") { uri.push_str("/"); } uri.push_str("notes"); uri }
} pub fn note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri } pub fn edit_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/edit"); uri } pub fn new_note_uri() -> String { let mut uri = notes_uri(); uri.push_str("/new"); uri } pub fn delete_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/delete"); uri }
pub fn notes_atom_uri() -> String { let mut uri = notes_uri(); uri.push_str(".atom"); uri
random_line_split
notes.rs
use crate::models::Note; use crate::uri_helpers::root_uri; pub fn notes_uri() -> String { let mut uri = root_uri(); if!uri.ends_with("/") { uri.push_str("/"); } uri.push_str("notes"); uri } pub fn notes_atom_uri() -> String { let mut uri = notes_uri(); uri.push_str(".atom"); uri } pub fn note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri } pub fn edit_note_uri(note: &Note) -> String
pub fn new_note_uri() -> String { let mut uri = notes_uri(); uri.push_str("/new"); uri } pub fn delete_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/delete"); uri }
{ let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/edit"); uri }
identifier_body
notes.rs
use crate::models::Note; use crate::uri_helpers::root_uri; pub fn notes_uri() -> String { let mut uri = root_uri(); if!uri.ends_with("/") { uri.push_str("/"); } uri.push_str("notes"); uri } pub fn notes_atom_uri() -> String { let mut uri = notes_uri(); uri.push_str(".atom"); uri } pub fn note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri } pub fn edit_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/edit"); uri } pub fn
() -> String { let mut uri = notes_uri(); uri.push_str("/new"); uri } pub fn delete_note_uri(note: &Note) -> String { let mut uri = notes_uri(); uri.push_str("/"); uri.push_str(&note.id.to_string()); uri.push_str("/delete"); uri }
new_note_uri
identifier_name
decoder.rs
use std::slice; use std::old_io::MemReader; use std::default::Default; use image; use image::ImageResult; use image::ImageDecoder; use color; use super::vp8::Frame; use super::vp8::VP8Decoder; /// A Representation of a Webp Image format decoder. pub struct WebpDecoder<R> { r: R, frame: Frame, have_frame: bool, decoded_rows: u32, } impl<R: Reader> WebpDecoder<R> { /// Create a new WebpDecoder from the Reader ```r```. /// This function takes ownership of the Reader. pub fn new(r: R) -> WebpDecoder<R> { let f: Frame = Default::default(); WebpDecoder { r: r, have_frame: false, frame: f, decoded_rows: 0 } } fn read_riff_header(&mut self) -> ImageResult<u32> { let riff = try!(self.r.read_exact(4)); let size = try!(self.r.read_le_u32()); let webp = try!(self.r.read_exact(4)); if &*riff!= "RIFF".as_bytes() { return Err(image::ImageError::FormatError("Invalid RIFF signature.".to_string())) } if &*webp!= "WEBP".as_bytes() { return Err(image::ImageError::FormatError("Invalid WEBP signature.".to_string())) } Ok(size) } fn read_vp8_header(&mut self) -> ImageResult<()> { let vp8 = try!(self.r.read_exact(4)); if &*vp8!= "VP8 ".as_bytes() { return Err(image::ImageError::FormatError("Invalid VP8 signature.".to_string())) } let _len = try!(self.r.read_le_u32()); Ok(()) } fn read_frame(&mut self) -> ImageResult<()> { let framedata = try!(self.r.read_to_end()); let m = MemReader::new(framedata); let mut v = VP8Decoder::new(m); let frame = try!(v.decode_frame()); self.frame = frame.clone(); Ok(()) } fn read_metadata(&mut self) -> ImageResult<()> { if!self.have_frame { let _ = try!(self.read_riff_header()); let _ = try!(self.read_vp8_header()); let _ = try!(self.read_frame()); self.have_frame = true; } Ok(()) } } impl<R: Reader> ImageDecoder for WebpDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { let _ = try!(self.read_metadata()); Ok((self.frame.width as u32, self.frame.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { Ok(color::ColorType::Gray(8)) } fn row_len(&mut self) -> ImageResult<usize> { let _ = try!(self.read_metadata()); Ok(self.frame.width as usize) } fn
(&mut self, buf: &mut [u8]) -> ImageResult<u32> { let _ = try!(self.read_metadata()); if self.decoded_rows > self.frame.height as u32 { return Err(image::ImageError::ImageEnd) } let rlen = buf.len(); let slice = &self.frame.ybuf[ self.decoded_rows as usize * rlen.. self.decoded_rows as usize * rlen + rlen ]; slice::bytes::copy_memory(buf, slice); self.decoded_rows += 1; Ok(self.decoded_rows) } fn read_image(&mut self) -> ImageResult<image::DecodingResult> { let _ = try!(self.read_metadata()); Ok(image::DecodingResult::U8(self.frame.ybuf.clone())) } }
read_scanline
identifier_name
decoder.rs
use std::slice; use std::old_io::MemReader; use std::default::Default; use image; use image::ImageResult; use image::ImageDecoder; use color; use super::vp8::Frame; use super::vp8::VP8Decoder; /// A Representation of a Webp Image format decoder. pub struct WebpDecoder<R> { r: R, frame: Frame, have_frame: bool, decoded_rows: u32, } impl<R: Reader> WebpDecoder<R> { /// Create a new WebpDecoder from the Reader ```r```. /// This function takes ownership of the Reader. pub fn new(r: R) -> WebpDecoder<R> { let f: Frame = Default::default(); WebpDecoder { r: r, have_frame: false, frame: f, decoded_rows: 0 } } fn read_riff_header(&mut self) -> ImageResult<u32> { let riff = try!(self.r.read_exact(4)); let size = try!(self.r.read_le_u32()); let webp = try!(self.r.read_exact(4)); if &*riff!= "RIFF".as_bytes() { return Err(image::ImageError::FormatError("Invalid RIFF signature.".to_string())) } if &*webp!= "WEBP".as_bytes() { return Err(image::ImageError::FormatError("Invalid WEBP signature.".to_string())) } Ok(size) } fn read_vp8_header(&mut self) -> ImageResult<()> { let vp8 = try!(self.r.read_exact(4)); if &*vp8!= "VP8 ".as_bytes() { return Err(image::ImageError::FormatError("Invalid VP8 signature.".to_string())) } let _len = try!(self.r.read_le_u32()); Ok(()) } fn read_frame(&mut self) -> ImageResult<()> { let framedata = try!(self.r.read_to_end()); let m = MemReader::new(framedata); let mut v = VP8Decoder::new(m); let frame = try!(v.decode_frame()); self.frame = frame.clone(); Ok(()) } fn read_metadata(&mut self) -> ImageResult<()> { if!self.have_frame { let _ = try!(self.read_riff_header()); let _ = try!(self.read_vp8_header()); let _ = try!(self.read_frame()); self.have_frame = true; } Ok(()) } } impl<R: Reader> ImageDecoder for WebpDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { let _ = try!(self.read_metadata()); Ok((self.frame.width as u32, self.frame.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { Ok(color::ColorType::Gray(8)) } fn row_len(&mut self) -> ImageResult<usize> { let _ = try!(self.read_metadata()); Ok(self.frame.width as usize) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> { let _ = try!(self.read_metadata()); if self.decoded_rows > self.frame.height as u32 { return Err(image::ImageError::ImageEnd) } let rlen = buf.len(); let slice = &self.frame.ybuf[ self.decoded_rows as usize * rlen.. self.decoded_rows as usize * rlen + rlen ]; slice::bytes::copy_memory(buf, slice); self.decoded_rows += 1;
} fn read_image(&mut self) -> ImageResult<image::DecodingResult> { let _ = try!(self.read_metadata()); Ok(image::DecodingResult::U8(self.frame.ybuf.clone())) } }
Ok(self.decoded_rows)
random_line_split
decoder.rs
use std::slice; use std::old_io::MemReader; use std::default::Default; use image; use image::ImageResult; use image::ImageDecoder; use color; use super::vp8::Frame; use super::vp8::VP8Decoder; /// A Representation of a Webp Image format decoder. pub struct WebpDecoder<R> { r: R, frame: Frame, have_frame: bool, decoded_rows: u32, } impl<R: Reader> WebpDecoder<R> { /// Create a new WebpDecoder from the Reader ```r```. /// This function takes ownership of the Reader. pub fn new(r: R) -> WebpDecoder<R> { let f: Frame = Default::default(); WebpDecoder { r: r, have_frame: false, frame: f, decoded_rows: 0 } } fn read_riff_header(&mut self) -> ImageResult<u32> { let riff = try!(self.r.read_exact(4)); let size = try!(self.r.read_le_u32()); let webp = try!(self.r.read_exact(4)); if &*riff!= "RIFF".as_bytes() { return Err(image::ImageError::FormatError("Invalid RIFF signature.".to_string())) } if &*webp!= "WEBP".as_bytes() { return Err(image::ImageError::FormatError("Invalid WEBP signature.".to_string())) } Ok(size) } fn read_vp8_header(&mut self) -> ImageResult<()> { let vp8 = try!(self.r.read_exact(4)); if &*vp8!= "VP8 ".as_bytes() { return Err(image::ImageError::FormatError("Invalid VP8 signature.".to_string())) } let _len = try!(self.r.read_le_u32()); Ok(()) } fn read_frame(&mut self) -> ImageResult<()> { let framedata = try!(self.r.read_to_end()); let m = MemReader::new(framedata); let mut v = VP8Decoder::new(m); let frame = try!(v.decode_frame()); self.frame = frame.clone(); Ok(()) } fn read_metadata(&mut self) -> ImageResult<()> { if!self.have_frame { let _ = try!(self.read_riff_header()); let _ = try!(self.read_vp8_header()); let _ = try!(self.read_frame()); self.have_frame = true; } Ok(()) } } impl<R: Reader> ImageDecoder for WebpDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { let _ = try!(self.read_metadata()); Ok((self.frame.width as u32, self.frame.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { Ok(color::ColorType::Gray(8)) } fn row_len(&mut self) -> ImageResult<usize> { let _ = try!(self.read_metadata()); Ok(self.frame.width as usize) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32>
fn read_image(&mut self) -> ImageResult<image::DecodingResult> { let _ = try!(self.read_metadata()); Ok(image::DecodingResult::U8(self.frame.ybuf.clone())) } }
{ let _ = try!(self.read_metadata()); if self.decoded_rows > self.frame.height as u32 { return Err(image::ImageError::ImageEnd) } let rlen = buf.len(); let slice = &self.frame.ybuf[ self.decoded_rows as usize * rlen.. self.decoded_rows as usize * rlen + rlen ]; slice::bytes::copy_memory(buf, slice); self.decoded_rows += 1; Ok(self.decoded_rows) }
identifier_body
decoder.rs
use std::slice; use std::old_io::MemReader; use std::default::Default; use image; use image::ImageResult; use image::ImageDecoder; use color; use super::vp8::Frame; use super::vp8::VP8Decoder; /// A Representation of a Webp Image format decoder. pub struct WebpDecoder<R> { r: R, frame: Frame, have_frame: bool, decoded_rows: u32, } impl<R: Reader> WebpDecoder<R> { /// Create a new WebpDecoder from the Reader ```r```. /// This function takes ownership of the Reader. pub fn new(r: R) -> WebpDecoder<R> { let f: Frame = Default::default(); WebpDecoder { r: r, have_frame: false, frame: f, decoded_rows: 0 } } fn read_riff_header(&mut self) -> ImageResult<u32> { let riff = try!(self.r.read_exact(4)); let size = try!(self.r.read_le_u32()); let webp = try!(self.r.read_exact(4)); if &*riff!= "RIFF".as_bytes()
if &*webp!= "WEBP".as_bytes() { return Err(image::ImageError::FormatError("Invalid WEBP signature.".to_string())) } Ok(size) } fn read_vp8_header(&mut self) -> ImageResult<()> { let vp8 = try!(self.r.read_exact(4)); if &*vp8!= "VP8 ".as_bytes() { return Err(image::ImageError::FormatError("Invalid VP8 signature.".to_string())) } let _len = try!(self.r.read_le_u32()); Ok(()) } fn read_frame(&mut self) -> ImageResult<()> { let framedata = try!(self.r.read_to_end()); let m = MemReader::new(framedata); let mut v = VP8Decoder::new(m); let frame = try!(v.decode_frame()); self.frame = frame.clone(); Ok(()) } fn read_metadata(&mut self) -> ImageResult<()> { if!self.have_frame { let _ = try!(self.read_riff_header()); let _ = try!(self.read_vp8_header()); let _ = try!(self.read_frame()); self.have_frame = true; } Ok(()) } } impl<R: Reader> ImageDecoder for WebpDecoder<R> { fn dimensions(&mut self) -> ImageResult<(u32, u32)> { let _ = try!(self.read_metadata()); Ok((self.frame.width as u32, self.frame.height as u32)) } fn colortype(&mut self) -> ImageResult<color::ColorType> { Ok(color::ColorType::Gray(8)) } fn row_len(&mut self) -> ImageResult<usize> { let _ = try!(self.read_metadata()); Ok(self.frame.width as usize) } fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> { let _ = try!(self.read_metadata()); if self.decoded_rows > self.frame.height as u32 { return Err(image::ImageError::ImageEnd) } let rlen = buf.len(); let slice = &self.frame.ybuf[ self.decoded_rows as usize * rlen.. self.decoded_rows as usize * rlen + rlen ]; slice::bytes::copy_memory(buf, slice); self.decoded_rows += 1; Ok(self.decoded_rows) } fn read_image(&mut self) -> ImageResult<image::DecodingResult> { let _ = try!(self.read_metadata()); Ok(image::DecodingResult::U8(self.frame.ybuf.clone())) } }
{ return Err(image::ImageError::FormatError("Invalid RIFF signature.".to_string())) }
conditional_block
bug-7183-generics.rs
// run-pass trait Speak : Sized { fn say(&self, s:&str) -> String; fn
(&self) -> String { hello(self) } } fn hello<S:Speak>(s:&S) -> String{ s.say("hello") } impl Speak for isize { fn say(&self, s:&str) -> String { format!("{}: {}", s, *self) } } impl<T: Speak> Speak for Option<T> { fn say(&self, s:&str) -> String { match *self { None => format!("{} - none", s), Some(ref x) => { format!("something!{}", x.say(s)) } } } } pub fn main() { assert_eq!(3.hi(), "hello: 3".to_string()); assert_eq!(Some(Some(3)).hi(), "something!something!hello: 3".to_string()); assert_eq!(None::<isize>.hi(), "hello - none".to_string()); assert_eq!(Some(None::<isize>).hi(), "something!hello - none".to_string()); assert_eq!(Some(3).hi(), "something!hello: 3".to_string()); }
hi
identifier_name
bug-7183-generics.rs
// run-pass trait Speak : Sized { fn say(&self, s:&str) -> String; fn hi(&self) -> String { hello(self) } } fn hello<S:Speak>(s:&S) -> String{ s.say("hello") } impl Speak for isize { fn say(&self, s:&str) -> String { format!("{}: {}", s, *self) } } impl<T: Speak> Speak for Option<T> { fn say(&self, s:&str) -> String { match *self { None => format!("{} - none", s), Some(ref x) =>
} } } pub fn main() { assert_eq!(3.hi(), "hello: 3".to_string()); assert_eq!(Some(Some(3)).hi(), "something!something!hello: 3".to_string()); assert_eq!(None::<isize>.hi(), "hello - none".to_string()); assert_eq!(Some(None::<isize>).hi(), "something!hello - none".to_string()); assert_eq!(Some(3).hi(), "something!hello: 3".to_string()); }
{ format!("something!{}", x.say(s)) }
conditional_block
bug-7183-generics.rs
// run-pass trait Speak : Sized { fn say(&self, s:&str) -> String; fn hi(&self) -> String { hello(self) } } fn hello<S:Speak>(s:&S) -> String
impl Speak for isize { fn say(&self, s:&str) -> String { format!("{}: {}", s, *self) } } impl<T: Speak> Speak for Option<T> { fn say(&self, s:&str) -> String { match *self { None => format!("{} - none", s), Some(ref x) => { format!("something!{}", x.say(s)) } } } } pub fn main() { assert_eq!(3.hi(), "hello: 3".to_string()); assert_eq!(Some(Some(3)).hi(), "something!something!hello: 3".to_string()); assert_eq!(None::<isize>.hi(), "hello - none".to_string()); assert_eq!(Some(None::<isize>).hi(), "something!hello - none".to_string()); assert_eq!(Some(3).hi(), "something!hello: 3".to_string()); }
{ s.say("hello") }
identifier_body
bug-7183-generics.rs
// run-pass trait Speak : Sized { fn say(&self, s:&str) -> String; fn hi(&self) -> String { hello(self) } } fn hello<S:Speak>(s:&S) -> String{ s.say("hello") } impl Speak for isize { fn say(&self, s:&str) -> String { format!("{}: {}", s, *self)
} impl<T: Speak> Speak for Option<T> { fn say(&self, s:&str) -> String { match *self { None => format!("{} - none", s), Some(ref x) => { format!("something!{}", x.say(s)) } } } } pub fn main() { assert_eq!(3.hi(), "hello: 3".to_string()); assert_eq!(Some(Some(3)).hi(), "something!something!hello: 3".to_string()); assert_eq!(None::<isize>.hi(), "hello - none".to_string()); assert_eq!(Some(None::<isize>).hi(), "something!hello - none".to_string()); assert_eq!(Some(3).hi(), "something!hello: 3".to_string()); }
}
random_line_split
event_loop.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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::Error; use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::marker::PhantomData; use std::rc::Rc; /// <https://html.spec.whatwg.org/multipage/#event-loop> pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn drop(&mut self)
} impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), Error> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn sender(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
{ let _ = self .script_chan .send(ConstellationControlMsg::ExitScriptThread); }
identifier_body
event_loop.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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::Error; use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::marker::PhantomData; use std::rc::Rc; /// <https://html.spec.whatwg.org/multipage/#event-loop> pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn drop(&mut self) { let _ = self .script_chan .send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), Error> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn
(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
sender
identifier_name
event_loop.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/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. use ipc_channel::Error; use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::marker::PhantomData; use std::rc::Rc; /// <https://html.spec.whatwg.org/multipage/#event-loop> pub struct EventLoop { script_chan: IpcSender<ConstellationControlMsg>, dont_send_or_sync: PhantomData<Rc<()>>, } impl Drop for EventLoop { fn drop(&mut self) {
let _ = self .script_chan .send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a message to the event loop. pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), Error> { self.script_chan.send(msg) } /// The underlying channel to the script thread. pub fn sender(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
random_line_split
route.rs
use std::str::FromStr; use std::collections::HashSet; use syntax::ast::*; use syntax::ext::base::{ExtCtxt, Annotatable}; use syntax::codemap::{Span, Spanned, dummy_spanned}; use utils::{span, MetaItemExt, SpanExt, is_valid_ident}; use super::{Function, ParamIter}; use super::keyvalue::KVSpanned; use super::uri::validate_uri; use rocket::http::{Method, MediaType}; use rocket::http::uri::URI; /// This structure represents the parsed `route` attribute. /// /// It contains all of the information supplied by the user and the span where /// the user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub data_param: Option<KVSpanned<Ident>>, pub query_param: Option<Spanned<Ident>>, pub format: Option<KVSpanned<MediaType>>, pub rank: Option<KVSpanned<isize>>, } impl RouteParams { /// Parses the route attribute from the given decorator context. If the /// parse is not successful, this function exits early with the appropriate /// error message to the user. pub fn from(ecx: &mut ExtCtxt, sp: Span, known_method: Option<Spanned<Method>>, meta_item: &MetaItem, annotated: &Annotatable) -> RouteParams { let function = Function::from(annotated).unwrap_or_else(|item_sp| { ecx.span_err(sp, "this attribute can only be used on functions..."); ecx.span_fatal(item_sp, "...but was applied to the item above."); }); let meta_items = meta_item.meta_item_list().unwrap_or_else(|| { ecx.struct_span_err(sp, "incorrect use of attribute") .help("attributes in Rocket must have the form: #[name(...)]") .emit(); ecx.span_fatal(sp, "malformed attribute"); }); if meta_items.len() < 1 { ecx.span_fatal(sp, "attribute requires at least 1 parameter"); } // Figure out the method. If it is known (i.e, because we're parsing a // helper attribute), use that method directly. Otherwise, try to parse // it from the list of meta items. let (method, attr_params) = match known_method { Some(method) => (method, meta_items), None => (parse_method(ecx, &meta_items[0]), &meta_items[1..]) }; if attr_params.len() < 1 { ecx.struct_span_err(sp, "attribute requires at least a path") .help(r#"example: #[get("/my/path")] or #[get(path = "/hi")]"#) .emit(); ecx.span_fatal(sp, "malformed attribute"); } // Parse the required path and optional query parameters. let (uri, query) = parse_path(ecx, &attr_params[0]); // Parse all of the optional parameters. let mut seen_keys = HashSet::new(); let (mut rank, mut data, mut format) = Default::default(); for param in &attr_params[1..] { let kv_opt = kv_from_nested(param); if kv_opt.is_none() { ecx.span_err(param.span(), "expected key = value"); continue; } let kv = kv_opt.unwrap(); match kv.key().as_str() { "rank" => rank = parse_opt(ecx, &kv, parse_rank), "data" => data = parse_opt(ecx, &kv, parse_data), "format" => format = parse_opt(ecx, &kv, parse_format), _ => { let msg = format!("'{}' is not a known parameter", kv.key()); ecx.span_err(kv.span, &msg); continue; } } if seen_keys.contains(kv.key()) { let msg = format!("{} was already defined", kv.key()); ecx.struct_span_warn(param.span, &msg) .note("the last declared value will be used") .emit(); } else { seen_keys.insert(kv.key().clone()); } } // Sanity check: `data` should only be used with payload methods. if let Some(ref data_param) = data { if!method.node.supports_payload() { ecx.struct_span_err(data_param.span, "`data` route parameters \ can only be used with payload supporting methods") .note(&format!("'{}' does not support payloads", method.node)) .emit(); } }
uri: uri, data_param: data, query_param: query, format: format, rank: rank, annotated_fn: function, } } pub fn path_params<'s, 'a, 'c: 'a>(&'s self, ecx: &'a ExtCtxt<'c>) -> ParamIter<'s, 'a, 'c> { ParamIter::new(ecx, self.uri.node.path(), self.uri.span.trim(1)) } } fn is_valid_method(method: Method) -> bool { use rocket::http::Method::*; match method { Get | Put | Post | Delete | Head | Patch | Options => true, Trace | Connect => false } } pub fn kv_from_nested(item: &NestedMetaItem) -> Option<KVSpanned<LitKind>> { item.name_value().map(|(name, value)| { let k_span = item.span().shorten_to(name.as_str().len()); KVSpanned { key: span(name.to_string(), k_span), value: value.clone(), span: item.span(), } }) } pub fn param_to_ident(ecx: &ExtCtxt, s: Spanned<&str>) -> Option<Spanned<Ident>> { let string = s.node; if string.starts_with('<') && string.ends_with('>') { let param = &string[1..(string.len() - 1)]; if is_valid_ident(param) { return Some(span(Ident::from_str(param), s.span.trim(1))); } ecx.span_err(s.span, "parameter name must be alphanumeric"); } else { ecx.span_err(s.span, "parameters must start with '<' and end with '>'"); } None } fn parse_method(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> Spanned<Method> { if let Some(word) = meta_item.word() { if let Ok(method) = Method::from_str(&word.name().as_str()) { if is_valid_method(method) { return span(method, word.span()); } } else { let msg = format!("'{}' is not a valid HTTP method.", word.name()); ecx.span_err(word.span(), &msg); } } // Fallthrough. Return default method. ecx.struct_span_err(meta_item.span, "expected a valid HTTP method") .help("valid methods are: GET, PUT, POST, DELETE, PATCH") .emit(); dummy_spanned(Method::Get) } fn parse_path(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> (Spanned<URI<'static>>, Option<Spanned<Ident>>) { let sp = meta_item.span(); if let Some((name, lit)) = meta_item.name_value() { if name!= &"path" { ecx.span_err(sp, "the first key, if any, must be 'path'"); } else if let LitKind::Str(ref s, _) = lit.node { return validate_uri(ecx, &s.as_str(), lit.span); } else { ecx.span_err(lit.span, "`path` value must be a string") } } else if let Some(s) = meta_item.str_lit() { return validate_uri(ecx, &s.as_str(), sp); } else { ecx.struct_span_err(sp, r#"expected `path = string` or a path string"#) .help(r#"you can specify the path directly as a string, \ e.g: "/hello/world", or as a key-value pair, \ e.g: path = "/hello/world" "#) .emit(); } (dummy_spanned(URI::new("")), None) } fn parse_opt<O, T, F>(ecx: &ExtCtxt, kv: &KVSpanned<T>, f: F) -> Option<KVSpanned<O>> where F: Fn(&ExtCtxt, &KVSpanned<T>) -> O { Some(kv.map_ref(|_| f(ecx, kv))) } fn parse_data(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> Ident { let mut ident = Ident::from_str("unknown"); if let LitKind::Str(ref s, _) = *kv.value() { ident = Ident::from_str(&s.as_str()); if let Some(id) = param_to_ident(ecx, span(&s.as_str(), kv.value.span)) { return id.node; } } let err_string = r#"`data` value must be a parameter, e.g: "<name>"`"#; ecx.struct_span_fatal(kv.span, err_string) .help(r#"data, if specified, must be a key-value pair where the key is `data` and the value is a string with a single parameter inside '<' '>'. e.g: data = "<user_form>""#) .emit(); ident } fn parse_rank(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> isize { if let LitKind::Int(n, _) = *kv.value() { let max = isize::max_value(); if n <= max as u128 { return n as isize; } else { let msg = format!("rank must be less than or equal to {}", max); ecx.span_err(kv.value.span, msg.as_str()); } } else { ecx.struct_span_err(kv.span, r#"`rank` value must be an int"#) .help(r#"the rank, if specified, must be a key-value pair where the key is `rank` and the value is an integer. e.g: rank = 1, or e.g: rank = 10"#) .emit(); } -1 } fn parse_format(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> MediaType { if let LitKind::Str(ref s, _) = *kv.value() { if let Ok(ct) = MediaType::from_str(&s.as_str()) { if!ct.is_known() { let msg = format!("'{}' is not a known media type", s); ecx.span_warn(kv.value.span, &msg); } return ct; } else { ecx.span_err(kv.value.span, "malformed media type"); } } ecx.struct_span_err(kv.span, r#"`format` must be a "media/type""#) .help(r#"format, if specified, must be a key-value pair where the key is `format` and the value is a string representing the media type accepted. e.g: format = "application/json""#) .emit(); MediaType::Any }
RouteParams { method: method,
random_line_split
route.rs
use std::str::FromStr; use std::collections::HashSet; use syntax::ast::*; use syntax::ext::base::{ExtCtxt, Annotatable}; use syntax::codemap::{Span, Spanned, dummy_spanned}; use utils::{span, MetaItemExt, SpanExt, is_valid_ident}; use super::{Function, ParamIter}; use super::keyvalue::KVSpanned; use super::uri::validate_uri; use rocket::http::{Method, MediaType}; use rocket::http::uri::URI; /// This structure represents the parsed `route` attribute. /// /// It contains all of the information supplied by the user and the span where /// the user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub data_param: Option<KVSpanned<Ident>>, pub query_param: Option<Spanned<Ident>>, pub format: Option<KVSpanned<MediaType>>, pub rank: Option<KVSpanned<isize>>, } impl RouteParams { /// Parses the route attribute from the given decorator context. If the /// parse is not successful, this function exits early with the appropriate /// error message to the user. pub fn from(ecx: &mut ExtCtxt, sp: Span, known_method: Option<Spanned<Method>>, meta_item: &MetaItem, annotated: &Annotatable) -> RouteParams
let (method, attr_params) = match known_method { Some(method) => (method, meta_items), None => (parse_method(ecx, &meta_items[0]), &meta_items[1..]) }; if attr_params.len() < 1 { ecx.struct_span_err(sp, "attribute requires at least a path") .help(r#"example: #[get("/my/path")] or #[get(path = "/hi")]"#) .emit(); ecx.span_fatal(sp, "malformed attribute"); } // Parse the required path and optional query parameters. let (uri, query) = parse_path(ecx, &attr_params[0]); // Parse all of the optional parameters. let mut seen_keys = HashSet::new(); let (mut rank, mut data, mut format) = Default::default(); for param in &attr_params[1..] { let kv_opt = kv_from_nested(param); if kv_opt.is_none() { ecx.span_err(param.span(), "expected key = value"); continue; } let kv = kv_opt.unwrap(); match kv.key().as_str() { "rank" => rank = parse_opt(ecx, &kv, parse_rank), "data" => data = parse_opt(ecx, &kv, parse_data), "format" => format = parse_opt(ecx, &kv, parse_format), _ => { let msg = format!("'{}' is not a known parameter", kv.key()); ecx.span_err(kv.span, &msg); continue; } } if seen_keys.contains(kv.key()) { let msg = format!("{} was already defined", kv.key()); ecx.struct_span_warn(param.span, &msg) .note("the last declared value will be used") .emit(); } else { seen_keys.insert(kv.key().clone()); } } // Sanity check: `data` should only be used with payload methods. if let Some(ref data_param) = data { if!method.node.supports_payload() { ecx.struct_span_err(data_param.span, "`data` route parameters \ can only be used with payload supporting methods") .note(&format!("'{}' does not support payloads", method.node)) .emit(); } } RouteParams { method: method, uri: uri, data_param: data, query_param: query, format: format, rank: rank, annotated_fn: function, } } pub fn path_params<'s, 'a, 'c: 'a>(&'s self, ecx: &'a ExtCtxt<'c>) -> ParamIter<'s, 'a, 'c> { ParamIter::new(ecx, self.uri.node.path(), self.uri.span.trim(1)) } } fn is_valid_method(method: Method) -> bool { use rocket::http::Method::*; match method { Get | Put | Post | Delete | Head | Patch | Options => true, Trace | Connect => false } } pub fn kv_from_nested(item: &NestedMetaItem) -> Option<KVSpanned<LitKind>> { item.name_value().map(|(name, value)| { let k_span = item.span().shorten_to(name.as_str().len()); KVSpanned { key: span(name.to_string(), k_span), value: value.clone(), span: item.span(), } }) } pub fn param_to_ident(ecx: &ExtCtxt, s: Spanned<&str>) -> Option<Spanned<Ident>> { let string = s.node; if string.starts_with('<') && string.ends_with('>') { let param = &string[1..(string.len() - 1)]; if is_valid_ident(param) { return Some(span(Ident::from_str(param), s.span.trim(1))); } ecx.span_err(s.span, "parameter name must be alphanumeric"); } else { ecx.span_err(s.span, "parameters must start with '<' and end with '>'"); } None } fn parse_method(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> Spanned<Method> { if let Some(word) = meta_item.word() { if let Ok(method) = Method::from_str(&word.name().as_str()) { if is_valid_method(method) { return span(method, word.span()); } } else { let msg = format!("'{}' is not a valid HTTP method.", word.name()); ecx.span_err(word.span(), &msg); } } // Fallthrough. Return default method. ecx.struct_span_err(meta_item.span, "expected a valid HTTP method") .help("valid methods are: GET, PUT, POST, DELETE, PATCH") .emit(); dummy_spanned(Method::Get) } fn parse_path(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> (Spanned<URI<'static>>, Option<Spanned<Ident>>) { let sp = meta_item.span(); if let Some((name, lit)) = meta_item.name_value() { if name!= &"path" { ecx.span_err(sp, "the first key, if any, must be 'path'"); } else if let LitKind::Str(ref s, _) = lit.node { return validate_uri(ecx, &s.as_str(), lit.span); } else { ecx.span_err(lit.span, "`path` value must be a string") } } else if let Some(s) = meta_item.str_lit() { return validate_uri(ecx, &s.as_str(), sp); } else { ecx.struct_span_err(sp, r#"expected `path = string` or a path string"#) .help(r#"you can specify the path directly as a string, \ e.g: "/hello/world", or as a key-value pair, \ e.g: path = "/hello/world" "#) .emit(); } (dummy_spanned(URI::new("")), None) } fn parse_opt<O, T, F>(ecx: &ExtCtxt, kv: &KVSpanned<T>, f: F) -> Option<KVSpanned<O>> where F: Fn(&ExtCtxt, &KVSpanned<T>) -> O { Some(kv.map_ref(|_| f(ecx, kv))) } fn parse_data(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> Ident { let mut ident = Ident::from_str("unknown"); if let LitKind::Str(ref s, _) = *kv.value() { ident = Ident::from_str(&s.as_str()); if let Some(id) = param_to_ident(ecx, span(&s.as_str(), kv.value.span)) { return id.node; } } let err_string = r#"`data` value must be a parameter, e.g: "<name>"`"#; ecx.struct_span_fatal(kv.span, err_string) .help(r#"data, if specified, must be a key-value pair where the key is `data` and the value is a string with a single parameter inside '<' '>'. e.g: data = "<user_form>""#) .emit(); ident } fn parse_rank(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> isize { if let LitKind::Int(n, _) = *kv.value() { let max = isize::max_value(); if n <= max as u128 { return n as isize; } else { let msg = format!("rank must be less than or equal to {}", max); ecx.span_err(kv.value.span, msg.as_str()); } } else { ecx.struct_span_err(kv.span, r#"`rank` value must be an int"#) .help(r#"the rank, if specified, must be a key-value pair where the key is `rank` and the value is an integer. e.g: rank = 1, or e.g: rank = 10"#) .emit(); } -1 } fn parse_format(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> MediaType { if let LitKind::Str(ref s, _) = *kv.value() { if let Ok(ct) = MediaType::from_str(&s.as_str()) { if!ct.is_known() { let msg = format!("'{}' is not a known media type", s); ecx.span_warn(kv.value.span, &msg); } return ct; } else { ecx.span_err(kv.value.span, "malformed media type"); } } ecx.struct_span_err(kv.span, r#"`format` must be a "media/type""#) .help(r#"format, if specified, must be a key-value pair where the key is `format` and the value is a string representing the media type accepted. e.g: format = "application/json""#) .emit(); MediaType::Any }
{ let function = Function::from(annotated).unwrap_or_else(|item_sp| { ecx.span_err(sp, "this attribute can only be used on functions..."); ecx.span_fatal(item_sp, "...but was applied to the item above."); }); let meta_items = meta_item.meta_item_list().unwrap_or_else(|| { ecx.struct_span_err(sp, "incorrect use of attribute") .help("attributes in Rocket must have the form: #[name(...)]") .emit(); ecx.span_fatal(sp, "malformed attribute"); }); if meta_items.len() < 1 { ecx.span_fatal(sp, "attribute requires at least 1 parameter"); } // Figure out the method. If it is known (i.e, because we're parsing a // helper attribute), use that method directly. Otherwise, try to parse // it from the list of meta items.
identifier_body
route.rs
use std::str::FromStr; use std::collections::HashSet; use syntax::ast::*; use syntax::ext::base::{ExtCtxt, Annotatable}; use syntax::codemap::{Span, Spanned, dummy_spanned}; use utils::{span, MetaItemExt, SpanExt, is_valid_ident}; use super::{Function, ParamIter}; use super::keyvalue::KVSpanned; use super::uri::validate_uri; use rocket::http::{Method, MediaType}; use rocket::http::uri::URI; /// This structure represents the parsed `route` attribute. /// /// It contains all of the information supplied by the user and the span where /// the user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct
{ pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub data_param: Option<KVSpanned<Ident>>, pub query_param: Option<Spanned<Ident>>, pub format: Option<KVSpanned<MediaType>>, pub rank: Option<KVSpanned<isize>>, } impl RouteParams { /// Parses the route attribute from the given decorator context. If the /// parse is not successful, this function exits early with the appropriate /// error message to the user. pub fn from(ecx: &mut ExtCtxt, sp: Span, known_method: Option<Spanned<Method>>, meta_item: &MetaItem, annotated: &Annotatable) -> RouteParams { let function = Function::from(annotated).unwrap_or_else(|item_sp| { ecx.span_err(sp, "this attribute can only be used on functions..."); ecx.span_fatal(item_sp, "...but was applied to the item above."); }); let meta_items = meta_item.meta_item_list().unwrap_or_else(|| { ecx.struct_span_err(sp, "incorrect use of attribute") .help("attributes in Rocket must have the form: #[name(...)]") .emit(); ecx.span_fatal(sp, "malformed attribute"); }); if meta_items.len() < 1 { ecx.span_fatal(sp, "attribute requires at least 1 parameter"); } // Figure out the method. If it is known (i.e, because we're parsing a // helper attribute), use that method directly. Otherwise, try to parse // it from the list of meta items. let (method, attr_params) = match known_method { Some(method) => (method, meta_items), None => (parse_method(ecx, &meta_items[0]), &meta_items[1..]) }; if attr_params.len() < 1 { ecx.struct_span_err(sp, "attribute requires at least a path") .help(r#"example: #[get("/my/path")] or #[get(path = "/hi")]"#) .emit(); ecx.span_fatal(sp, "malformed attribute"); } // Parse the required path and optional query parameters. let (uri, query) = parse_path(ecx, &attr_params[0]); // Parse all of the optional parameters. let mut seen_keys = HashSet::new(); let (mut rank, mut data, mut format) = Default::default(); for param in &attr_params[1..] { let kv_opt = kv_from_nested(param); if kv_opt.is_none() { ecx.span_err(param.span(), "expected key = value"); continue; } let kv = kv_opt.unwrap(); match kv.key().as_str() { "rank" => rank = parse_opt(ecx, &kv, parse_rank), "data" => data = parse_opt(ecx, &kv, parse_data), "format" => format = parse_opt(ecx, &kv, parse_format), _ => { let msg = format!("'{}' is not a known parameter", kv.key()); ecx.span_err(kv.span, &msg); continue; } } if seen_keys.contains(kv.key()) { let msg = format!("{} was already defined", kv.key()); ecx.struct_span_warn(param.span, &msg) .note("the last declared value will be used") .emit(); } else { seen_keys.insert(kv.key().clone()); } } // Sanity check: `data` should only be used with payload methods. if let Some(ref data_param) = data { if!method.node.supports_payload() { ecx.struct_span_err(data_param.span, "`data` route parameters \ can only be used with payload supporting methods") .note(&format!("'{}' does not support payloads", method.node)) .emit(); } } RouteParams { method: method, uri: uri, data_param: data, query_param: query, format: format, rank: rank, annotated_fn: function, } } pub fn path_params<'s, 'a, 'c: 'a>(&'s self, ecx: &'a ExtCtxt<'c>) -> ParamIter<'s, 'a, 'c> { ParamIter::new(ecx, self.uri.node.path(), self.uri.span.trim(1)) } } fn is_valid_method(method: Method) -> bool { use rocket::http::Method::*; match method { Get | Put | Post | Delete | Head | Patch | Options => true, Trace | Connect => false } } pub fn kv_from_nested(item: &NestedMetaItem) -> Option<KVSpanned<LitKind>> { item.name_value().map(|(name, value)| { let k_span = item.span().shorten_to(name.as_str().len()); KVSpanned { key: span(name.to_string(), k_span), value: value.clone(), span: item.span(), } }) } pub fn param_to_ident(ecx: &ExtCtxt, s: Spanned<&str>) -> Option<Spanned<Ident>> { let string = s.node; if string.starts_with('<') && string.ends_with('>') { let param = &string[1..(string.len() - 1)]; if is_valid_ident(param) { return Some(span(Ident::from_str(param), s.span.trim(1))); } ecx.span_err(s.span, "parameter name must be alphanumeric"); } else { ecx.span_err(s.span, "parameters must start with '<' and end with '>'"); } None } fn parse_method(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> Spanned<Method> { if let Some(word) = meta_item.word() { if let Ok(method) = Method::from_str(&word.name().as_str()) { if is_valid_method(method) { return span(method, word.span()); } } else { let msg = format!("'{}' is not a valid HTTP method.", word.name()); ecx.span_err(word.span(), &msg); } } // Fallthrough. Return default method. ecx.struct_span_err(meta_item.span, "expected a valid HTTP method") .help("valid methods are: GET, PUT, POST, DELETE, PATCH") .emit(); dummy_spanned(Method::Get) } fn parse_path(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> (Spanned<URI<'static>>, Option<Spanned<Ident>>) { let sp = meta_item.span(); if let Some((name, lit)) = meta_item.name_value() { if name!= &"path" { ecx.span_err(sp, "the first key, if any, must be 'path'"); } else if let LitKind::Str(ref s, _) = lit.node { return validate_uri(ecx, &s.as_str(), lit.span); } else { ecx.span_err(lit.span, "`path` value must be a string") } } else if let Some(s) = meta_item.str_lit() { return validate_uri(ecx, &s.as_str(), sp); } else { ecx.struct_span_err(sp, r#"expected `path = string` or a path string"#) .help(r#"you can specify the path directly as a string, \ e.g: "/hello/world", or as a key-value pair, \ e.g: path = "/hello/world" "#) .emit(); } (dummy_spanned(URI::new("")), None) } fn parse_opt<O, T, F>(ecx: &ExtCtxt, kv: &KVSpanned<T>, f: F) -> Option<KVSpanned<O>> where F: Fn(&ExtCtxt, &KVSpanned<T>) -> O { Some(kv.map_ref(|_| f(ecx, kv))) } fn parse_data(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> Ident { let mut ident = Ident::from_str("unknown"); if let LitKind::Str(ref s, _) = *kv.value() { ident = Ident::from_str(&s.as_str()); if let Some(id) = param_to_ident(ecx, span(&s.as_str(), kv.value.span)) { return id.node; } } let err_string = r#"`data` value must be a parameter, e.g: "<name>"`"#; ecx.struct_span_fatal(kv.span, err_string) .help(r#"data, if specified, must be a key-value pair where the key is `data` and the value is a string with a single parameter inside '<' '>'. e.g: data = "<user_form>""#) .emit(); ident } fn parse_rank(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> isize { if let LitKind::Int(n, _) = *kv.value() { let max = isize::max_value(); if n <= max as u128 { return n as isize; } else { let msg = format!("rank must be less than or equal to {}", max); ecx.span_err(kv.value.span, msg.as_str()); } } else { ecx.struct_span_err(kv.span, r#"`rank` value must be an int"#) .help(r#"the rank, if specified, must be a key-value pair where the key is `rank` and the value is an integer. e.g: rank = 1, or e.g: rank = 10"#) .emit(); } -1 } fn parse_format(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> MediaType { if let LitKind::Str(ref s, _) = *kv.value() { if let Ok(ct) = MediaType::from_str(&s.as_str()) { if!ct.is_known() { let msg = format!("'{}' is not a known media type", s); ecx.span_warn(kv.value.span, &msg); } return ct; } else { ecx.span_err(kv.value.span, "malformed media type"); } } ecx.struct_span_err(kv.span, r#"`format` must be a "media/type""#) .help(r#"format, if specified, must be a key-value pair where the key is `format` and the value is a string representing the media type accepted. e.g: format = "application/json""#) .emit(); MediaType::Any }
RouteParams
identifier_name
route.rs
use std::str::FromStr; use std::collections::HashSet; use syntax::ast::*; use syntax::ext::base::{ExtCtxt, Annotatable}; use syntax::codemap::{Span, Spanned, dummy_spanned}; use utils::{span, MetaItemExt, SpanExt, is_valid_ident}; use super::{Function, ParamIter}; use super::keyvalue::KVSpanned; use super::uri::validate_uri; use rocket::http::{Method, MediaType}; use rocket::http::uri::URI; /// This structure represents the parsed `route` attribute. /// /// It contains all of the information supplied by the user and the span where /// the user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub data_param: Option<KVSpanned<Ident>>, pub query_param: Option<Spanned<Ident>>, pub format: Option<KVSpanned<MediaType>>, pub rank: Option<KVSpanned<isize>>, } impl RouteParams { /// Parses the route attribute from the given decorator context. If the /// parse is not successful, this function exits early with the appropriate /// error message to the user. pub fn from(ecx: &mut ExtCtxt, sp: Span, known_method: Option<Spanned<Method>>, meta_item: &MetaItem, annotated: &Annotatable) -> RouteParams { let function = Function::from(annotated).unwrap_or_else(|item_sp| { ecx.span_err(sp, "this attribute can only be used on functions..."); ecx.span_fatal(item_sp, "...but was applied to the item above."); }); let meta_items = meta_item.meta_item_list().unwrap_or_else(|| { ecx.struct_span_err(sp, "incorrect use of attribute") .help("attributes in Rocket must have the form: #[name(...)]") .emit(); ecx.span_fatal(sp, "malformed attribute"); }); if meta_items.len() < 1 { ecx.span_fatal(sp, "attribute requires at least 1 parameter"); } // Figure out the method. If it is known (i.e, because we're parsing a // helper attribute), use that method directly. Otherwise, try to parse // it from the list of meta items. let (method, attr_params) = match known_method { Some(method) => (method, meta_items), None => (parse_method(ecx, &meta_items[0]), &meta_items[1..]) }; if attr_params.len() < 1 { ecx.struct_span_err(sp, "attribute requires at least a path") .help(r#"example: #[get("/my/path")] or #[get(path = "/hi")]"#) .emit(); ecx.span_fatal(sp, "malformed attribute"); } // Parse the required path and optional query parameters. let (uri, query) = parse_path(ecx, &attr_params[0]); // Parse all of the optional parameters. let mut seen_keys = HashSet::new(); let (mut rank, mut data, mut format) = Default::default(); for param in &attr_params[1..] { let kv_opt = kv_from_nested(param); if kv_opt.is_none() { ecx.span_err(param.span(), "expected key = value"); continue; } let kv = kv_opt.unwrap(); match kv.key().as_str() { "rank" => rank = parse_opt(ecx, &kv, parse_rank), "data" => data = parse_opt(ecx, &kv, parse_data), "format" => format = parse_opt(ecx, &kv, parse_format), _ => { let msg = format!("'{}' is not a known parameter", kv.key()); ecx.span_err(kv.span, &msg); continue; } } if seen_keys.contains(kv.key()) { let msg = format!("{} was already defined", kv.key()); ecx.struct_span_warn(param.span, &msg) .note("the last declared value will be used") .emit(); } else { seen_keys.insert(kv.key().clone()); } } // Sanity check: `data` should only be used with payload methods. if let Some(ref data_param) = data { if!method.node.supports_payload() { ecx.struct_span_err(data_param.span, "`data` route parameters \ can only be used with payload supporting methods") .note(&format!("'{}' does not support payloads", method.node)) .emit(); } } RouteParams { method: method, uri: uri, data_param: data, query_param: query, format: format, rank: rank, annotated_fn: function, } } pub fn path_params<'s, 'a, 'c: 'a>(&'s self, ecx: &'a ExtCtxt<'c>) -> ParamIter<'s, 'a, 'c> { ParamIter::new(ecx, self.uri.node.path(), self.uri.span.trim(1)) } } fn is_valid_method(method: Method) -> bool { use rocket::http::Method::*; match method { Get | Put | Post | Delete | Head | Patch | Options => true, Trace | Connect => false } } pub fn kv_from_nested(item: &NestedMetaItem) -> Option<KVSpanned<LitKind>> { item.name_value().map(|(name, value)| { let k_span = item.span().shorten_to(name.as_str().len()); KVSpanned { key: span(name.to_string(), k_span), value: value.clone(), span: item.span(), } }) } pub fn param_to_ident(ecx: &ExtCtxt, s: Spanned<&str>) -> Option<Spanned<Ident>> { let string = s.node; if string.starts_with('<') && string.ends_with('>') { let param = &string[1..(string.len() - 1)]; if is_valid_ident(param) { return Some(span(Ident::from_str(param), s.span.trim(1))); } ecx.span_err(s.span, "parameter name must be alphanumeric"); } else { ecx.span_err(s.span, "parameters must start with '<' and end with '>'"); } None } fn parse_method(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> Spanned<Method> { if let Some(word) = meta_item.word() { if let Ok(method) = Method::from_str(&word.name().as_str()) { if is_valid_method(method) { return span(method, word.span()); } } else { let msg = format!("'{}' is not a valid HTTP method.", word.name()); ecx.span_err(word.span(), &msg); } } // Fallthrough. Return default method. ecx.struct_span_err(meta_item.span, "expected a valid HTTP method") .help("valid methods are: GET, PUT, POST, DELETE, PATCH") .emit(); dummy_spanned(Method::Get) } fn parse_path(ecx: &ExtCtxt, meta_item: &NestedMetaItem) -> (Spanned<URI<'static>>, Option<Spanned<Ident>>) { let sp = meta_item.span(); if let Some((name, lit)) = meta_item.name_value()
else if let Some(s) = meta_item.str_lit() { return validate_uri(ecx, &s.as_str(), sp); } else { ecx.struct_span_err(sp, r#"expected `path = string` or a path string"#) .help(r#"you can specify the path directly as a string, \ e.g: "/hello/world", or as a key-value pair, \ e.g: path = "/hello/world" "#) .emit(); } (dummy_spanned(URI::new("")), None) } fn parse_opt<O, T, F>(ecx: &ExtCtxt, kv: &KVSpanned<T>, f: F) -> Option<KVSpanned<O>> where F: Fn(&ExtCtxt, &KVSpanned<T>) -> O { Some(kv.map_ref(|_| f(ecx, kv))) } fn parse_data(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> Ident { let mut ident = Ident::from_str("unknown"); if let LitKind::Str(ref s, _) = *kv.value() { ident = Ident::from_str(&s.as_str()); if let Some(id) = param_to_ident(ecx, span(&s.as_str(), kv.value.span)) { return id.node; } } let err_string = r#"`data` value must be a parameter, e.g: "<name>"`"#; ecx.struct_span_fatal(kv.span, err_string) .help(r#"data, if specified, must be a key-value pair where the key is `data` and the value is a string with a single parameter inside '<' '>'. e.g: data = "<user_form>""#) .emit(); ident } fn parse_rank(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> isize { if let LitKind::Int(n, _) = *kv.value() { let max = isize::max_value(); if n <= max as u128 { return n as isize; } else { let msg = format!("rank must be less than or equal to {}", max); ecx.span_err(kv.value.span, msg.as_str()); } } else { ecx.struct_span_err(kv.span, r#"`rank` value must be an int"#) .help(r#"the rank, if specified, must be a key-value pair where the key is `rank` and the value is an integer. e.g: rank = 1, or e.g: rank = 10"#) .emit(); } -1 } fn parse_format(ecx: &ExtCtxt, kv: &KVSpanned<LitKind>) -> MediaType { if let LitKind::Str(ref s, _) = *kv.value() { if let Ok(ct) = MediaType::from_str(&s.as_str()) { if!ct.is_known() { let msg = format!("'{}' is not a known media type", s); ecx.span_warn(kv.value.span, &msg); } return ct; } else { ecx.span_err(kv.value.span, "malformed media type"); } } ecx.struct_span_err(kv.span, r#"`format` must be a "media/type""#) .help(r#"format, if specified, must be a key-value pair where the key is `format` and the value is a string representing the media type accepted. e.g: format = "application/json""#) .emit(); MediaType::Any }
{ if name != &"path" { ecx.span_err(sp, "the first key, if any, must be 'path'"); } else if let LitKind::Str(ref s, _) = lit.node { return validate_uri(ecx, &s.as_str(), lit.span); } else { ecx.span_err(lit.span, "`path` value must be a string") } }
conditional_block
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::storage::Storage; use crate::base::{ DefaultAllocator, Hessenberg, MatrixN, SquareMatrix, Unit, Vector2, Vector3, VectorN, }; use crate::constraint::{DimEq, ShapeConstraint}; use crate::geometry::{Reflection, UnitComplex}; use crate::linalg::householder; use crate::linalg::Schur; /// Eigendecomposition of a real matrix with real eigenvalues (or complex eigen values for complex matrices). #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde-serialize", serde(bound(serialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Serialize")) )] #[cfg_attr( feature = "serde-serialize", serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Deserialize<'de>")) )] #[derive(Clone, Debug)] pub struct
<N: ComplexField, D: Dim> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D> { pub eigenvectors: MatrixN<N, D>, pub eigenvalues: VectorN<N, D>, } impl<N: ComplexField, D: Dim> Copy for Eigen<N, D> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>, MatrixN<N, D>: Copy, VectorN<N, D>: Copy, { } impl<N: ComplexField, D: Dim> Eigen<N, D> where D: DimSub<U1>, // For Hessenberg. ShapeConstraint: DimEq<Dynamic, DimDiff<D, U1>>, // For Hessenberg. DefaultAllocator: Allocator<N, D, DimDiff<D, U1>> + Allocator<N, DimDiff<D, U1>> + Allocator<N, D, D> + Allocator<N, D>, // XXX: for debug DefaultAllocator: Allocator<usize, D, D>, MatrixN<N, D>: Display, { /// Computes the eigendecomposition of a diagonalizable matrix with Complex eigenvalues. pub fn new(m: MatrixN<N, D>) -> Option<Eigen<N, D>> { assert!( m.is_square(), "Unable to compute the eigendecomposition of a non-square matrix." ); let dim = m.nrows(); let (mut eigenvectors, mut eigenvalues) = Schur::new(m, 0).unwrap().unpack(); println!("Schur eigenvalues: {}", eigenvalues); // Check that the eigenvalues are all Complex. for i in 0..dim - 1 { if!eigenvalues[(i + 1, i)].is_zero() { return None; } } for j in 1..dim { for i in 0..j { let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() &&!eigenvalues[(i, j)].is_zero() { return None; } let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenvectors[(k, i)]; } } } // Normalize the eigenvector basis. for i in 0..dim { let _ = eigenvectors.column_mut(i).normalize_mut(); } Some(Eigen { eigenvectors, eigenvalues: eigenvalues.diagonal(), }) } }
Eigen
identifier_name
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::storage::Storage; use crate::base::{ DefaultAllocator, Hessenberg, MatrixN, SquareMatrix, Unit, Vector2, Vector3, VectorN, }; use crate::constraint::{DimEq, ShapeConstraint}; use crate::geometry::{Reflection, UnitComplex}; use crate::linalg::householder; use crate::linalg::Schur; /// Eigendecomposition of a real matrix with real eigenvalues (or complex eigen values for complex matrices). #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde-serialize", serde(bound(serialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Serialize")) )] #[cfg_attr( feature = "serde-serialize", serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Deserialize<'de>")) )] #[derive(Clone, Debug)] pub struct Eigen<N: ComplexField, D: Dim> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D> { pub eigenvectors: MatrixN<N, D>, pub eigenvalues: VectorN<N, D>, } impl<N: ComplexField, D: Dim> Copy for Eigen<N, D> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>, MatrixN<N, D>: Copy, VectorN<N, D>: Copy, { } impl<N: ComplexField, D: Dim> Eigen<N, D> where D: DimSub<U1>, // For Hessenberg. ShapeConstraint: DimEq<Dynamic, DimDiff<D, U1>>, // For Hessenberg. DefaultAllocator: Allocator<N, D, DimDiff<D, U1>> + Allocator<N, DimDiff<D, U1>> + Allocator<N, D, D> + Allocator<N, D>, // XXX: for debug DefaultAllocator: Allocator<usize, D, D>, MatrixN<N, D>: Display, { /// Computes the eigendecomposition of a diagonalizable matrix with Complex eigenvalues. pub fn new(m: MatrixN<N, D>) -> Option<Eigen<N, D>> { assert!( m.is_square(), "Unable to compute the eigendecomposition of a non-square matrix." ); let dim = m.nrows(); let (mut eigenvectors, mut eigenvalues) = Schur::new(m, 0).unwrap().unpack(); println!("Schur eigenvalues: {}", eigenvalues); // Check that the eigenvalues are all Complex. for i in 0..dim - 1 { if!eigenvalues[(i + 1, i)].is_zero() { return None; } } for j in 1..dim {
return None; } let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenvectors[(k, i)]; } } } // Normalize the eigenvector basis. for i in 0..dim { let _ = eigenvectors.column_mut(i).normalize_mut(); } Some(Eigen { eigenvectors, eigenvalues: eigenvalues.diagonal(), }) } }
for i in 0..j { let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() && !eigenvalues[(i, j)].is_zero() {
random_line_split
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::storage::Storage; use crate::base::{ DefaultAllocator, Hessenberg, MatrixN, SquareMatrix, Unit, Vector2, Vector3, VectorN, }; use crate::constraint::{DimEq, ShapeConstraint}; use crate::geometry::{Reflection, UnitComplex}; use crate::linalg::householder; use crate::linalg::Schur; /// Eigendecomposition of a real matrix with real eigenvalues (or complex eigen values for complex matrices). #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde-serialize", serde(bound(serialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Serialize")) )] #[cfg_attr( feature = "serde-serialize", serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Deserialize<'de>")) )] #[derive(Clone, Debug)] pub struct Eigen<N: ComplexField, D: Dim> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D> { pub eigenvectors: MatrixN<N, D>, pub eigenvalues: VectorN<N, D>, } impl<N: ComplexField, D: Dim> Copy for Eigen<N, D> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>, MatrixN<N, D>: Copy, VectorN<N, D>: Copy, { } impl<N: ComplexField, D: Dim> Eigen<N, D> where D: DimSub<U1>, // For Hessenberg. ShapeConstraint: DimEq<Dynamic, DimDiff<D, U1>>, // For Hessenberg. DefaultAllocator: Allocator<N, D, DimDiff<D, U1>> + Allocator<N, DimDiff<D, U1>> + Allocator<N, D, D> + Allocator<N, D>, // XXX: for debug DefaultAllocator: Allocator<usize, D, D>, MatrixN<N, D>: Display, { /// Computes the eigendecomposition of a diagonalizable matrix with Complex eigenvalues. pub fn new(m: MatrixN<N, D>) -> Option<Eigen<N, D>> { assert!( m.is_square(), "Unable to compute the eigendecomposition of a non-square matrix." ); let dim = m.nrows(); let (mut eigenvectors, mut eigenvalues) = Schur::new(m, 0).unwrap().unpack(); println!("Schur eigenvalues: {}", eigenvalues); // Check that the eigenvalues are all Complex. for i in 0..dim - 1 { if!eigenvalues[(i + 1, i)].is_zero() { return None; } } for j in 1..dim { for i in 0..j { let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() &&!eigenvalues[(i, j)].is_zero()
let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenvectors[(k, i)]; } } } // Normalize the eigenvector basis. for i in 0..dim { let _ = eigenvectors.column_mut(i).normalize_mut(); } Some(Eigen { eigenvectors, eigenvalues: eigenvalues.diagonal(), }) } }
{ return None; }
conditional_block
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::storage::Storage; use crate::base::{ DefaultAllocator, Hessenberg, MatrixN, SquareMatrix, Unit, Vector2, Vector3, VectorN, }; use crate::constraint::{DimEq, ShapeConstraint}; use crate::geometry::{Reflection, UnitComplex}; use crate::linalg::householder; use crate::linalg::Schur; /// Eigendecomposition of a real matrix with real eigenvalues (or complex eigen values for complex matrices). #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))] #[cfg_attr( feature = "serde-serialize", serde(bound(serialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Serialize")) )] #[cfg_attr( feature = "serde-serialize", serde(bound(deserialize = "DefaultAllocator: Allocator<N, D>, VectorN<N, D>: Serialize, MatrixN<N, D>: Deserialize<'de>")) )] #[derive(Clone, Debug)] pub struct Eigen<N: ComplexField, D: Dim> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D> { pub eigenvectors: MatrixN<N, D>, pub eigenvalues: VectorN<N, D>, } impl<N: ComplexField, D: Dim> Copy for Eigen<N, D> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>, MatrixN<N, D>: Copy, VectorN<N, D>: Copy, { } impl<N: ComplexField, D: Dim> Eigen<N, D> where D: DimSub<U1>, // For Hessenberg. ShapeConstraint: DimEq<Dynamic, DimDiff<D, U1>>, // For Hessenberg. DefaultAllocator: Allocator<N, D, DimDiff<D, U1>> + Allocator<N, DimDiff<D, U1>> + Allocator<N, D, D> + Allocator<N, D>, // XXX: for debug DefaultAllocator: Allocator<usize, D, D>, MatrixN<N, D>: Display, { /// Computes the eigendecomposition of a diagonalizable matrix with Complex eigenvalues. pub fn new(m: MatrixN<N, D>) -> Option<Eigen<N, D>>
let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() &&!eigenvalues[(i, j)].is_zero() { return None; } let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenvectors[(k, i)]; } } } // Normalize the eigenvector basis. for i in 0..dim { let _ = eigenvectors.column_mut(i).normalize_mut(); } Some(Eigen { eigenvectors, eigenvalues: eigenvalues.diagonal(), }) } }
{ assert!( m.is_square(), "Unable to compute the eigendecomposition of a non-square matrix." ); let dim = m.nrows(); let (mut eigenvectors, mut eigenvalues) = Schur::new(m, 0).unwrap().unpack(); println!("Schur eigenvalues: {}", eigenvalues); // Check that the eigenvalues are all Complex. for i in 0..dim - 1 { if !eigenvalues[(i + 1, i)].is_zero() { return None; } } for j in 1..dim { for i in 0..j {
identifier_body
bug_char.rs
#include "shared.rsh" char rand_sc1_0, rand_sc1_1; char2 rand_sc2_0, rand_sc2_1; char min_rand_sc1_sc1; char2 min_rand_sc2_sc2; static bool test_bug_char() { bool failed = false; rsDebug("rand_sc2_0.x: ", rand_sc2_0.x); rsDebug("rand_sc2_0.y: ", rand_sc2_0.y); rsDebug("rand_sc2_1.x: ", rand_sc2_1.x); rsDebug("rand_sc2_1.y: ", rand_sc2_1.y); char temp_sc1; char2 temp_sc2; temp_sc1 = min( rand_sc1_0, rand_sc1_1 ); if (temp_sc1!= min_rand_sc1_sc1)
rsDebug("broken", 'y'); temp_sc2 = min( rand_sc2_0, rand_sc2_1 ); if (temp_sc2.x!= min_rand_sc2_sc2.x || temp_sc2.y!= min_rand_sc2_sc2.y) { failed = true; } return failed; } void bug_char_test() { bool failed = false; failed |= test_bug_char(); if (failed) { rsSendToClientBlocking(RS_MSG_TEST_FAILED); } else { rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
{ rsDebug("temp_sc1", temp_sc1); failed = true; }
conditional_block
bug_char.rs
#include "shared.rsh" char rand_sc1_0, rand_sc1_1; char2 rand_sc2_0, rand_sc2_1; char min_rand_sc1_sc1; char2 min_rand_sc2_sc2; static bool test_bug_char() { bool failed = false; rsDebug("rand_sc2_0.x: ", rand_sc2_0.x); rsDebug("rand_sc2_0.y: ", rand_sc2_0.y); rsDebug("rand_sc2_1.x: ", rand_sc2_1.x); rsDebug("rand_sc2_1.y: ", rand_sc2_1.y); char temp_sc1; char2 temp_sc2; temp_sc1 = min( rand_sc1_0, rand_sc1_1 ); if (temp_sc1!= min_rand_sc1_sc1) { rsDebug("temp_sc1", temp_sc1); failed = true; } rsDebug("broken", 'y'); temp_sc2 = min( rand_sc2_0, rand_sc2_1 ); if (temp_sc2.x!= min_rand_sc2_sc2.x || temp_sc2.y!= min_rand_sc2_sc2.y) { failed = true; } return failed; }
if (failed) { rsSendToClientBlocking(RS_MSG_TEST_FAILED); } else { rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
void bug_char_test() { bool failed = false; failed |= test_bug_char();
random_line_split
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait { fn
(&self, x_align: f32, y_align: f32) -> () { unsafe { ffi::gtk_misc_set_alignment(GTK_MISC(self.unwrap_widget()), x_align as c_float, y_align as c_float); } } fn set_padding(&self, x_pad: i32, y_pad: i32) -> () { unsafe { ffi::gtk_misc_set_padding(GTK_MISC(self.unwrap_widget()), x_pad as c_int, y_pad as c_int); } } fn get_alignment(&self) -> (f32, f32) { let mut x: c_float = 0.; let mut y: c_float = 0.; unsafe { ffi::gtk_misc_get_alignment(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as f32, y as f32) } fn get_padding(&self) -> (i32, i32) { let mut x: c_int = 0; let mut y: c_int = 0; unsafe { ffi::gtk_misc_get_padding(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as i32, y as i32) } }
set_alignment
identifier_name
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait { fn set_alignment(&self, x_align: f32, y_align: f32) -> () { unsafe { ffi::gtk_misc_set_alignment(GTK_MISC(self.unwrap_widget()), x_align as c_float, y_align as c_float); } } fn set_padding(&self, x_pad: i32, y_pad: i32) -> () { unsafe { ffi::gtk_misc_set_padding(GTK_MISC(self.unwrap_widget()), x_pad as c_int, y_pad as c_int); } } fn get_alignment(&self) -> (f32, f32) { let mut x: c_float = 0.; let mut y: c_float = 0.; unsafe { ffi::gtk_misc_get_alignment(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as f32, y as f32) } fn get_padding(&self) -> (i32, i32) { let mut x: c_int = 0; let mut y: c_int = 0; unsafe { ffi::gtk_misc_get_padding(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); }
(x as i32, y as i32) } }
random_line_split
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait { fn set_alignment(&self, x_align: f32, y_align: f32) -> () { unsafe { ffi::gtk_misc_set_alignment(GTK_MISC(self.unwrap_widget()), x_align as c_float, y_align as c_float); } } fn set_padding(&self, x_pad: i32, y_pad: i32) -> ()
fn get_alignment(&self) -> (f32, f32) { let mut x: c_float = 0.; let mut y: c_float = 0.; unsafe { ffi::gtk_misc_get_alignment(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as f32, y as f32) } fn get_padding(&self) -> (i32, i32) { let mut x: c_int = 0; let mut y: c_int = 0; unsafe { ffi::gtk_misc_get_padding(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as i32, y as i32) } }
{ unsafe { ffi::gtk_misc_set_padding(GTK_MISC(self.unwrap_widget()), x_pad as c_int, y_pad as c_int); } }
identifier_body
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn
() { let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\ )".to_string()); } }
rem_test1
identifier_name
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn rem_test1()
}
{ let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\ )".to_string()); }
identifier_body
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn rem_test1() { let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 );
)".to_string()); } }
let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\
random_line_split
show.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast; use ast::{MetaItem, Expr,}; use codemap::Span; use ext::base::{ExtCtxt, Annotatable}; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token; use ptr::P; pub fn expand_deriving_show(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable)) { // &mut ::std::fmt::Formatter let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))), Borrowed(None, ast::MutMutable)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::fmt::Debug), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec![ MethodDef { name: "fmt", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: vec!(fmtr), ret_ty: Literal(path_std!(cx, core::fmt::Result)), attributes: Vec::new(), is_unsafe: false, combine_substructure: combine_substructure(Box::new(|a, b, c| { show_substructure(a, b, c) })) } ], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } /// We use the debug builders to do the heavy lifting here fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build() // or fmt.debug_tuple(<name>).field(&<fieldval>)....build() // based on the "shape". let name = match *substr.fields { Struct(_) => substr.type_ident, EnumMatching(_, v, _) => v.node.name, EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { cx.span_bug(span, "nonsensical.fields in `#[derive(Debug)]`")
// We want to make sure we have the expn_id set so that we can use unstable methods let span = Span { expn_id: cx.backtrace(),.. span }; let name = cx.expr_lit(span, ast::Lit_::LitStr(token::get_ident(name), ast::StrStyle::CookedStr)); let mut expr = substr.nonself_args[0].clone(); match *substr.fields { Struct(ref fields) | EnumMatching(_, _, ref fields) => { if fields.is_empty() || fields[0].name.is_none() { // tuple struct/"normal" variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_tuple"), vec![name]); for field in fields { // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![field]); } } else { // normal struct/struct variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_struct"), vec![name]); for field in fields { let name = cx.expr_lit(field.span, ast::Lit_::LitStr( token::get_ident(field.name.clone().unwrap()), ast::StrStyle::CookedStr)); // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![name, field]); } } } _ => unreachable!() } cx.expr_method_call(span, expr, token::str_to_ident("finish"), vec![]) }
} };
random_line_split
show.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast; use ast::{MetaItem, Expr,}; use codemap::Span; use ext::base::{ExtCtxt, Annotatable}; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token; use ptr::P; pub fn expand_deriving_show(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable))
combine_substructure: combine_substructure(Box::new(|a, b, c| { show_substructure(a, b, c) })) } ], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } /// We use the debug builders to do the heavy lifting here fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build() // or fmt.debug_tuple(<name>).field(&<fieldval>)....build() // based on the "shape". let name = match *substr.fields { Struct(_) => substr.type_ident, EnumMatching(_, v, _) => v.node.name, EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { cx.span_bug(span, "nonsensical.fields in `#[derive(Debug)]`") } }; // We want to make sure we have the expn_id set so that we can use unstable methods let span = Span { expn_id: cx.backtrace(),.. span }; let name = cx.expr_lit(span, ast::Lit_::LitStr(token::get_ident(name), ast::StrStyle::CookedStr)); let mut expr = substr.nonself_args[0].clone(); match *substr.fields { Struct(ref fields) | EnumMatching(_, _, ref fields) => { if fields.is_empty() || fields[0].name.is_none() { // tuple struct/"normal" variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_tuple"), vec![name]); for field in fields { // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![field]); } } else { // normal struct/struct variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_struct"), vec![name]); for field in fields { let name = cx.expr_lit(field.span, ast::Lit_::LitStr( token::get_ident(field.name.clone().unwrap()), ast::StrStyle::CookedStr)); // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![name, field]); } } } _ => unreachable!() } cx.expr_method_call(span, expr, token::str_to_ident("finish"), vec![]) }
{ // &mut ::std::fmt::Formatter let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))), Borrowed(None, ast::MutMutable)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::fmt::Debug), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec![ MethodDef { name: "fmt", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: vec!(fmtr), ret_ty: Literal(path_std!(cx, core::fmt::Result)), attributes: Vec::new(), is_unsafe: false,
identifier_body
show.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast; use ast::{MetaItem, Expr,}; use codemap::Span; use ext::base::{ExtCtxt, Annotatable}; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token; use ptr::P; pub fn expand_deriving_show(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable)) { // &mut ::std::fmt::Formatter let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))), Borrowed(None, ast::MutMutable)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::fmt::Debug), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec![ MethodDef { name: "fmt", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: vec!(fmtr), ret_ty: Literal(path_std!(cx, core::fmt::Result)), attributes: Vec::new(), is_unsafe: false, combine_substructure: combine_substructure(Box::new(|a, b, c| { show_substructure(a, b, c) })) } ], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } /// We use the debug builders to do the heavy lifting here fn
(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build() // or fmt.debug_tuple(<name>).field(&<fieldval>)....build() // based on the "shape". let name = match *substr.fields { Struct(_) => substr.type_ident, EnumMatching(_, v, _) => v.node.name, EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { cx.span_bug(span, "nonsensical.fields in `#[derive(Debug)]`") } }; // We want to make sure we have the expn_id set so that we can use unstable methods let span = Span { expn_id: cx.backtrace(),.. span }; let name = cx.expr_lit(span, ast::Lit_::LitStr(token::get_ident(name), ast::StrStyle::CookedStr)); let mut expr = substr.nonself_args[0].clone(); match *substr.fields { Struct(ref fields) | EnumMatching(_, _, ref fields) => { if fields.is_empty() || fields[0].name.is_none() { // tuple struct/"normal" variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_tuple"), vec![name]); for field in fields { // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![field]); } } else { // normal struct/struct variant expr = cx.expr_method_call(span, expr, token::str_to_ident("debug_struct"), vec![name]); for field in fields { let name = cx.expr_lit(field.span, ast::Lit_::LitStr( token::get_ident(field.name.clone().unwrap()), ast::StrStyle::CookedStr)); // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); expr = cx.expr_method_call(span, expr, token::str_to_ident("field"), vec![name, field]); } } } _ => unreachable!() } cx.expr_method_call(span, expr, token::str_to_ident("finish"), vec![]) }
show_substructure
identifier_name
context.rs
//- // Copyright (c) 2016, 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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. // // Ensync 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 // Ensync. If not, see <http://www.gnu.org/licenses/>. use std::cmp::{Ord, Ordering}; use std::collections::{BTreeMap, BinaryHeap, HashMap}; use std::ffi::{OsStr, OsString}; use std::num::Wrapping; use std::sync::Mutex; use crate::defs::*; use crate::log::Logger; use crate::replica::Replica; use crate::rules::engine::{DirEngine, FileEngine}; use crate::work_stack::WorkStack; // This whole thing is basically stable-man's-FnBox. We wrap an FnOnce in an // option and a box so we can make something approximating an FnMut (and which // thus can be invoked as a DST), while relegating the lifetime check to // runtime. struct TaskContainer<F: Send>(Mutex<Option<F>>); pub trait TaskT<T>: Send { fn invoke(&self, t: &T); } impl<T, F: FnOnce(&T) + Send> TaskT<T> for TaskContainer<F> { fn invoke(&self, t: &T) { self.0.lock().unwrap().take().unwrap()(t) } } pub type Task<T> = Box<dyn TaskT<T>>; pub fn task<T, F: FnOnce(&T) + Send +'static>(f: F) -> Task<T> { Box::new(TaskContainer(Mutex::new(Some(f)))) } /// Maps integer ids to unqueued tasks. struct UnqueuedTasksData<T> { tasks: HashMap<usize, T>, next_id: Wrapping<usize>, } pub struct UnqueuedTasks<T>(Mutex<UnqueuedTasksData<T>>); impl<T> UnqueuedTasks<T> { pub fn new() -> Self { UnqueuedTasks(Mutex::new(UnqueuedTasksData { tasks: HashMap::new(), next_id: Wrapping(0), })) } pub fn put(&self, task: T) -> usize { let mut lock = self.0.lock().unwrap(); while lock.tasks.contains_key(&lock.next_id.0) { lock.next_id = lock.next_id + Wrapping(1); } let id = lock.next_id.0; lock.next_id = lock.next_id + Wrapping(1); lock.tasks.insert(id, task); id } pub fn get(&self, id: usize) -> T { self.0.lock().unwrap().tasks.remove(&id).unwrap() } } pub struct Context<CLI, ANC, SRV> { pub cli: CLI, pub anc: ANC, pub srv: SRV, pub log: Box<dyn Logger + Send + Sync>, pub root_rules: FileEngine, pub work: WorkStack<Task<Self>>, pub tasks: UnqueuedTasks<Task<Self>>, } impl<CLI, ANC, SRV> Context<CLI, ANC, SRV> { pub fn run_work(&self)
} pub trait ContextExt { type Dir; } impl<CLI: Replica, ANC: Replica, SRV: Replica> ContextExt for Context<CLI, ANC, SRV> { type Dir = DirContext<CLI::Directory, ANC::Directory, SRV::Directory>; } /// Directory-specific context information for a single replica. pub struct SingleDirContext<T> { /// The `Replica::Directory` object. pub dir: T, /// The files in this directory when it was listed. pub files: BTreeMap<OsString, FileData>, } /// Directory-specific context information. pub struct DirContext<CD, AD, SD> { pub cli: SingleDirContext<CD>, pub anc: SingleDirContext<AD>, pub srv: SingleDirContext<SD>, /// Queue of filenames to process. Files are processed in approximately /// asciibetical order so that informational messages can give a rough idea /// of progress. pub todo: BinaryHeap<Reversed<OsString>>, pub rules: DirEngine, } impl<CD, AD, SD> DirContext<CD, AD, SD> { pub fn name_in_use(&self, name: &OsStr) -> bool { self.cli.files.contains_key(name) || self.anc.files.contains_key(name) || self.srv.files.contains_key(name) } } #[derive(PartialEq, Eq)] pub struct Reversed<T: Ord + PartialEq + Eq>(pub T); impl<T: Ord> PartialOrd<Reversed<T>> for Reversed<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T: Ord> Ord for Reversed<T> { fn cmp(&self, other: &Self) -> Ordering { other.0.cmp(&self.0) } }
{ self.work.run(|task| task.invoke(self)); }
identifier_body
context.rs
//- // Copyright (c) 2016, 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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. // // Ensync 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 // Ensync. If not, see <http://www.gnu.org/licenses/>. use std::cmp::{Ord, Ordering}; use std::collections::{BTreeMap, BinaryHeap, HashMap}; use std::ffi::{OsStr, OsString}; use std::num::Wrapping; use std::sync::Mutex; use crate::defs::*; use crate::log::Logger; use crate::replica::Replica; use crate::rules::engine::{DirEngine, FileEngine}; use crate::work_stack::WorkStack; // This whole thing is basically stable-man's-FnBox. We wrap an FnOnce in an // option and a box so we can make something approximating an FnMut (and which // thus can be invoked as a DST), while relegating the lifetime check to // runtime. struct
<F: Send>(Mutex<Option<F>>); pub trait TaskT<T>: Send { fn invoke(&self, t: &T); } impl<T, F: FnOnce(&T) + Send> TaskT<T> for TaskContainer<F> { fn invoke(&self, t: &T) { self.0.lock().unwrap().take().unwrap()(t) } } pub type Task<T> = Box<dyn TaskT<T>>; pub fn task<T, F: FnOnce(&T) + Send +'static>(f: F) -> Task<T> { Box::new(TaskContainer(Mutex::new(Some(f)))) } /// Maps integer ids to unqueued tasks. struct UnqueuedTasksData<T> { tasks: HashMap<usize, T>, next_id: Wrapping<usize>, } pub struct UnqueuedTasks<T>(Mutex<UnqueuedTasksData<T>>); impl<T> UnqueuedTasks<T> { pub fn new() -> Self { UnqueuedTasks(Mutex::new(UnqueuedTasksData { tasks: HashMap::new(), next_id: Wrapping(0), })) } pub fn put(&self, task: T) -> usize { let mut lock = self.0.lock().unwrap(); while lock.tasks.contains_key(&lock.next_id.0) { lock.next_id = lock.next_id + Wrapping(1); } let id = lock.next_id.0; lock.next_id = lock.next_id + Wrapping(1); lock.tasks.insert(id, task); id } pub fn get(&self, id: usize) -> T { self.0.lock().unwrap().tasks.remove(&id).unwrap() } } pub struct Context<CLI, ANC, SRV> { pub cli: CLI, pub anc: ANC, pub srv: SRV, pub log: Box<dyn Logger + Send + Sync>, pub root_rules: FileEngine, pub work: WorkStack<Task<Self>>, pub tasks: UnqueuedTasks<Task<Self>>, } impl<CLI, ANC, SRV> Context<CLI, ANC, SRV> { pub fn run_work(&self) { self.work.run(|task| task.invoke(self)); } } pub trait ContextExt { type Dir; } impl<CLI: Replica, ANC: Replica, SRV: Replica> ContextExt for Context<CLI, ANC, SRV> { type Dir = DirContext<CLI::Directory, ANC::Directory, SRV::Directory>; } /// Directory-specific context information for a single replica. pub struct SingleDirContext<T> { /// The `Replica::Directory` object. pub dir: T, /// The files in this directory when it was listed. pub files: BTreeMap<OsString, FileData>, } /// Directory-specific context information. pub struct DirContext<CD, AD, SD> { pub cli: SingleDirContext<CD>, pub anc: SingleDirContext<AD>, pub srv: SingleDirContext<SD>, /// Queue of filenames to process. Files are processed in approximately /// asciibetical order so that informational messages can give a rough idea /// of progress. pub todo: BinaryHeap<Reversed<OsString>>, pub rules: DirEngine, } impl<CD, AD, SD> DirContext<CD, AD, SD> { pub fn name_in_use(&self, name: &OsStr) -> bool { self.cli.files.contains_key(name) || self.anc.files.contains_key(name) || self.srv.files.contains_key(name) } } #[derive(PartialEq, Eq)] pub struct Reversed<T: Ord + PartialEq + Eq>(pub T); impl<T: Ord> PartialOrd<Reversed<T>> for Reversed<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T: Ord> Ord for Reversed<T> { fn cmp(&self, other: &Self) -> Ordering { other.0.cmp(&self.0) } }
TaskContainer
identifier_name
context.rs
//- // Copyright (c) 2016, 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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. // // Ensync 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 // Ensync. If not, see <http://www.gnu.org/licenses/>. use std::cmp::{Ord, Ordering}; use std::collections::{BTreeMap, BinaryHeap, HashMap}; use std::ffi::{OsStr, OsString}; use std::num::Wrapping; use std::sync::Mutex; use crate::defs::*; use crate::log::Logger; use crate::replica::Replica; use crate::rules::engine::{DirEngine, FileEngine}; use crate::work_stack::WorkStack; // This whole thing is basically stable-man's-FnBox. We wrap an FnOnce in an // option and a box so we can make something approximating an FnMut (and which // thus can be invoked as a DST), while relegating the lifetime check to // runtime. struct TaskContainer<F: Send>(Mutex<Option<F>>); pub trait TaskT<T>: Send { fn invoke(&self, t: &T); } impl<T, F: FnOnce(&T) + Send> TaskT<T> for TaskContainer<F> { fn invoke(&self, t: &T) { self.0.lock().unwrap().take().unwrap()(t) } } pub type Task<T> = Box<dyn TaskT<T>>; pub fn task<T, F: FnOnce(&T) + Send +'static>(f: F) -> Task<T> { Box::new(TaskContainer(Mutex::new(Some(f)))) } /// Maps integer ids to unqueued tasks. struct UnqueuedTasksData<T> { tasks: HashMap<usize, T>, next_id: Wrapping<usize>, } pub struct UnqueuedTasks<T>(Mutex<UnqueuedTasksData<T>>); impl<T> UnqueuedTasks<T> { pub fn new() -> Self { UnqueuedTasks(Mutex::new(UnqueuedTasksData { tasks: HashMap::new(), next_id: Wrapping(0), })) } pub fn put(&self, task: T) -> usize { let mut lock = self.0.lock().unwrap(); while lock.tasks.contains_key(&lock.next_id.0) { lock.next_id = lock.next_id + Wrapping(1); } let id = lock.next_id.0; lock.next_id = lock.next_id + Wrapping(1); lock.tasks.insert(id, task); id } pub fn get(&self, id: usize) -> T { self.0.lock().unwrap().tasks.remove(&id).unwrap() } } pub struct Context<CLI, ANC, SRV> { pub cli: CLI, pub anc: ANC, pub srv: SRV, pub log: Box<dyn Logger + Send + Sync>, pub root_rules: FileEngine, pub work: WorkStack<Task<Self>>, pub tasks: UnqueuedTasks<Task<Self>>, } impl<CLI, ANC, SRV> Context<CLI, ANC, SRV> { pub fn run_work(&self) { self.work.run(|task| task.invoke(self)); } } pub trait ContextExt { type Dir; } impl<CLI: Replica, ANC: Replica, SRV: Replica> ContextExt for Context<CLI, ANC, SRV> { type Dir = DirContext<CLI::Directory, ANC::Directory, SRV::Directory>; } /// Directory-specific context information for a single replica. pub struct SingleDirContext<T> { /// The `Replica::Directory` object. pub dir: T, /// The files in this directory when it was listed. pub files: BTreeMap<OsString, FileData>, } /// Directory-specific context information. pub struct DirContext<CD, AD, SD> { pub cli: SingleDirContext<CD>, pub anc: SingleDirContext<AD>, pub srv: SingleDirContext<SD>, /// Queue of filenames to process. Files are processed in approximately /// asciibetical order so that informational messages can give a rough idea /// of progress. pub todo: BinaryHeap<Reversed<OsString>>, pub rules: DirEngine, } impl<CD, AD, SD> DirContext<CD, AD, SD> { pub fn name_in_use(&self, name: &OsStr) -> bool { self.cli.files.contains_key(name) || self.anc.files.contains_key(name) || self.srv.files.contains_key(name) } } #[derive(PartialEq, Eq)] pub struct Reversed<T: Ord + PartialEq + Eq>(pub T); impl<T: Ord> PartialOrd<Reversed<T>> for Reversed<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
impl<T: Ord> Ord for Reversed<T> { fn cmp(&self, other: &Self) -> Ordering { other.0.cmp(&self.0) } }
}
random_line_split
unwind-misc-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_NEWRT=1 // error-pattern:fail use std::vec; use std::collections; use std::gc::GC; fn main()
{ let _count = box(GC) 0u; let mut map = collections::HashMap::new(); let mut arr = Vec::new(); for _i in range(0u, 10u) { arr.push(box(GC) "key stuff".to_string()); map.insert(arr.clone(), arr.clone().append([box(GC) "value stuff".to_string()])); if arr.len() == 5 { fail!(); } } }
identifier_body
unwind-misc-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_NEWRT=1 // error-pattern:fail use std::vec; use std::collections; use std::gc::GC; fn main() { let _count = box(GC) 0u; let mut map = collections::HashMap::new(); let mut arr = Vec::new(); for _i in range(0u, 10u) { arr.push(box(GC) "key stuff".to_string()); map.insert(arr.clone(), arr.clone().append([box(GC) "value stuff".to_string()])); if arr.len() == 5 {
fail!(); } } }
random_line_split
unwind-misc-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_NEWRT=1 // error-pattern:fail use std::vec; use std::collections; use std::gc::GC; fn
() { let _count = box(GC) 0u; let mut map = collections::HashMap::new(); let mut arr = Vec::new(); for _i in range(0u, 10u) { arr.push(box(GC) "key stuff".to_string()); map.insert(arr.clone(), arr.clone().append([box(GC) "value stuff".to_string()])); if arr.len() == 5 { fail!(); } } }
main
identifier_name
unwind-misc-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_NEWRT=1 // error-pattern:fail use std::vec; use std::collections; use std::gc::GC; fn main() { let _count = box(GC) 0u; let mut map = collections::HashMap::new(); let mut arr = Vec::new(); for _i in range(0u, 10u) { arr.push(box(GC) "key stuff".to_string()); map.insert(arr.clone(), arr.clone().append([box(GC) "value stuff".to_string()])); if arr.len() == 5
} }
{ fail!(); }
conditional_block
fact.rs
// @author: Constantine Apostolou // @description: // Testing how recursive implementation of a function // that computes the factorial behaves in Rust. // @license: GNU GPL v3 // We add the following line to be able to "use" everything // in a library, since the "lib::*" feature is experimental. #![feature(globs)] // We include the external libc crate. extern crate libc; // And we use the needed libraries. use std::*; use libc::*; // Compute the factorial of a number in a // recursive manner. The parameter n is the // number of which we want to find the factorial. fn fact(n: u64) -> u64
// Computes the factorial of a manner in a // tail-recursive manner. From the parameters: // 'n' is the number of which we want to find the factorial. // 'a' is initialy 1 and will carry the result of the // computation of the factorial. fn facttail(n: u64, a: u64) -> u64 { if n == 1 { return a; } else if n == 0 { return 1; } else { if n < 0 { return 0; } return facttail(n - 1, n * a); } } // Main entry to the program: fn main() { // Store the parameters that were passed through the terminal // to the program. let args: Vec<String> = os::args(); // Check if we have enough arguments; if we don't, then we need // to exit the program, as the nex step will result in an error. if args.len() < 2 { println!("Usage: fact [number]"); println!("\tThis program computes the factorial of a given number."); println!("\t[number] must be a positive number."); unsafe { exit(1 as c_int); } } // This step does not check if we have a character/string instead // of a number. // Save the number that is in the second command line argument. let num: u64 = from_str::<u64>(args.get(1).as_slice()).unwrap(); // Run the two functions that compute the factorial. let res = fact(num); // Compute in a recursive manner. let ret = facttail(num, 1); // Compute in a tail-recursive manner. // Finally print the results. println!("Result of fact({}) -> {}", num, res); println!("Result of facttail({}, 1) -> {}", num, ret); }
{ if n < 2 { 1 } else { n * fact(n - 1) } }
identifier_body
fact.rs
// @author: Constantine Apostolou // @description: // Testing how recursive implementation of a function // that computes the factorial behaves in Rust. // @license: GNU GPL v3 // We add the following line to be able to "use" everything // in a library, since the "lib::*" feature is experimental. #![feature(globs)] // We include the external libc crate. extern crate libc; // And we use the needed libraries. use std::*; use libc::*; // Compute the factorial of a number in a // recursive manner. The parameter n is the // number of which we want to find the factorial. fn fact(n: u64) -> u64 { if n < 2
else { n * fact(n - 1) } } // Computes the factorial of a manner in a // tail-recursive manner. From the parameters: // 'n' is the number of which we want to find the factorial. // 'a' is initialy 1 and will carry the result of the // computation of the factorial. fn facttail(n: u64, a: u64) -> u64 { if n == 1 { return a; } else if n == 0 { return 1; } else { if n < 0 { return 0; } return facttail(n - 1, n * a); } } // Main entry to the program: fn main() { // Store the parameters that were passed through the terminal // to the program. let args: Vec<String> = os::args(); // Check if we have enough arguments; if we don't, then we need // to exit the program, as the nex step will result in an error. if args.len() < 2 { println!("Usage: fact [number]"); println!("\tThis program computes the factorial of a given number."); println!("\t[number] must be a positive number."); unsafe { exit(1 as c_int); } } // This step does not check if we have a character/string instead // of a number. // Save the number that is in the second command line argument. let num: u64 = from_str::<u64>(args.get(1).as_slice()).unwrap(); // Run the two functions that compute the factorial. let res = fact(num); // Compute in a recursive manner. let ret = facttail(num, 1); // Compute in a tail-recursive manner. // Finally print the results. println!("Result of fact({}) -> {}", num, res); println!("Result of facttail({}, 1) -> {}", num, ret); }
{ 1 }
conditional_block
fact.rs
// @author: Constantine Apostolou // @description: // Testing how recursive implementation of a function // that computes the factorial behaves in Rust. // @license: GNU GPL v3 // We add the following line to be able to "use" everything // in a library, since the "lib::*" feature is experimental. #![feature(globs)] // We include the external libc crate. extern crate libc; // And we use the needed libraries. use std::*; use libc::*; // Compute the factorial of a number in a // recursive manner. The parameter n is the // number of which we want to find the factorial. fn fact(n: u64) -> u64 { if n < 2 { 1 } else { n * fact(n - 1) } } // Computes the factorial of a manner in a // tail-recursive manner. From the parameters: // 'n' is the number of which we want to find the factorial. // 'a' is initialy 1 and will carry the result of the // computation of the factorial. fn
(n: u64, a: u64) -> u64 { if n == 1 { return a; } else if n == 0 { return 1; } else { if n < 0 { return 0; } return facttail(n - 1, n * a); } } // Main entry to the program: fn main() { // Store the parameters that were passed through the terminal // to the program. let args: Vec<String> = os::args(); // Check if we have enough arguments; if we don't, then we need // to exit the program, as the nex step will result in an error. if args.len() < 2 { println!("Usage: fact [number]"); println!("\tThis program computes the factorial of a given number."); println!("\t[number] must be a positive number."); unsafe { exit(1 as c_int); } } // This step does not check if we have a character/string instead // of a number. // Save the number that is in the second command line argument. let num: u64 = from_str::<u64>(args.get(1).as_slice()).unwrap(); // Run the two functions that compute the factorial. let res = fact(num); // Compute in a recursive manner. let ret = facttail(num, 1); // Compute in a tail-recursive manner. // Finally print the results. println!("Result of fact({}) -> {}", num, res); println!("Result of facttail({}, 1) -> {}", num, ret); }
facttail
identifier_name
fact.rs
// @author: Constantine Apostolou // @description: // Testing how recursive implementation of a function // that computes the factorial behaves in Rust. // @license: GNU GPL v3 // We add the following line to be able to "use" everything // in a library, since the "lib::*" feature is experimental. #![feature(globs)] // We include the external libc crate. extern crate libc; // And we use the needed libraries. use std::*; use libc::*; // Compute the factorial of a number in a // recursive manner. The parameter n is the // number of which we want to find the factorial. fn fact(n: u64) -> u64 { if n < 2 { 1 } else { n * fact(n - 1) } } // Computes the factorial of a manner in a // tail-recursive manner. From the parameters: // 'n' is the number of which we want to find the factorial. // 'a' is initialy 1 and will carry the result of the // computation of the factorial. fn facttail(n: u64, a: u64) -> u64 { if n == 1 { return a; } else if n == 0 { return 1; } else { if n < 0 { return 0; } return facttail(n - 1, n * a); } } // Main entry to the program: fn main() { // Store the parameters that were passed through the terminal // to the program. let args: Vec<String> = os::args(); // Check if we have enough arguments; if we don't, then we need // to exit the program, as the nex step will result in an error.
println!("\tThis program computes the factorial of a given number."); println!("\t[number] must be a positive number."); unsafe { exit(1 as c_int); } } // This step does not check if we have a character/string instead // of a number. // Save the number that is in the second command line argument. let num: u64 = from_str::<u64>(args.get(1).as_slice()).unwrap(); // Run the two functions that compute the factorial. let res = fact(num); // Compute in a recursive manner. let ret = facttail(num, 1); // Compute in a tail-recursive manner. // Finally print the results. println!("Result of fact({}) -> {}", num, res); println!("Result of facttail({}, 1) -> {}", num, ret); }
if args.len() < 2 { println!("Usage: fact [number]");
random_line_split
int.rs
// This file is part of Mooneye GB. // Copyright (C) 2014-2020 Joonas Javanainen <[email protected]> // // Mooneye GB 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. // // Mooneye GB 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 Mooneye GB. If not, see <http://www.gnu.org/licenses/>. use num_traits::{PrimInt, WrappingAdd, WrappingSub}; #[cfg(test)] use quickcheck::quickcheck; pub trait IntExt { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI fn isolate_rightmost_one(self) -> Self; /// Returns the specified bit as 0 or 1 fn bit(self, bit: usize) -> Self; /// Returns the specified bit as boolean fn bit_bool(self, bit: usize) -> bool; /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK fn activate_rightmost_zeros(self) -> Self; /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool;
{ /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI #[inline(always)] fn isolate_rightmost_one(self) -> Self { let x = self; // Unsigned negation: -x ==!x + 1 let minus_x = (!x).wrapping_add(&Self::one()); // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x & minus_x } /// Returns the specified bit as 0 or 1 #[inline(always)] fn bit(self, bit: usize) -> Self { (self >> bit) & Self::one() } /// Returns the specified bit as boolean #[inline(always)] fn bit_bool(self, bit: usize) -> bool { !self.bit(bit).is_zero() } /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK #[inline(always)] fn activate_rightmost_zeros(self) -> Self { let x = self; // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x | x.wrapping_sub(&Self::one()) } /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit #[inline(always)] fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool { // Create a mask that includes the specified bit and 1-bits on the right side // e.g. for u8: // bit=0 -> 0000 0001 // bit=3 -> 0000 1111 // bit=6 -> 0111 1111 let mask = (Self::one() << bit).activate_rightmost_zeros(); (a & mask) + (b & mask) > mask } } #[cfg(test)] fn test_isolate_rightmost_one<T: PrimInt + WrappingAdd + WrappingSub>(x: T) -> bool { let y = x.isolate_rightmost_one(); if x.is_zero() { y.is_zero() } else { let mut value = x; let mut expected = T::one(); while!value.bit_bool(0) { value = value >> 1; expected = expected << 1; } y == expected } } #[cfg(test)] #[test] fn test_u8_isolate_rightmost_one() { fn prop(x: u8) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u8) -> bool); } #[cfg(test)] #[test] fn test_u16_isolate_rightmost_one() { fn prop(x: u16) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u16) -> bool); }
} impl<T> IntExt for T where T: PrimInt + WrappingAdd + WrappingSub,
random_line_split
int.rs
// This file is part of Mooneye GB. // Copyright (C) 2014-2020 Joonas Javanainen <[email protected]> // // Mooneye GB 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. // // Mooneye GB 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 Mooneye GB. If not, see <http://www.gnu.org/licenses/>. use num_traits::{PrimInt, WrappingAdd, WrappingSub}; #[cfg(test)] use quickcheck::quickcheck; pub trait IntExt { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI fn isolate_rightmost_one(self) -> Self; /// Returns the specified bit as 0 or 1 fn bit(self, bit: usize) -> Self; /// Returns the specified bit as boolean fn bit_bool(self, bit: usize) -> bool; /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK fn activate_rightmost_zeros(self) -> Self; /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool; } impl<T> IntExt for T where T: PrimInt + WrappingAdd + WrappingSub, { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI #[inline(always)] fn isolate_rightmost_one(self) -> Self { let x = self; // Unsigned negation: -x ==!x + 1 let minus_x = (!x).wrapping_add(&Self::one()); // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x & minus_x } /// Returns the specified bit as 0 or 1 #[inline(always)] fn bit(self, bit: usize) -> Self { (self >> bit) & Self::one() } /// Returns the specified bit as boolean #[inline(always)] fn bit_bool(self, bit: usize) -> bool { !self.bit(bit).is_zero() } /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK #[inline(always)] fn activate_rightmost_zeros(self) -> Self { let x = self; // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x | x.wrapping_sub(&Self::one()) } /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit #[inline(always)] fn
(bit: usize, a: Self, b: Self) -> bool { // Create a mask that includes the specified bit and 1-bits on the right side // e.g. for u8: // bit=0 -> 0000 0001 // bit=3 -> 0000 1111 // bit=6 -> 0111 1111 let mask = (Self::one() << bit).activate_rightmost_zeros(); (a & mask) + (b & mask) > mask } } #[cfg(test)] fn test_isolate_rightmost_one<T: PrimInt + WrappingAdd + WrappingSub>(x: T) -> bool { let y = x.isolate_rightmost_one(); if x.is_zero() { y.is_zero() } else { let mut value = x; let mut expected = T::one(); while!value.bit_bool(0) { value = value >> 1; expected = expected << 1; } y == expected } } #[cfg(test)] #[test] fn test_u8_isolate_rightmost_one() { fn prop(x: u8) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u8) -> bool); } #[cfg(test)] #[test] fn test_u16_isolate_rightmost_one() { fn prop(x: u16) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u16) -> bool); }
test_add_carry_bit
identifier_name
int.rs
// This file is part of Mooneye GB. // Copyright (C) 2014-2020 Joonas Javanainen <[email protected]> // // Mooneye GB 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. // // Mooneye GB 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 Mooneye GB. If not, see <http://www.gnu.org/licenses/>. use num_traits::{PrimInt, WrappingAdd, WrappingSub}; #[cfg(test)] use quickcheck::quickcheck; pub trait IntExt { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI fn isolate_rightmost_one(self) -> Self; /// Returns the specified bit as 0 or 1 fn bit(self, bit: usize) -> Self; /// Returns the specified bit as boolean fn bit_bool(self, bit: usize) -> bool; /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK fn activate_rightmost_zeros(self) -> Self; /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool; } impl<T> IntExt for T where T: PrimInt + WrappingAdd + WrappingSub, { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI #[inline(always)] fn isolate_rightmost_one(self) -> Self { let x = self; // Unsigned negation: -x ==!x + 1 let minus_x = (!x).wrapping_add(&Self::one()); // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x & minus_x } /// Returns the specified bit as 0 or 1 #[inline(always)] fn bit(self, bit: usize) -> Self { (self >> bit) & Self::one() } /// Returns the specified bit as boolean #[inline(always)] fn bit_bool(self, bit: usize) -> bool { !self.bit(bit).is_zero() } /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK #[inline(always)] fn activate_rightmost_zeros(self) -> Self { let x = self; // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x | x.wrapping_sub(&Self::one()) } /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit #[inline(always)] fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool { // Create a mask that includes the specified bit and 1-bits on the right side // e.g. for u8: // bit=0 -> 0000 0001 // bit=3 -> 0000 1111 // bit=6 -> 0111 1111 let mask = (Self::one() << bit).activate_rightmost_zeros(); (a & mask) + (b & mask) > mask } } #[cfg(test)] fn test_isolate_rightmost_one<T: PrimInt + WrappingAdd + WrappingSub>(x: T) -> bool { let y = x.isolate_rightmost_one(); if x.is_zero() { y.is_zero() } else
} #[cfg(test)] #[test] fn test_u8_isolate_rightmost_one() { fn prop(x: u8) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u8) -> bool); } #[cfg(test)] #[test] fn test_u16_isolate_rightmost_one() { fn prop(x: u16) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u16) -> bool); }
{ let mut value = x; let mut expected = T::one(); while !value.bit_bool(0) { value = value >> 1; expected = expected << 1; } y == expected }
conditional_block
int.rs
// This file is part of Mooneye GB. // Copyright (C) 2014-2020 Joonas Javanainen <[email protected]> // // Mooneye GB 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. // // Mooneye GB 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 Mooneye GB. If not, see <http://www.gnu.org/licenses/>. use num_traits::{PrimInt, WrappingAdd, WrappingSub}; #[cfg(test)] use quickcheck::quickcheck; pub trait IntExt { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI fn isolate_rightmost_one(self) -> Self; /// Returns the specified bit as 0 or 1 fn bit(self, bit: usize) -> Self; /// Returns the specified bit as boolean fn bit_bool(self, bit: usize) -> bool; /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK fn activate_rightmost_zeros(self) -> Self; /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool; } impl<T> IntExt for T where T: PrimInt + WrappingAdd + WrappingSub, { /// Isolates the rightmost 1-bit leaving all other bits as 0 /// e.g. 1010 1000 -> 0000 1000 /// /// Equivalent to Intel BMI1 instruction BLSI #[inline(always)] fn isolate_rightmost_one(self) -> Self { let x = self; // Unsigned negation: -x ==!x + 1 let minus_x = (!x).wrapping_add(&Self::one()); // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x & minus_x } /// Returns the specified bit as 0 or 1 #[inline(always)] fn bit(self, bit: usize) -> Self { (self >> bit) & Self::one() } /// Returns the specified bit as boolean #[inline(always)] fn bit_bool(self, bit: usize) -> bool { !self.bit(bit).is_zero() } /// Sets all rightmost 0-bits to 1 /// e.g. 1010 1000 -> 1010 1111 /// /// Equivalent to Intel BMI1 instruction BLSMSK #[inline(always)] fn activate_rightmost_zeros(self) -> Self { let x = self; // Hacker's Delight 2nd ed, 2-1 Manipulating Rightmost Bits x | x.wrapping_sub(&Self::one()) } /// Tests if addition results in a carry from the specified bit. /// Does not support overflow, so cannot be used to check carry from the leftmost bit #[inline(always)] fn test_add_carry_bit(bit: usize, a: Self, b: Self) -> bool { // Create a mask that includes the specified bit and 1-bits on the right side // e.g. for u8: // bit=0 -> 0000 0001 // bit=3 -> 0000 1111 // bit=6 -> 0111 1111 let mask = (Self::one() << bit).activate_rightmost_zeros(); (a & mask) + (b & mask) > mask } } #[cfg(test)] fn test_isolate_rightmost_one<T: PrimInt + WrappingAdd + WrappingSub>(x: T) -> bool { let y = x.isolate_rightmost_one(); if x.is_zero() { y.is_zero() } else { let mut value = x; let mut expected = T::one(); while!value.bit_bool(0) { value = value >> 1; expected = expected << 1; } y == expected } } #[cfg(test)] #[test] fn test_u8_isolate_rightmost_one()
#[cfg(test)] #[test] fn test_u16_isolate_rightmost_one() { fn prop(x: u16) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u16) -> bool); }
{ fn prop(x: u8) -> bool { test_isolate_rightmost_one(x) } quickcheck(prop as fn(u8) -> bool); }
identifier_body
poly.rs
use std::iter::Iterator; use super::{Circ, Line, Rect, Shape, Vector2}; pub struct Poly { pub pos: Vector2, pub rotation: f32, pub scale: f32, pub origin: Vector2, pub points: Vec<Vector2>, } impl Poly { pub fn new(pos: Vector2, points: Vec<Vector2>) -> Poly { Poly { pos: pos, origin: Vector2::new(0f32, 0f32), rotation: 0f32, scale: 1f32, points: points, } } pub fn from_rect(rect: Rect, origin: Vector2) -> Poly { Poly { pos: Vector2::new(rect.x, rect.y), origin: origin, rotation: 0f32, scale: 1f32, points: vec![Vector2::new(0f32, 0f32), Vector2::new(0f32, rect.height), Vector2::new(rect.width, rect.height), Vector2::new(rect.width, 0f32)], } } pub fn vertex(&self, index: usize) -> Vector2 { let original = self.points[index]; // Transform the vector with the origin let moved = original - self.origin; // Rotate and scale the vector let transformed = moved.rotate(self.rotation).scl(self.scale); // Move the transformed vector back into the correct coordinate space transformed + self.pos + self.origin } } impl Shape for Poly { fn set_position(&mut self, x: f32, y: f32) -> () { self.pos.x = x; self.pos.y = y; } fn get_position(&self) -> Vector2 { return self.pos; } fn intersects(&self, line: Line) -> bool { for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); if line.intersects(face) { return true; } } return false; } fn contains(&self, point: Vector2) -> bool { let mut i = 0; let mut j = self.points.len() - 1; let mut c = 0; while i < self.points.len() { if ((self.vertex(i).y > point.y)!= (self.vertex(j).y > point.y)) && (point.x < (self.vertex(j).x - self.vertex(i).x) * (point.y - self.vertex(i).y) / (self.vertex(j).y - self.vertex(i).y) + self.vertex(i).x) { c =!c; } j = i; i += 1; } return c!= 0; } fn overlaps_rect(&self, rect: Rect) -> bool { self.overlaps(&rect) } fn overlaps_circ(&self, circ: Circ) -> bool { self.overlaps(&circ) }
fn overlaps<T: Shape>(&self, shape: &T) -> bool { if self.contains(shape.get_position()) { return true; } for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); println!("{}:{}, {}:{}", one.x, one.y, two.x, two.y); if shape.contains(one) || shape.intersects(face) { return true; } } return false; } fn get_bounding_box(&self) -> Rect { let get_x = |vector: &Vector2| vector.x; let get_y = |vector: &Vector2| vector.y; let minimum = |a, b| { if b < a { b } else { a } }; let maximum = |a, b| { if b > a { b } else { a } }; let x = self.points[0].x; let y = self.points[0].y; let min_x = self.points.iter().map(&get_x).fold(x, &minimum); let min_y = self.points.iter().map(&get_y).fold(y, &minimum); let max_x = self.points.iter().map(&get_x).fold(x, &maximum); let max_y = self.points.iter().map(&get_y).fold(y, &maximum); Rect::new(min_x, min_y, max_x - min_x, max_y - min_y) } }
fn overlaps_poly(&self, poly: &Poly) -> bool { self.overlaps(poly) }
random_line_split
poly.rs
use std::iter::Iterator; use super::{Circ, Line, Rect, Shape, Vector2}; pub struct Poly { pub pos: Vector2, pub rotation: f32, pub scale: f32, pub origin: Vector2, pub points: Vec<Vector2>, } impl Poly { pub fn new(pos: Vector2, points: Vec<Vector2>) -> Poly { Poly { pos: pos, origin: Vector2::new(0f32, 0f32), rotation: 0f32, scale: 1f32, points: points, } } pub fn
(rect: Rect, origin: Vector2) -> Poly { Poly { pos: Vector2::new(rect.x, rect.y), origin: origin, rotation: 0f32, scale: 1f32, points: vec![Vector2::new(0f32, 0f32), Vector2::new(0f32, rect.height), Vector2::new(rect.width, rect.height), Vector2::new(rect.width, 0f32)], } } pub fn vertex(&self, index: usize) -> Vector2 { let original = self.points[index]; // Transform the vector with the origin let moved = original - self.origin; // Rotate and scale the vector let transformed = moved.rotate(self.rotation).scl(self.scale); // Move the transformed vector back into the correct coordinate space transformed + self.pos + self.origin } } impl Shape for Poly { fn set_position(&mut self, x: f32, y: f32) -> () { self.pos.x = x; self.pos.y = y; } fn get_position(&self) -> Vector2 { return self.pos; } fn intersects(&self, line: Line) -> bool { for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); if line.intersects(face) { return true; } } return false; } fn contains(&self, point: Vector2) -> bool { let mut i = 0; let mut j = self.points.len() - 1; let mut c = 0; while i < self.points.len() { if ((self.vertex(i).y > point.y)!= (self.vertex(j).y > point.y)) && (point.x < (self.vertex(j).x - self.vertex(i).x) * (point.y - self.vertex(i).y) / (self.vertex(j).y - self.vertex(i).y) + self.vertex(i).x) { c =!c; } j = i; i += 1; } return c!= 0; } fn overlaps_rect(&self, rect: Rect) -> bool { self.overlaps(&rect) } fn overlaps_circ(&self, circ: Circ) -> bool { self.overlaps(&circ) } fn overlaps_poly(&self, poly: &Poly) -> bool { self.overlaps(poly) } fn overlaps<T: Shape>(&self, shape: &T) -> bool { if self.contains(shape.get_position()) { return true; } for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); println!("{}:{}, {}:{}", one.x, one.y, two.x, two.y); if shape.contains(one) || shape.intersects(face) { return true; } } return false; } fn get_bounding_box(&self) -> Rect { let get_x = |vector: &Vector2| vector.x; let get_y = |vector: &Vector2| vector.y; let minimum = |a, b| { if b < a { b } else { a } }; let maximum = |a, b| { if b > a { b } else { a } }; let x = self.points[0].x; let y = self.points[0].y; let min_x = self.points.iter().map(&get_x).fold(x, &minimum); let min_y = self.points.iter().map(&get_y).fold(y, &minimum); let max_x = self.points.iter().map(&get_x).fold(x, &maximum); let max_y = self.points.iter().map(&get_y).fold(y, &maximum); Rect::new(min_x, min_y, max_x - min_x, max_y - min_y) } }
from_rect
identifier_name
poly.rs
use std::iter::Iterator; use super::{Circ, Line, Rect, Shape, Vector2}; pub struct Poly { pub pos: Vector2, pub rotation: f32, pub scale: f32, pub origin: Vector2, pub points: Vec<Vector2>, } impl Poly { pub fn new(pos: Vector2, points: Vec<Vector2>) -> Poly { Poly { pos: pos, origin: Vector2::new(0f32, 0f32), rotation: 0f32, scale: 1f32, points: points, } } pub fn from_rect(rect: Rect, origin: Vector2) -> Poly { Poly { pos: Vector2::new(rect.x, rect.y), origin: origin, rotation: 0f32, scale: 1f32, points: vec![Vector2::new(0f32, 0f32), Vector2::new(0f32, rect.height), Vector2::new(rect.width, rect.height), Vector2::new(rect.width, 0f32)], } } pub fn vertex(&self, index: usize) -> Vector2 { let original = self.points[index]; // Transform the vector with the origin let moved = original - self.origin; // Rotate and scale the vector let transformed = moved.rotate(self.rotation).scl(self.scale); // Move the transformed vector back into the correct coordinate space transformed + self.pos + self.origin } } impl Shape for Poly { fn set_position(&mut self, x: f32, y: f32) -> () { self.pos.x = x; self.pos.y = y; } fn get_position(&self) -> Vector2 { return self.pos; } fn intersects(&self, line: Line) -> bool { for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); if line.intersects(face) { return true; } } return false; } fn contains(&self, point: Vector2) -> bool { let mut i = 0; let mut j = self.points.len() - 1; let mut c = 0; while i < self.points.len() { if ((self.vertex(i).y > point.y)!= (self.vertex(j).y > point.y)) && (point.x < (self.vertex(j).x - self.vertex(i).x) * (point.y - self.vertex(i).y) / (self.vertex(j).y - self.vertex(i).y) + self.vertex(i).x) { c =!c; } j = i; i += 1; } return c!= 0; } fn overlaps_rect(&self, rect: Rect) -> bool { self.overlaps(&rect) } fn overlaps_circ(&self, circ: Circ) -> bool { self.overlaps(&circ) } fn overlaps_poly(&self, poly: &Poly) -> bool { self.overlaps(poly) } fn overlaps<T: Shape>(&self, shape: &T) -> bool { if self.contains(shape.get_position()) { return true; } for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); println!("{}:{}, {}:{}", one.x, one.y, two.x, two.y); if shape.contains(one) || shape.intersects(face) { return true; } } return false; } fn get_bounding_box(&self) -> Rect
}
{ let get_x = |vector: &Vector2| vector.x; let get_y = |vector: &Vector2| vector.y; let minimum = |a, b| { if b < a { b } else { a } }; let maximum = |a, b| { if b > a { b } else { a } }; let x = self.points[0].x; let y = self.points[0].y; let min_x = self.points.iter().map(&get_x).fold(x, &minimum); let min_y = self.points.iter().map(&get_y).fold(y, &minimum); let max_x = self.points.iter().map(&get_x).fold(x, &maximum); let max_y = self.points.iter().map(&get_y).fold(y, &maximum); Rect::new(min_x, min_y, max_x - min_x, max_y - min_y) }
identifier_body
poly.rs
use std::iter::Iterator; use super::{Circ, Line, Rect, Shape, Vector2}; pub struct Poly { pub pos: Vector2, pub rotation: f32, pub scale: f32, pub origin: Vector2, pub points: Vec<Vector2>, } impl Poly { pub fn new(pos: Vector2, points: Vec<Vector2>) -> Poly { Poly { pos: pos, origin: Vector2::new(0f32, 0f32), rotation: 0f32, scale: 1f32, points: points, } } pub fn from_rect(rect: Rect, origin: Vector2) -> Poly { Poly { pos: Vector2::new(rect.x, rect.y), origin: origin, rotation: 0f32, scale: 1f32, points: vec![Vector2::new(0f32, 0f32), Vector2::new(0f32, rect.height), Vector2::new(rect.width, rect.height), Vector2::new(rect.width, 0f32)], } } pub fn vertex(&self, index: usize) -> Vector2 { let original = self.points[index]; // Transform the vector with the origin let moved = original - self.origin; // Rotate and scale the vector let transformed = moved.rotate(self.rotation).scl(self.scale); // Move the transformed vector back into the correct coordinate space transformed + self.pos + self.origin } } impl Shape for Poly { fn set_position(&mut self, x: f32, y: f32) -> () { self.pos.x = x; self.pos.y = y; } fn get_position(&self) -> Vector2 { return self.pos; } fn intersects(&self, line: Line) -> bool { for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); if line.intersects(face) { return true; } } return false; } fn contains(&self, point: Vector2) -> bool { let mut i = 0; let mut j = self.points.len() - 1; let mut c = 0; while i < self.points.len() { if ((self.vertex(i).y > point.y)!= (self.vertex(j).y > point.y)) && (point.x < (self.vertex(j).x - self.vertex(i).x) * (point.y - self.vertex(i).y) / (self.vertex(j).y - self.vertex(i).y) + self.vertex(i).x) { c =!c; } j = i; i += 1; } return c!= 0; } fn overlaps_rect(&self, rect: Rect) -> bool { self.overlaps(&rect) } fn overlaps_circ(&self, circ: Circ) -> bool { self.overlaps(&circ) } fn overlaps_poly(&self, poly: &Poly) -> bool { self.overlaps(poly) } fn overlaps<T: Shape>(&self, shape: &T) -> bool { if self.contains(shape.get_position())
for i in 0..(self.points.len() + 1) { let one = self.vertex(i % self.points.len()); let two = self.vertex((i + self.points.len() - 1) % self.points.len()); let face = Line::new(one, two); println!("{}:{}, {}:{}", one.x, one.y, two.x, two.y); if shape.contains(one) || shape.intersects(face) { return true; } } return false; } fn get_bounding_box(&self) -> Rect { let get_x = |vector: &Vector2| vector.x; let get_y = |vector: &Vector2| vector.y; let minimum = |a, b| { if b < a { b } else { a } }; let maximum = |a, b| { if b > a { b } else { a } }; let x = self.points[0].x; let y = self.points[0].y; let min_x = self.points.iter().map(&get_x).fold(x, &minimum); let min_y = self.points.iter().map(&get_y).fold(y, &minimum); let max_x = self.points.iter().map(&get_x).fold(x, &maximum); let max_y = self.points.iter().map(&get_y).fold(y, &maximum); Rect::new(min_x, min_y, max_x - min_x, max_y - min_y) } }
{ return true; }
conditional_block
build.rs
#![allow(unused_variables)] // extern crate bindgen; extern crate make_cmd; use make_cmd::make; use std::env; use std::path::Path; use std::process::Command; const LIBSIXEL_DIR: &str = "libsixel"; fn main()
let pixbuf = has_feature("pixbuf"); let png = has_feature("png"); let gd = has_feature("gd"); let python_interface = has_feature("python_interface"); let sixel_dir = Path::new(LIBSIXEL_DIR); { let mut cmd = Command::new("./configure"); cmd.current_dir(sixel_dir) .arg("--prefix") .arg(out_dir); // cmd.arg("-fPIC"); if curl { cmd.arg("--with-libcurl"); } if gd { cmd.arg("--with-gd"); } if pixbuf { cmd.arg("--with-gdk-pixbuf"); } if jpeg { cmd.arg("--with-jpeg"); } if png { cmd.arg("--with-png"); } if!python_interface { cmd.arg("--without-python"); } cmd.status().expect("Failed to execute./configure"); make() .arg("install") .current_dir(sixel_dir) .status().expect("Failed to execute make"); } // generate_bindings(out_dir); } // fn generate_bindings(out_dir: &Path) { // let bindings = bindgen::Builder::default() // .no_unstable_rust() // .header("wrapper.h") // .hide_type("max_align_t") // .generate() // .expect("Unable to generate bindings"); // // bindings // .write_to_file(out_dir.join("bindings.rs")) // .expect("Couldn't write bindings"); // } const FEATURE_PREFIX: &str = "CARGO_FEATURE_"; fn has_feature(feature: &'static str) -> bool { let feature = feature.to_owned().to_uppercase(); let mut name = FEATURE_PREFIX.to_owned(); name.push_str(&feature); env::var(name).is_ok() }
{ let testing_build = false; let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = Path::new(&out_dir); println!("cargo:rustc-link-lib=dylib=sixel"); // println!("cargo:rustc-link-lib=static=sixel"); println!("cargo:rustc-link-search=native={}", out_dir.join("lib").display()); if testing_build { return; } let curl = has_feature("curl"); let jpeg = has_feature("jpeg");
identifier_body
build.rs
#![allow(unused_variables)] // extern crate bindgen; extern crate make_cmd; use make_cmd::make; use std::env; use std::path::Path; use std::process::Command; const LIBSIXEL_DIR: &str = "libsixel"; fn
() { let testing_build = false; let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = Path::new(&out_dir); println!("cargo:rustc-link-lib=dylib=sixel"); // println!("cargo:rustc-link-lib=static=sixel"); println!("cargo:rustc-link-search=native={}", out_dir.join("lib").display()); if testing_build { return; } let curl = has_feature("curl"); let jpeg = has_feature("jpeg"); let pixbuf = has_feature("pixbuf"); let png = has_feature("png"); let gd = has_feature("gd"); let python_interface = has_feature("python_interface"); let sixel_dir = Path::new(LIBSIXEL_DIR); { let mut cmd = Command::new("./configure"); cmd.current_dir(sixel_dir) .arg("--prefix") .arg(out_dir); // cmd.arg("-fPIC"); if curl { cmd.arg("--with-libcurl"); } if gd { cmd.arg("--with-gd"); } if pixbuf { cmd.arg("--with-gdk-pixbuf"); } if jpeg { cmd.arg("--with-jpeg"); } if png { cmd.arg("--with-png"); } if!python_interface { cmd.arg("--without-python"); } cmd.status().expect("Failed to execute./configure"); make() .arg("install") .current_dir(sixel_dir) .status().expect("Failed to execute make"); } // generate_bindings(out_dir); } // fn generate_bindings(out_dir: &Path) { // let bindings = bindgen::Builder::default() // .no_unstable_rust() // .header("wrapper.h") // .hide_type("max_align_t") // .generate() // .expect("Unable to generate bindings"); // // bindings // .write_to_file(out_dir.join("bindings.rs")) // .expect("Couldn't write bindings"); // } const FEATURE_PREFIX: &str = "CARGO_FEATURE_"; fn has_feature(feature: &'static str) -> bool { let feature = feature.to_owned().to_uppercase(); let mut name = FEATURE_PREFIX.to_owned(); name.push_str(&feature); env::var(name).is_ok() }
main
identifier_name
build.rs
#![allow(unused_variables)] // extern crate bindgen; extern crate make_cmd; use make_cmd::make; use std::env; use std::path::Path; use std::process::Command; const LIBSIXEL_DIR: &str = "libsixel"; fn main() { let testing_build = false; let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = Path::new(&out_dir); println!("cargo:rustc-link-lib=dylib=sixel"); // println!("cargo:rustc-link-lib=static=sixel"); println!("cargo:rustc-link-search=native={}", out_dir.join("lib").display()); if testing_build { return; } let curl = has_feature("curl"); let jpeg = has_feature("jpeg"); let pixbuf = has_feature("pixbuf"); let png = has_feature("png"); let gd = has_feature("gd"); let python_interface = has_feature("python_interface"); let sixel_dir = Path::new(LIBSIXEL_DIR); { let mut cmd = Command::new("./configure"); cmd.current_dir(sixel_dir) .arg("--prefix") .arg(out_dir); // cmd.arg("-fPIC"); if curl
if gd { cmd.arg("--with-gd"); } if pixbuf { cmd.arg("--with-gdk-pixbuf"); } if jpeg { cmd.arg("--with-jpeg"); } if png { cmd.arg("--with-png"); } if!python_interface { cmd.arg("--without-python"); } cmd.status().expect("Failed to execute./configure"); make() .arg("install") .current_dir(sixel_dir) .status().expect("Failed to execute make"); } // generate_bindings(out_dir); } // fn generate_bindings(out_dir: &Path) { // let bindings = bindgen::Builder::default() // .no_unstable_rust() // .header("wrapper.h") // .hide_type("max_align_t") // .generate() // .expect("Unable to generate bindings"); // // bindings // .write_to_file(out_dir.join("bindings.rs")) // .expect("Couldn't write bindings"); // } const FEATURE_PREFIX: &str = "CARGO_FEATURE_"; fn has_feature(feature: &'static str) -> bool { let feature = feature.to_owned().to_uppercase(); let mut name = FEATURE_PREFIX.to_owned(); name.push_str(&feature); env::var(name).is_ok() }
{ cmd.arg("--with-libcurl"); }
conditional_block
build.rs
#![allow(unused_variables)] // extern crate bindgen; extern crate make_cmd; use make_cmd::make; use std::env; use std::path::Path; use std::process::Command; const LIBSIXEL_DIR: &str = "libsixel"; fn main() { let testing_build = false; let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = Path::new(&out_dir); println!("cargo:rustc-link-lib=dylib=sixel"); // println!("cargo:rustc-link-lib=static=sixel"); println!("cargo:rustc-link-search=native={}", out_dir.join("lib").display()); if testing_build { return; } let curl = has_feature("curl"); let jpeg = has_feature("jpeg"); let pixbuf = has_feature("pixbuf"); let png = has_feature("png"); let gd = has_feature("gd"); let python_interface = has_feature("python_interface"); let sixel_dir = Path::new(LIBSIXEL_DIR); { let mut cmd = Command::new("./configure"); cmd.current_dir(sixel_dir) .arg("--prefix") .arg(out_dir); // cmd.arg("-fPIC"); if curl { cmd.arg("--with-libcurl"); } if gd { cmd.arg("--with-gd"); } if pixbuf { cmd.arg("--with-gdk-pixbuf"); } if jpeg { cmd.arg("--with-jpeg"); } if png { cmd.arg("--with-png"); }
make() .arg("install") .current_dir(sixel_dir) .status().expect("Failed to execute make"); } // generate_bindings(out_dir); } // fn generate_bindings(out_dir: &Path) { // let bindings = bindgen::Builder::default() // .no_unstable_rust() // .header("wrapper.h") // .hide_type("max_align_t") // .generate() // .expect("Unable to generate bindings"); // // bindings // .write_to_file(out_dir.join("bindings.rs")) // .expect("Couldn't write bindings"); // } const FEATURE_PREFIX: &str = "CARGO_FEATURE_"; fn has_feature(feature: &'static str) -> bool { let feature = feature.to_owned().to_uppercase(); let mut name = FEATURE_PREFIX.to_owned(); name.push_str(&feature); env::var(name).is_ok() }
if !python_interface { cmd.arg("--without-python"); } cmd.status().expect("Failed to execute ./configure");
random_line_split