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 |
---|---|---|---|---|
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn example_program_2() {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World!\n";
end for;
assert (x = nTimes);"#;
let mut scanner = Scanner::new();
let mut tokens = VecDeque::new();
scanner.scan(source, &mut tokens);
let mut statements = VecDeque::new();
let mut expected: VecDeque<_> = vec![
Statement::Declaration(
"nTimes".to_string(),
Type::Int,
Some(Expression::Singleton(Operand::Int(0.into()))),
),
Statement::Print(Expression::Singleton(Operand::StringLiteral(
"How many times?".to_string(),
))), | Statement::Read("nTimes".to_string()),
Statement::Declaration("x".to_string(), Type::Int, None),
Statement::For(
"x".to_string(),
Expression::Singleton(Operand::Int(0.into())),
Expression::Binary(
Operand::Identifier("nTimes".to_string()),
BinaryOperator::Minus,
Operand::Int(1.into()),
),
vec![
Statement::Print(Expression::Singleton(Operand::Identifier("x".to_string()))),
Statement::Print(Expression::Singleton(Operand::StringLiteral(
" : Hello, World!\n".to_string(),
))),
],
),
Statement::Assert(Expression::Binary(
Operand::Identifier("x".to_string()),
BinaryOperator::Equals,
Operand::Identifier("nTimes".to_string()),
)),
].into_iter()
.collect();
parse(&mut tokens, &mut statements);
assert_eq!(statements, expected);
} | random_line_split |
|
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn example_program_2() | Statement::Print(Expression::Singleton(Operand::StringLiteral(
"How many times?".to_string(),
))),
Statement::Read("nTimes".to_string()),
Statement::Declaration("x".to_string(), Type::Int, None),
Statement::For(
"x".to_string(),
Expression::Singleton(Operand::Int(0.into())),
Expression::Binary(
Operand::Identifier("nTimes".to_string()),
BinaryOperator::Minus,
Operand::Int(1.into()),
),
vec![
Statement::Print(Expression::Singleton(Operand::Identifier("x".to_string()))),
Statement::Print(Expression::Singleton(Operand::StringLiteral(
" : Hello, World!\n".to_string(),
))),
],
),
Statement::Assert(Expression::Binary(
Operand::Identifier("x".to_string()),
BinaryOperator::Equals,
Operand::Identifier("nTimes".to_string()),
)),
].into_iter()
.collect();
parse(&mut tokens, &mut statements);
assert_eq!(statements, expected);
}
| {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World!\n";
end for;
assert (x = nTimes);"#;
let mut scanner = Scanner::new();
let mut tokens = VecDeque::new();
scanner.scan(source, &mut tokens);
let mut statements = VecDeque::new();
let mut expected: VecDeque<_> = vec![
Statement::Declaration(
"nTimes".to_string(),
Type::Int,
Some(Expression::Singleton(Operand::Int(0.into()))),
), | identifier_body |
test.rs | use std::collections::VecDeque;
use super::{parse, BinaryOperator, Expression, Operand, Statement, Type};
use scanner::Scanner;
#[test]
fn | () {
let source = r#" var nTimes : int := 0;
print "How many times?";
read nTimes;
var x : int;
for x in 0..nTimes-1 do
print x;
print " : Hello, World!\n";
end for;
assert (x = nTimes);"#;
let mut scanner = Scanner::new();
let mut tokens = VecDeque::new();
scanner.scan(source, &mut tokens);
let mut statements = VecDeque::new();
let mut expected: VecDeque<_> = vec![
Statement::Declaration(
"nTimes".to_string(),
Type::Int,
Some(Expression::Singleton(Operand::Int(0.into()))),
),
Statement::Print(Expression::Singleton(Operand::StringLiteral(
"How many times?".to_string(),
))),
Statement::Read("nTimes".to_string()),
Statement::Declaration("x".to_string(), Type::Int, None),
Statement::For(
"x".to_string(),
Expression::Singleton(Operand::Int(0.into())),
Expression::Binary(
Operand::Identifier("nTimes".to_string()),
BinaryOperator::Minus,
Operand::Int(1.into()),
),
vec![
Statement::Print(Expression::Singleton(Operand::Identifier("x".to_string()))),
Statement::Print(Expression::Singleton(Operand::StringLiteral(
" : Hello, World!\n".to_string(),
))),
],
),
Statement::Assert(Expression::Binary(
Operand::Identifier("x".to_string()),
BinaryOperator::Equals,
Operand::Identifier("nTimes".to_string()),
)),
].into_iter()
.collect();
parse(&mut tokens, &mut statements);
assert_eq!(statements, expected);
}
| example_program_2 | identifier_name |
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", empty_msg);
}
let mut table = Table::new();
print_header(&mut table, headers);
for row in rows {
print_row(&mut table, row, headers);
}
table.printstd();
}
pub fn print_table(row: &serde_json::Value, headers: &[(&str, &str)]) {
let mut table = Table::new();
print_header(&mut table, headers);
print_row(&mut table, row, headers);
table.printstd();
}
pub fn print_header(table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(tittles));
}
pub fn print_row(table: &mut Table, row: &serde_json::Value, headers: &[(&str, &str)]) {
let columns = headers.iter().clone()
.map(|&(ref key, _)| {
let mut value = "-".to_string();
if row[key].is_string() {
value = row[key].as_str().unwrap().to_string()
}
if row[key].is_i64() {
value = row[key].as_i64().unwrap().to_string();
}
if row[key].is_boolean() {
value = row[key].as_bool().unwrap().to_string()
}
if row[key].is_array() {
value = row[key].as_array().unwrap()
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(",")
}
if row[key].is_object() |
Cell::new(&value)
})
.collect::<Vec<Cell>>();
table.add_row(Row::new(columns));
} | {
value = row[key].as_object().unwrap()
.iter()
.map(|(key, value)| format!("{}:{}", key, value))
.collect::<Vec<String>>()
.join(",");
value = format!("{{{}}}", value)
} | conditional_block |
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", empty_msg);
}
let mut table = Table::new();
print_header(&mut table, headers);
for row in rows {
print_row(&mut table, row, headers);
}
table.printstd();
}
pub fn print_table(row: &serde_json::Value, headers: &[(&str, &str)]) {
let mut table = Table::new();
print_header(&mut table, headers);
print_row(&mut table, row, headers);
table.printstd();
}
pub fn | (table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(tittles));
}
pub fn print_row(table: &mut Table, row: &serde_json::Value, headers: &[(&str, &str)]) {
let columns = headers.iter().clone()
.map(|&(ref key, _)| {
let mut value = "-".to_string();
if row[key].is_string() {
value = row[key].as_str().unwrap().to_string()
}
if row[key].is_i64() {
value = row[key].as_i64().unwrap().to_string();
}
if row[key].is_boolean() {
value = row[key].as_bool().unwrap().to_string()
}
if row[key].is_array() {
value = row[key].as_array().unwrap()
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(",")
}
if row[key].is_object() {
value = row[key].as_object().unwrap()
.iter()
.map(|(key, value)| format!("{}:{}", key, value))
.collect::<Vec<String>>()
.join(",");
value = format!("{{{}}}", value)
}
Cell::new(&value)
})
.collect::<Vec<Cell>>();
table.add_row(Row::new(columns));
} | print_header | identifier_name |
table.rs | use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", empty_msg);
}
let mut table = Table::new();
print_header(&mut table, headers);
for row in rows {
print_row(&mut table, row, headers);
}
table.printstd();
}
pub fn print_table(row: &serde_json::Value, headers: &[(&str, &str)]) {
let mut table = Table::new();
print_header(&mut table, headers);
print_row(&mut table, row, headers);
table.printstd();
}
pub fn print_header(table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(tittles));
}
pub fn print_row(table: &mut Table, row: &serde_json::Value, headers: &[(&str, &str)]) {
let columns = headers.iter().clone()
.map(|&(ref key, _)| {
let mut value = "-".to_string();
if row[key].is_string() {
value = row[key].as_str().unwrap().to_string()
}
if row[key].is_i64() {
value = row[key].as_i64().unwrap().to_string();
}
if row[key].is_boolean() {
value = row[key].as_bool().unwrap().to_string()
}
if row[key].is_array() {
value = row[key].as_array().unwrap()
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(",")
}
if row[key].is_object() {
value = row[key].as_object().unwrap()
.iter()
.map(|(key, value)| format!("{}:{}", key, value))
.collect::<Vec<String>>()
.join(",");
value = format!("{{{}}}", value)
}
Cell::new(&value)
})
.collect::<Vec<Cell>>();
table.add_row(Row::new(columns));
} | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table; | random_line_split |
|
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", empty_msg);
}
let mut table = Table::new();
print_header(&mut table, headers);
for row in rows {
print_row(&mut table, row, headers);
}
table.printstd();
}
pub fn print_table(row: &serde_json::Value, headers: &[(&str, &str)]) |
pub fn print_header(table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(tittles));
}
pub fn print_row(table: &mut Table, row: &serde_json::Value, headers: &[(&str, &str)]) {
let columns = headers.iter().clone()
.map(|&(ref key, _)| {
let mut value = "-".to_string();
if row[key].is_string() {
value = row[key].as_str().unwrap().to_string()
}
if row[key].is_i64() {
value = row[key].as_i64().unwrap().to_string();
}
if row[key].is_boolean() {
value = row[key].as_bool().unwrap().to_string()
}
if row[key].is_array() {
value = row[key].as_array().unwrap()
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(",")
}
if row[key].is_object() {
value = row[key].as_object().unwrap()
.iter()
.map(|(key, value)| format!("{}:{}", key, value))
.collect::<Vec<String>>()
.join(",");
value = format!("{{{}}}", value)
}
Cell::new(&value)
})
.collect::<Vec<Cell>>();
table.add_row(Row::new(columns));
} | {
let mut table = Table::new();
print_header(&mut table, headers);
print_row(&mut table, row, headers);
table.printstd();
} | identifier_body |
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true { |
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() { test_vec(); } | true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
} | random_line_split |
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() | { test_vec(); } | identifier_body |
|
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
fn | <T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() { test_vec(); }
| test_generic | identifier_name |
tuple.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.
//! Operations on tuples
//!
//! To access the _N_-th element of a tuple one can use `N` itself
//! as a field of the tuple.
//!
//! Indexing starts from zero, so `0` returns first value, `1`
//! returns second value, and so on. In general, a tuple with _S_
//! elements provides aforementioned fields from `0` to `S-1`.
//!
//! If every type inside a tuple implements one of the following
//! traits, then a tuple itself also implements it.
//!
//! * `Clone`
//! * `PartialEq`
//! * `Eq`
//! * `PartialOrd`
//! * `Ord`
//! * `Default`
//!
//! # Examples
//!
//! Accessing elements of a tuple at specified indices:
//!
//! ```
//! let x = ("colorless", "green", "ideas", "sleep", "furiously");
//! assert_eq!(x.3, "sleep");
//!
//! let v = (3, 3);
//! let u = (1, -5);
//! assert_eq!(v.0 * u.0 + v.1 * u.1, -12);
//! ```
//!
//! Using traits implemented for tuples:
//!
//! ```
//! let a = (1, 2);
//! let b = (3, 4);
//! assert!(a!= b);
//! | //! assert!(b == c);
//!
//! let d : (u32, f32) = Default::default();
//! assert_eq!(d, (0, 0.0f32));
//! ```
#![doc(primitive = "tuple")]
#![stable(feature = "rust1", since = "1.0.0")] | //! let c = b.clone(); | random_line_split |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rustc_serialize::json;
use na::{Vector3, Point3};
macro_rules! try_with_yolo{
($expr:expr) =>
{
match $expr
{
_ => {}
}
}
}
struct Robot
{
legs: Vec<Leg>
}
impl Robot
{
pub fn new(window: &mut Window) -> Robot
{
let mut legs = vec!();
let leg_positions = vec!(
na::Vector3::new(10., 0., -6.) * constants::UNIT_SCALE, //Left front
na::Vector3::new(10., 0., 6.) * constants::UNIT_SCALE, //Right front
na::Vector3::new(0., 0., -8.) * constants::UNIT_SCALE, //Left mid
na::Vector3::new(0., 0., 10.) * constants::UNIT_SCALE, //Right mid
na::Vector3::new(-10., 0., -6.) * constants::UNIT_SCALE, //Left back
na::Vector3::new(-10., 0., 6.) * constants::UNIT_SCALE, //Right back
);
let leg_angles = vec!(PI/4., -PI/4., PI/2., -PI/2., 3. * PI/4., -3. * PI/4.);
for i in 0..6
{
legs.push(Leg::new(window, leg_angles[i], leg_positions[i]));
}
Robot {
legs: legs
}
}
pub fn update(&mut self, delta_time: f32)
{
for leg in &mut self.legs
{
leg.update(delta_time);
}
}
pub fn set_targets(&mut self, targets: Vec<LegTarget>)
{
assert_eq!(targets.len(), self.legs.len());
for i in 0..self.legs.len()
{
self.legs[i].set_target_angles(&targets[i].angles);
self.legs[i].set_target_point(&targets[i].point);
}
}
pub fn write_angles_done(&self)
{
{
let mut file = File::create("/tmp/hexsim/servo_states").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.is_still_moving()
{
result += match status
{
true => "1",
false => "0"
}
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing angles
{
let mut file = File::create("/tmp/hexsim/servo_angles").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing targets
{
let mut file = File::create("/tmp/hexsim/servo_targets").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_target_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
}
}
#[derive(RustcDecodable)]
struct LegTarget
{
point: na::Vector3<f32>,
angles: Vec<f32>
}
impl LegTarget
{
pub fn convert_to_simulator_coordinates(&self) -> LegTarget
{
const scaling: f32 = 10. * constants::UNIT_SCALE;
let mut new_target = LegTarget{
angles: self.angles.clone(),
point: na::zero()
};
new_target.point.x = self.point.x * scaling;
new_target.point.y = self.point.z * scaling;
new_target.point.z = -self.point.y * scaling;
new_target
}
}
//Panics if file is wrong, maybe change?
fn read_target_angles() -> Vec<LegTarget>
| };
//Reading the file into a string
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
//let json_data = json::Json::from_str(&s).unwrap();
result = match json::decode(&s)
{
Ok(val) => {
is_done = true;
val
},
Err(e) => {
println!("Failed to parse json, {}", e);
continue;
}
};
}
result = result.into_iter().map(|x|{x.convert_to_simulator_coordinates()}).collect();
result
}
fn draw_grid(window: &mut Window)
{
for pos in -1000..1000
{
let pos = pos as f32;
if pos!= 0.
{
window.draw_line(&Point3::new(pos, 0., -1000.), &Point3::new(pos, 0., 1000.), &Point3::new(0.5, 0.5, 0.5));
window.draw_line(&Point3::new(-1000., 0., pos), &Point3::new(1000., 0., pos), &Point3::new(0.5, 0.5, 0.5));
}
}
}
fn main() {
let mut window = Window::new("Kiss3d: cube");
window.set_light(Light::StickToCamera);
let mut robot = Robot::new(&mut window);
let mut old_time = time::precise_time_s() as f32;
while window.render()
{
let new_time = time::precise_time_s() as f32;
let delta_time = (new_time - old_time) * constants::TIME_MODIFIER;
old_time = new_time;
let leg_targets = read_target_angles();
robot.set_targets(leg_targets);
robot.update(delta_time);
robot.write_angles_done();
draw_grid(&mut window);
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(1000., 0., 0.), &Point3::new(1., 0., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 1000., 0.), &Point3::new(0., 1., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 0., 1000.), &Point3::new(0., 0., 1.));
}
}
| {
let file_dir = String::from("/tmp/hexsim");
let filepath = file_dir.clone() + "/leg_input";
try_with_yolo!(std::fs::create_dir(&file_dir));
//Opening the file
//let mut file = None;
let mut is_done = false;
let mut result: Vec<LegTarget> = vec!();
while !is_done
{
let mut file = match File::open(&filepath)
{
Ok(val) => val,
Err(e) => {
println!("Failed to open target file {}, {:?}", filepath, e);
continue;
} | identifier_body |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rustc_serialize::json;
use na::{Vector3, Point3};
macro_rules! try_with_yolo{
($expr:expr) =>
{
match $expr
{
_ => {}
}
}
}
struct Robot
{
legs: Vec<Leg>
}
impl Robot
{
pub fn new(window: &mut Window) -> Robot
{
let mut legs = vec!();
let leg_positions = vec!(
na::Vector3::new(10., 0., -6.) * constants::UNIT_SCALE, //Left front
na::Vector3::new(10., 0., 6.) * constants::UNIT_SCALE, //Right front
na::Vector3::new(0., 0., -8.) * constants::UNIT_SCALE, //Left mid
na::Vector3::new(0., 0., 10.) * constants::UNIT_SCALE, //Right mid
na::Vector3::new(-10., 0., -6.) * constants::UNIT_SCALE, //Left back
na::Vector3::new(-10., 0., 6.) * constants::UNIT_SCALE, //Right back
);
let leg_angles = vec!(PI/4., -PI/4., PI/2., -PI/2., 3. * PI/4., -3. * PI/4.);
for i in 0..6
{
legs.push(Leg::new(window, leg_angles[i], leg_positions[i]));
}
Robot {
legs: legs
}
}
pub fn update(&mut self, delta_time: f32)
{
for leg in &mut self.legs
{
leg.update(delta_time);
}
}
pub fn set_targets(&mut self, targets: Vec<LegTarget>)
{
assert_eq!(targets.len(), self.legs.len());
for i in 0..self.legs.len()
{
self.legs[i].set_target_angles(&targets[i].angles);
self.legs[i].set_target_point(&targets[i].point);
}
}
pub fn write_angles_done(&self)
{
{
let mut file = File::create("/tmp/hexsim/servo_states").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.is_still_moving()
{
result += match status
{
true => "1",
false => "0"
}
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing angles
{
let mut file = File::create("/tmp/hexsim/servo_angles").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing targets
{
let mut file = File::create("/tmp/hexsim/servo_targets").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_target_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
}
}
#[derive(RustcDecodable)]
struct LegTarget
{
point: na::Vector3<f32>,
angles: Vec<f32>
}
impl LegTarget
{
pub fn convert_to_simulator_coordinates(&self) -> LegTarget
{
const scaling: f32 = 10. * constants::UNIT_SCALE;
let mut new_target = LegTarget{
angles: self.angles.clone(),
point: na::zero()
};
new_target.point.x = self.point.x * scaling;
new_target.point.y = self.point.z * scaling;
new_target.point.z = -self.point.y * scaling;
new_target
}
}
//Panics if file is wrong, maybe change?
fn read_target_angles() -> Vec<LegTarget>
{
let file_dir = String::from("/tmp/hexsim");
let filepath = file_dir.clone() + "/leg_input";
try_with_yolo!(std::fs::create_dir(&file_dir));
//Opening the file
//let mut file = None;
let mut is_done = false;
let mut result: Vec<LegTarget> = vec!();
while!is_done
{
let mut file = match File::open(&filepath)
{
Ok(val) => val,
Err(e) => {
println!("Failed to open target file {}, {:?}", filepath, e);
continue;
}
};
//Reading the file into a string
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
//let json_data = json::Json::from_str(&s).unwrap();
result = match json::decode(&s)
{
Ok(val) => {
is_done = true;
val
},
Err(e) => {
println!("Failed to parse json, {}", e);
continue;
}
};
}
result = result.into_iter().map(|x|{x.convert_to_simulator_coordinates()}).collect();
result
}
fn draw_grid(window: &mut Window)
{
for pos in -1000..1000
{
let pos = pos as f32;
if pos!= 0.
{
window.draw_line(&Point3::new(pos, 0., -1000.), &Point3::new(pos, 0., 1000.), &Point3::new(0.5, 0.5, 0.5));
window.draw_line(&Point3::new(-1000., 0., pos), &Point3::new(1000., 0., pos), &Point3::new(0.5, 0.5, 0.5));
}
} |
window.set_light(Light::StickToCamera);
let mut robot = Robot::new(&mut window);
let mut old_time = time::precise_time_s() as f32;
while window.render()
{
let new_time = time::precise_time_s() as f32;
let delta_time = (new_time - old_time) * constants::TIME_MODIFIER;
old_time = new_time;
let leg_targets = read_target_angles();
robot.set_targets(leg_targets);
robot.update(delta_time);
robot.write_angles_done();
draw_grid(&mut window);
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(1000., 0., 0.), &Point3::new(1., 0., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 1000., 0.), &Point3::new(0., 1., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 0., 1000.), &Point3::new(0., 0., 1.));
}
} | }
fn main() {
let mut window = Window::new("Kiss3d: cube"); | random_line_split |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rustc_serialize::json;
use na::{Vector3, Point3};
macro_rules! try_with_yolo{
($expr:expr) =>
{
match $expr
{
_ => {}
}
}
}
struct Robot
{
legs: Vec<Leg>
}
impl Robot
{
pub fn new(window: &mut Window) -> Robot
{
let mut legs = vec!();
let leg_positions = vec!(
na::Vector3::new(10., 0., -6.) * constants::UNIT_SCALE, //Left front
na::Vector3::new(10., 0., 6.) * constants::UNIT_SCALE, //Right front
na::Vector3::new(0., 0., -8.) * constants::UNIT_SCALE, //Left mid
na::Vector3::new(0., 0., 10.) * constants::UNIT_SCALE, //Right mid
na::Vector3::new(-10., 0., -6.) * constants::UNIT_SCALE, //Left back
na::Vector3::new(-10., 0., 6.) * constants::UNIT_SCALE, //Right back
);
let leg_angles = vec!(PI/4., -PI/4., PI/2., -PI/2., 3. * PI/4., -3. * PI/4.);
for i in 0..6
{
legs.push(Leg::new(window, leg_angles[i], leg_positions[i]));
}
Robot {
legs: legs
}
}
pub fn update(&mut self, delta_time: f32)
{
for leg in &mut self.legs
{
leg.update(delta_time);
}
}
pub fn set_targets(&mut self, targets: Vec<LegTarget>)
{
assert_eq!(targets.len(), self.legs.len());
for i in 0..self.legs.len()
{
self.legs[i].set_target_angles(&targets[i].angles);
self.legs[i].set_target_point(&targets[i].point);
}
}
pub fn | (&self)
{
{
let mut file = File::create("/tmp/hexsim/servo_states").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.is_still_moving()
{
result += match status
{
true => "1",
false => "0"
}
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing angles
{
let mut file = File::create("/tmp/hexsim/servo_angles").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
//Writing targets
{
let mut file = File::create("/tmp/hexsim/servo_targets").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.get_target_angles()
{
file.write(&format!("{}\n", status).into_bytes());
}
}
file.write_all(result.into_bytes().as_slice());
}
}
}
#[derive(RustcDecodable)]
struct LegTarget
{
point: na::Vector3<f32>,
angles: Vec<f32>
}
impl LegTarget
{
pub fn convert_to_simulator_coordinates(&self) -> LegTarget
{
const scaling: f32 = 10. * constants::UNIT_SCALE;
let mut new_target = LegTarget{
angles: self.angles.clone(),
point: na::zero()
};
new_target.point.x = self.point.x * scaling;
new_target.point.y = self.point.z * scaling;
new_target.point.z = -self.point.y * scaling;
new_target
}
}
//Panics if file is wrong, maybe change?
fn read_target_angles() -> Vec<LegTarget>
{
let file_dir = String::from("/tmp/hexsim");
let filepath = file_dir.clone() + "/leg_input";
try_with_yolo!(std::fs::create_dir(&file_dir));
//Opening the file
//let mut file = None;
let mut is_done = false;
let mut result: Vec<LegTarget> = vec!();
while!is_done
{
let mut file = match File::open(&filepath)
{
Ok(val) => val,
Err(e) => {
println!("Failed to open target file {}, {:?}", filepath, e);
continue;
}
};
//Reading the file into a string
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
//let json_data = json::Json::from_str(&s).unwrap();
result = match json::decode(&s)
{
Ok(val) => {
is_done = true;
val
},
Err(e) => {
println!("Failed to parse json, {}", e);
continue;
}
};
}
result = result.into_iter().map(|x|{x.convert_to_simulator_coordinates()}).collect();
result
}
fn draw_grid(window: &mut Window)
{
for pos in -1000..1000
{
let pos = pos as f32;
if pos!= 0.
{
window.draw_line(&Point3::new(pos, 0., -1000.), &Point3::new(pos, 0., 1000.), &Point3::new(0.5, 0.5, 0.5));
window.draw_line(&Point3::new(-1000., 0., pos), &Point3::new(1000., 0., pos), &Point3::new(0.5, 0.5, 0.5));
}
}
}
fn main() {
let mut window = Window::new("Kiss3d: cube");
window.set_light(Light::StickToCamera);
let mut robot = Robot::new(&mut window);
let mut old_time = time::precise_time_s() as f32;
while window.render()
{
let new_time = time::precise_time_s() as f32;
let delta_time = (new_time - old_time) * constants::TIME_MODIFIER;
old_time = new_time;
let leg_targets = read_target_angles();
robot.set_targets(leg_targets);
robot.update(delta_time);
robot.write_angles_done();
draw_grid(&mut window);
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(1000., 0., 0.), &Point3::new(1., 0., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 1000., 0.), &Point3::new(0., 1., 0.));
window.draw_line(&Point3::new(0., 0., 0.), &Point3::new(0., 0., 1000.), &Point3::new(0., 0., 1.));
}
}
| write_angles_done | identifier_name |
rtctrackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::RTCTrackEventBinding::{self, RTCTrackEventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope;
use crate::dom::mediastreamtrack::MediaStreamTrack;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct RTCTrackEvent {
event: Event,
track: Dom<MediaStreamTrack>,
}
impl RTCTrackEvent {
#[allow(unrooted_must_root)]
fn new_inherited(track: &MediaStreamTrack) -> RTCTrackEvent {
RTCTrackEvent {
event: Event::new_inherited(),
track: Dom::from_ref(track),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
track: &MediaStreamTrack,
) -> DomRoot<RTCTrackEvent> {
let trackevent = reflect_dom_object(
Box::new(RTCTrackEvent::new_inherited(&track)),
global,
RTCTrackEventBinding::Wrap,
);
{
let event = trackevent.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
trackevent
}
pub fn Constructor(
window: &Window,
type_: DOMString,
init: &RTCTrackEventBinding::RTCTrackEventInit,
) -> Fallible<DomRoot<RTCTrackEvent>> |
}
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track
fn Track(&self) -> DomRoot<MediaStreamTrack> {
DomRoot::from_ref(&*self.track)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
Ok(RTCTrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
} | identifier_body |
rtctrackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::RTCTrackEventBinding::{self, RTCTrackEventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope;
use crate::dom::mediastreamtrack::MediaStreamTrack;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct RTCTrackEvent {
event: Event,
track: Dom<MediaStreamTrack>,
}
impl RTCTrackEvent {
#[allow(unrooted_must_root)]
fn new_inherited(track: &MediaStreamTrack) -> RTCTrackEvent {
RTCTrackEvent { | pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
track: &MediaStreamTrack,
) -> DomRoot<RTCTrackEvent> {
let trackevent = reflect_dom_object(
Box::new(RTCTrackEvent::new_inherited(&track)),
global,
RTCTrackEventBinding::Wrap,
);
{
let event = trackevent.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
trackevent
}
pub fn Constructor(
window: &Window,
type_: DOMString,
init: &RTCTrackEventBinding::RTCTrackEventInit,
) -> Fallible<DomRoot<RTCTrackEvent>> {
Ok(RTCTrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
}
}
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track
fn Track(&self) -> DomRoot<MediaStreamTrack> {
DomRoot::from_ref(&*self.track)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
} | event: Event::new_inherited(),
track: Dom::from_ref(track),
}
}
| random_line_split |
rtctrackevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::RTCTrackEventBinding::{self, RTCTrackEventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope;
use crate::dom::mediastreamtrack::MediaStreamTrack;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct RTCTrackEvent {
event: Event,
track: Dom<MediaStreamTrack>,
}
impl RTCTrackEvent {
#[allow(unrooted_must_root)]
fn new_inherited(track: &MediaStreamTrack) -> RTCTrackEvent {
RTCTrackEvent {
event: Event::new_inherited(),
track: Dom::from_ref(track),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
track: &MediaStreamTrack,
) -> DomRoot<RTCTrackEvent> {
let trackevent = reflect_dom_object(
Box::new(RTCTrackEvent::new_inherited(&track)),
global,
RTCTrackEventBinding::Wrap,
);
{
let event = trackevent.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
trackevent
}
pub fn Constructor(
window: &Window,
type_: DOMString,
init: &RTCTrackEventBinding::RTCTrackEventInit,
) -> Fallible<DomRoot<RTCTrackEvent>> {
Ok(RTCTrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
}
}
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track
fn Track(&self) -> DomRoot<MediaStreamTrack> {
DomRoot::from_ref(&*self.track)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn | (&self) -> bool {
self.event.IsTrusted()
}
}
| IsTrusted | identifier_name |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::fmt;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits;
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn new() -> (IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
// We pass this info to various threads, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeline_id: PipelineId,
pub parent_info: Option<(PipelineId, SubpageId)>,
}
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<ViewportPx, f32>,
/// The "viewing area" in page px. See `PagePx` documentation for details.
pub visible_viewport: TypedSize2D<PagePx, f32>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
Refresh(PipelineId, IpcSender<LoadStatus>),
ScriptCommand(PipelineId, WebDriverScriptCommand),
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub struct ImageMetadata {
pub width: u32,
pub height: u32,
}
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct Image {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
#[ignore_heap_size_of = "Defined in webrender_traits"]
pub id: Option<webrender_traits::ImageKey>,
}
/// Similar to net::resource_thread::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
}
impl LoadData {
pub fn new(url: Url) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum NavigationDirection {
Forward,
Back,
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
next_index: PipelineIndex,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
} |
pub trait ConvertPipelineIdToWebRender {
fn to_webrender(&self) -> webrender_traits::PipelineId;
}
pub trait ConvertPipelineIdFromWebRender {
fn from_webrender(&self) -> PipelineId;
}
impl ConvertPipelineIdToWebRender for PipelineId {
fn to_webrender(&self) -> webrender_traits::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_traits::PipelineId(namespace_id, index)
}
}
impl ConvertPipelineIdFromWebRender for webrender_traits::PipelineId {
fn from_webrender(&self) -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(self.0),
index: PipelineIndex(self.1),
}
}
} | }
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32); | random_line_split |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::fmt;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits;
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn | () -> (IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
// We pass this info to various threads, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeline_id: PipelineId,
pub parent_info: Option<(PipelineId, SubpageId)>,
}
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<ViewportPx, f32>,
/// The "viewing area" in page px. See `PagePx` documentation for details.
pub visible_viewport: TypedSize2D<PagePx, f32>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
Refresh(PipelineId, IpcSender<LoadStatus>),
ScriptCommand(PipelineId, WebDriverScriptCommand),
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub struct ImageMetadata {
pub width: u32,
pub height: u32,
}
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct Image {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
#[ignore_heap_size_of = "Defined in webrender_traits"]
pub id: Option<webrender_traits::ImageKey>,
}
/// Similar to net::resource_thread::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
}
impl LoadData {
pub fn new(url: Url) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum NavigationDirection {
Forward,
Back,
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
next_index: PipelineIndex,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32);
pub trait ConvertPipelineIdToWebRender {
fn to_webrender(&self) -> webrender_traits::PipelineId;
}
pub trait ConvertPipelineIdFromWebRender {
fn from_webrender(&self) -> PipelineId;
}
impl ConvertPipelineIdToWebRender for PipelineId {
fn to_webrender(&self) -> webrender_traits::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_traits::PipelineId(namespace_id, index)
}
}
impl ConvertPipelineIdFromWebRender for webrender_traits::PipelineId {
fn from_webrender(&self) -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(self.0),
index: PipelineIndex(self.1),
}
}
}
| new | identifier_name |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len()!= 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else | let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b = args[2];
let path_b = Path::new(fname_b.clone());
let msg_file_b = File::open(&path_b);
match(msg_file_a, msg_file_b)
{
(Some(mut msg_a), Some(mut msg_b)) =>
{
let msg_bytes_a: ~[u8] = msg_a.read_to_end();
let msg_bytes_b: ~[u8] = msg_b.read_to_end();
let join_file = File::create(&Path::new("join.txt"));
match (join_file)
{
Some(join) =>
{
joiner(join, msg_bytes_a, msg_bytes_b);
},
None => fail!("Error opening output files!"),
}
},
(_, _) => fail!("Error opening message file: {:s}", fname_a)
}
}
}
fn xor(a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8])
{
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | { | random_line_split |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len()!= 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b = args[2];
let path_b = Path::new(fname_b.clone());
let msg_file_b = File::open(&path_b);
match(msg_file_a, msg_file_b)
{
(Some(mut msg_a), Some(mut msg_b)) =>
{
let msg_bytes_a: ~[u8] = msg_a.read_to_end();
let msg_bytes_b: ~[u8] = msg_b.read_to_end();
let join_file = File::create(&Path::new("join.txt"));
match (join_file)
{
Some(join) =>
{
joiner(join, msg_bytes_a, msg_bytes_b);
},
None => fail!("Error opening output files!"),
}
},
(_, _) => fail!("Error opening message file: {:s}", fname_a)
}
}
}
fn | (a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8])
{
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | xor | identifier_name |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len()!= 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b = args[2];
let path_b = Path::new(fname_b.clone());
let msg_file_b = File::open(&path_b);
match(msg_file_a, msg_file_b)
{
(Some(mut msg_a), Some(mut msg_b)) =>
{
let msg_bytes_a: ~[u8] = msg_a.read_to_end();
let msg_bytes_b: ~[u8] = msg_b.read_to_end();
let join_file = File::create(&Path::new("join.txt"));
match (join_file)
{
Some(join) =>
| ,
None => fail!("Error opening output files!"),
}
},
(_, _) => fail!("Error opening message file: {:s}", fname_a)
}
}
}
fn xor(a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8])
{
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | {
joiner(join, msg_bytes_a, msg_bytes_b);
} | conditional_block |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len()!= 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b = args[2];
let path_b = Path::new(fname_b.clone());
let msg_file_b = File::open(&path_b);
match(msg_file_a, msg_file_b)
{
(Some(mut msg_a), Some(mut msg_b)) =>
{
let msg_bytes_a: ~[u8] = msg_a.read_to_end();
let msg_bytes_b: ~[u8] = msg_b.read_to_end();
let join_file = File::create(&Path::new("join.txt"));
match (join_file)
{
Some(join) =>
{
joiner(join, msg_bytes_a, msg_bytes_b);
},
None => fail!("Error opening output files!"),
}
},
(_, _) => fail!("Error opening message file: {:s}", fname_a)
}
}
}
fn xor(a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8])
| {
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | identifier_body |
|
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::channel::Channel;
use crate::error::Result;
use crate::task::Executor;
use crate::task::Kicker;
use futures_executor::block_on;
/// A generic client for making RPC calls.
#[derive(Clone)]
pub struct Client {
channel: Channel,
// Used to kick its completion queue.
kicker: Kicker,
}
impl Client {
/// Initialize a new [`Client`].
pub fn new(channel: Channel) -> Client {
let kicker = channel.create_kicker().unwrap();
Client { channel, kicker }
}
/// Create a synchronized unary RPC call.
///
/// It uses futures_executor::block_on to wait for the futures. It's recommended to use
/// the asynchronous version.
pub fn unary_call<Req, Resp: Unpin>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<Resp> {
block_on(self.unary_call_async(method, req, opt)?)
}
/// Create an asynchronized unary RPC call.
pub fn unary_call_async<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientUnaryReceiver<Resp>> {
Call::unary_async(&self.channel, method, req, opt)
}
/// Create an asynchronized client streaming call.
///
/// Client can send a stream of requests and server responds with a single response.
pub fn client_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientCStreamSender<Req>, ClientCStreamReceiver<Resp>)> {
Call::client_streaming(&self.channel, method, opt)
}
/// Create an asynchronized server streaming call.
///
/// Client sends on request and server responds with a stream of responses.
pub fn server_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientSStreamReceiver<Resp>> {
Call::server_streaming(&self.channel, method, req, opt)
}
/// Create an asynchronized duplex streaming call.
///
/// Client sends a stream of requests and server responds with a stream of responses.
/// The response stream is completely independent and both side can be sending messages
/// at the same time.
pub fn duplex_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientDuplexSender<Req>, ClientDuplexReceiver<Resp>)> |
/// Spawn the future into current gRPC poll thread.
///
/// This can reduce a lot of context switching, but please make
/// sure there is no heavy work in the future.
pub fn spawn<F>(&self, f: F)
where
F: Future<Output = ()> + Send +'static,
{
let kicker = self.kicker.clone();
Executor::new(self.channel.cq()).spawn(f, kicker)
}
}
| {
Call::duplex_streaming(&self.channel, method, opt)
} | identifier_body |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::channel::Channel;
use crate::error::Result;
use crate::task::Executor;
use crate::task::Kicker;
use futures_executor::block_on;
/// A generic client for making RPC calls.
#[derive(Clone)]
pub struct Client {
channel: Channel,
// Used to kick its completion queue.
kicker: Kicker,
}
impl Client {
/// Initialize a new [`Client`].
pub fn new(channel: Channel) -> Client {
let kicker = channel.create_kicker().unwrap();
Client { channel, kicker }
}
/// Create a synchronized unary RPC call.
///
/// It uses futures_executor::block_on to wait for the futures. It's recommended to use
/// the asynchronous version.
pub fn unary_call<Req, Resp: Unpin>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<Resp> {
block_on(self.unary_call_async(method, req, opt)?)
}
/// Create an asynchronized unary RPC call.
pub fn unary_call_async<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientUnaryReceiver<Resp>> {
Call::unary_async(&self.channel, method, req, opt)
}
| /// Create an asynchronized client streaming call.
///
/// Client can send a stream of requests and server responds with a single response.
pub fn client_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientCStreamSender<Req>, ClientCStreamReceiver<Resp>)> {
Call::client_streaming(&self.channel, method, opt)
}
/// Create an asynchronized server streaming call.
///
/// Client sends on request and server responds with a stream of responses.
pub fn server_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientSStreamReceiver<Resp>> {
Call::server_streaming(&self.channel, method, req, opt)
}
/// Create an asynchronized duplex streaming call.
///
/// Client sends a stream of requests and server responds with a stream of responses.
/// The response stream is completely independent and both side can be sending messages
/// at the same time.
pub fn duplex_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientDuplexSender<Req>, ClientDuplexReceiver<Resp>)> {
Call::duplex_streaming(&self.channel, method, opt)
}
/// Spawn the future into current gRPC poll thread.
///
/// This can reduce a lot of context switching, but please make
/// sure there is no heavy work in the future.
pub fn spawn<F>(&self, f: F)
where
F: Future<Output = ()> + Send +'static,
{
let kicker = self.kicker.clone();
Executor::new(self.channel.cq()).spawn(f, kicker)
}
} | random_line_split |
|
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::future::Future;
use crate::call::client::{
CallOption, ClientCStreamReceiver, ClientCStreamSender, ClientDuplexReceiver,
ClientDuplexSender, ClientSStreamReceiver, ClientUnaryReceiver,
};
use crate::call::{Call, Method};
use crate::channel::Channel;
use crate::error::Result;
use crate::task::Executor;
use crate::task::Kicker;
use futures_executor::block_on;
/// A generic client for making RPC calls.
#[derive(Clone)]
pub struct | {
channel: Channel,
// Used to kick its completion queue.
kicker: Kicker,
}
impl Client {
/// Initialize a new [`Client`].
pub fn new(channel: Channel) -> Client {
let kicker = channel.create_kicker().unwrap();
Client { channel, kicker }
}
/// Create a synchronized unary RPC call.
///
/// It uses futures_executor::block_on to wait for the futures. It's recommended to use
/// the asynchronous version.
pub fn unary_call<Req, Resp: Unpin>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<Resp> {
block_on(self.unary_call_async(method, req, opt)?)
}
/// Create an asynchronized unary RPC call.
pub fn unary_call_async<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientUnaryReceiver<Resp>> {
Call::unary_async(&self.channel, method, req, opt)
}
/// Create an asynchronized client streaming call.
///
/// Client can send a stream of requests and server responds with a single response.
pub fn client_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientCStreamSender<Req>, ClientCStreamReceiver<Resp>)> {
Call::client_streaming(&self.channel, method, opt)
}
/// Create an asynchronized server streaming call.
///
/// Client sends on request and server responds with a stream of responses.
pub fn server_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
req: &Req,
opt: CallOption,
) -> Result<ClientSStreamReceiver<Resp>> {
Call::server_streaming(&self.channel, method, req, opt)
}
/// Create an asynchronized duplex streaming call.
///
/// Client sends a stream of requests and server responds with a stream of responses.
/// The response stream is completely independent and both side can be sending messages
/// at the same time.
pub fn duplex_streaming<Req, Resp>(
&self,
method: &Method<Req, Resp>,
opt: CallOption,
) -> Result<(ClientDuplexSender<Req>, ClientDuplexReceiver<Resp>)> {
Call::duplex_streaming(&self.channel, method, opt)
}
/// Spawn the future into current gRPC poll thread.
///
/// This can reduce a lot of context switching, but please make
/// sure there is no heavy work in the future.
pub fn spawn<F>(&self, f: F)
where
F: Future<Output = ()> + Send +'static,
{
let kicker = self.kicker.clone();
Executor::new(self.channel.cq()).spawn(f, kicker)
}
}
| Client | identifier_name |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct | {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments(
_pr: &Region,
_rp: *mut Page,
_ep: *mut Page,
arguments: Ref<Vector<String>>,
) -> Ref<Options> {
let _r = Region::create(_pr);
let mut output_name: Option<String> = None;
let mut directory: Option<String> = None;
let mut files: Ref<Array<String>> = Ref::new(_r.page, Array::new());
let mut repl = false;
let mut args = arguments.iter();
loop {
let mut arg = args.next();
if let None = arg {
break;
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-o")) {
arg = args.next();
output_name = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-d")) {
arg = args.next();
directory = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-r")) {
repl = true;
continue;
}
}
files.add(*arg.unwrap());
}
Ref::new(
_rp,
Options {
files: Ref::new(_rp, Vector::from_array(_rp, files)),
output_name: output_name,
directory: directory,
repl: repl,
},
)
}
}
| Options | identifier_name |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct Options {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments(
_pr: &Region,
_rp: *mut Page,
_ep: *mut Page,
arguments: Ref<Vector<String>>,
) -> Ref<Options> {
let _r = Region::create(_pr);
let mut output_name: Option<String> = None;
let mut directory: Option<String> = None;
let mut files: Ref<Array<String>> = Ref::new(_r.page, Array::new());
let mut repl = false;
let mut args = arguments.iter();
loop {
let mut arg = args.next();
if let None = arg { | if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-o")) {
arg = args.next();
output_name = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-d")) {
arg = args.next();
directory = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-r")) {
repl = true;
continue;
}
}
files.add(*arg.unwrap());
}
Ref::new(
_rp,
Options {
files: Ref::new(_rp, Vector::from_array(_rp, files)),
output_name: output_name,
directory: directory,
repl: repl,
},
)
}
} | break;
}
{
let _r_1 = Region::create(&_r); | random_line_split |
options.rs | use scaly::containers::Ref;
use scaly::memory::Region;
use scaly::Equal;
use scaly::Page;
use scaly::{Array, String, Vector};
pub struct Options {
pub files: Ref<Vector<String>>,
pub output_name: Option<String>,
pub directory: Option<String>,
pub repl: bool,
}
impl Options {
pub fn parse_arguments(
_pr: &Region,
_rp: *mut Page,
_ep: *mut Page,
arguments: Ref<Vector<String>>,
) -> Ref<Options> {
let _r = Region::create(_pr);
let mut output_name: Option<String> = None;
let mut directory: Option<String> = None;
let mut files: Ref<Array<String>> = Ref::new(_r.page, Array::new());
let mut repl = false;
let mut args = arguments.iter();
loop {
let mut arg = args.next();
if let None = arg {
break;
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-o")) {
arg = args.next();
output_name = Some(*arg.unwrap());
continue;
}
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-d")) |
}
{
let _r_1 = Region::create(&_r);
if (arg.unwrap()).equals(&String::from_string_slice(_r_1.page, "-r")) {
repl = true;
continue;
}
}
files.add(*arg.unwrap());
}
Ref::new(
_rp,
Options {
files: Ref::new(_rp, Vector::from_array(_rp, files)),
output_name: output_name,
directory: directory,
repl: repl,
},
)
}
}
| {
arg = args.next();
directory = Some(*arg.unwrap());
continue;
} | conditional_block |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RENAMED_{}", original_variant_name))
}
}
#[derive(Debug)]
struct BlocklistedTypeImplementsTrait;
impl ParseCallbacks for BlocklistedTypeImplementsTrait {
fn | (
&self,
_name: &str,
derive_trait: DeriveTrait,
) -> Option<ImplementsTrait> {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
Some(ImplementsTrait::Yes)
}
}
}
pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {
match cb {
"enum-variant-rename" => Box::new(EnumVariantRename),
"blocklisted-type-implements-trait" => {
Box::new(BlocklistedTypeImplementsTrait)
}
_ => panic!("Couldn't find name ParseCallbacks: {}", cb),
}
}
| blocklisted_type_implements_trait | identifier_name |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RENAMED_{}", original_variant_name))
}
}
#[derive(Debug)]
struct BlocklistedTypeImplementsTrait;
impl ParseCallbacks for BlocklistedTypeImplementsTrait {
fn blocklisted_type_implements_trait(
&self,
_name: &str,
derive_trait: DeriveTrait,
) -> Option<ImplementsTrait> |
}
pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {
match cb {
"enum-variant-rename" => Box::new(EnumVariantRename),
"blocklisted-type-implements-trait" => {
Box::new(BlocklistedTypeImplementsTrait)
}
_ => panic!("Couldn't find name ParseCallbacks: {}", cb),
}
}
| {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
Some(ImplementsTrait::Yes)
}
} | identifier_body |
mod.rs | use bindgen::callbacks::*;
#[derive(Debug)]
struct EnumVariantRename;
impl ParseCallbacks for EnumVariantRename {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
Some(format!("RENAMED_{}", original_variant_name))
} |
impl ParseCallbacks for BlocklistedTypeImplementsTrait {
fn blocklisted_type_implements_trait(
&self,
_name: &str,
derive_trait: DeriveTrait,
) -> Option<ImplementsTrait> {
if derive_trait == DeriveTrait::Hash {
Some(ImplementsTrait::No)
} else {
Some(ImplementsTrait::Yes)
}
}
}
pub fn lookup(cb: &str) -> Box<dyn ParseCallbacks> {
match cb {
"enum-variant-rename" => Box::new(EnumVariantRename),
"blocklisted-type-implements-trait" => {
Box::new(BlocklistedTypeImplementsTrait)
}
_ => panic!("Couldn't find name ParseCallbacks: {}", cb),
}
} | }
#[derive(Debug)]
struct BlocklistedTypeImplementsTrait; | random_line_split |
duplex.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Higher level communication abstractions.
*/
#![allow(missing_doc)]
#![allow(deprecated)]
#![deprecated = "This type is replaced by having a pair of channels. This type \
is not fully composable with other channels in terms of \
or possible semantics on a duplex stream. It will be removed \
soon"]
use core::prelude::*;
use comm;
use comm::{Sender, Receiver, channel};
/// An extension of `pipes::stream` that allows both sending and receiving.
pub struct DuplexStream<S, R> {
tx: Sender<S>,
rx: Receiver<R>,
}
/// Creates a bidirectional stream.
pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
(DuplexStream { tx: tx1, rx: rx2 },
DuplexStream { tx: tx2, rx: rx1 })
}
// Allow these methods to be used without import:
impl<S:Send,R:Send> DuplexStream<S, R> {
pub fn send(&self, x: S) {
self.tx.send(x)
}
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn | (&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use comm::{duplex};
#[test]
pub fn duplex_stream_1() {
let (left, right) = duplex();
left.send("abc".to_string());
right.send(123i);
assert!(left.recv() == 123);
assert!(right.recv() == "abc".to_string());
}
}
| recv | identifier_name |
duplex.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Higher level communication abstractions.
*/
#![allow(missing_doc)]
#![allow(deprecated)]
#![deprecated = "This type is replaced by having a pair of channels. This type \
is not fully composable with other channels in terms of \
or possible semantics on a duplex stream. It will be removed \
soon"]
use core::prelude::*;
use comm;
use comm::{Sender, Receiver, channel};
/// An extension of `pipes::stream` that allows both sending and receiving.
pub struct DuplexStream<S, R> {
tx: Sender<S>,
rx: Receiver<R>,
}
/// Creates a bidirectional stream.
pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
(DuplexStream { tx: tx1, rx: rx2 },
DuplexStream { tx: tx2, rx: rx1 })
} |
// Allow these methods to be used without import:
impl<S:Send,R:Send> DuplexStream<S, R> {
pub fn send(&self, x: S) {
self.tx.send(x)
}
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn recv(&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use comm::{duplex};
#[test]
pub fn duplex_stream_1() {
let (left, right) = duplex();
left.send("abc".to_string());
right.send(123i);
assert!(left.recv() == 123);
assert!(right.recv() == "abc".to_string());
}
} | random_line_split |
|
duplex.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Higher level communication abstractions.
*/
#![allow(missing_doc)]
#![allow(deprecated)]
#![deprecated = "This type is replaced by having a pair of channels. This type \
is not fully composable with other channels in terms of \
or possible semantics on a duplex stream. It will be removed \
soon"]
use core::prelude::*;
use comm;
use comm::{Sender, Receiver, channel};
/// An extension of `pipes::stream` that allows both sending and receiving.
pub struct DuplexStream<S, R> {
tx: Sender<S>,
rx: Receiver<R>,
}
/// Creates a bidirectional stream.
pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
(DuplexStream { tx: tx1, rx: rx2 },
DuplexStream { tx: tx2, rx: rx1 })
}
// Allow these methods to be used without import:
impl<S:Send,R:Send> DuplexStream<S, R> {
pub fn send(&self, x: S) |
pub fn send_opt(&self, x: S) -> Result<(), S> {
self.tx.send_opt(x)
}
pub fn recv(&self) -> R {
self.rx.recv()
}
pub fn try_recv(&self) -> Result<R, comm::TryRecvError> {
self.rx.try_recv()
}
pub fn recv_opt(&self) -> Result<R, ()> {
self.rx.recv_opt()
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
use comm::{duplex};
#[test]
pub fn duplex_stream_1() {
let (left, right) = duplex();
left.send("abc".to_string());
right.send(123i);
assert!(left.recv() == 123);
assert!(right.recv() == "abc".to_string());
}
}
| {
self.tx.send(x)
} | identifier_body |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn | (pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_count = face_count * 3;
let t = (1.0 + 5.0_f32.sqrt()) / 2.0;
let n = (1. + t * t).sqrt();
let u = 1. / n;
let v = t / n;
let mut vertex_data = Vec::with_capacity(vertex_count);
vertex_data.extend_from_slice(&[
vertex([-u, v, 0.0]),
vertex([ u, v, 0.0]),
vertex([ -u, -v, 0.0]),
vertex([ u, -v, 0.0]),
vertex([ 0.0, -u, v]),
vertex([ 0.0, u, v]),
vertex([ 0.0, -u, -v]),
vertex([ 0.0, u, -v]),
vertex([ v, 0.0, -u]),
vertex([ v, 0.0, u]),
vertex([ -v, 0.0, -u]),
vertex([ -v, 0.0, u]),
]);
let mut index_data: Vec<u16> = Vec::with_capacity(index_count);
index_data.extend_from_slice(&[
// 5 faces around point 0
0, 11, 5,
0, 5, 1,
0, 1, 7,
0, 7, 10,
0, 10, 11,
// 5 adjacent faces
1, 5, 9,
5, 11, 4,
11, 10, 2,
10, 7, 6,
7, 1, 8,
// 5 faces around point 3
3, 9, 4,
3, 4, 2,
3, 2, 6,
3, 6, 8,
3, 8, 9,
// 5 adjacent faces
4, 9, 5,
2, 4, 11,
6, 2, 10,
8, 6, 7,
9, 8, 1,
]);
let mut cache = HashMap::new();
let mut next_indices = Vec::with_capacity(index_count);
{
let mut middle = |ia, ib| {
let key = if ia < ib { (ia, ib) } else { (ib, ia) };
cache.get(&key).cloned().unwrap_or_else(|| {
let pa = vertex_data[ia as usize].pos;
let pb = vertex_data[ib as usize].pos;
let middle = [
(pa[0] + pb[0]) / 2.0,
(pa[1] + pb[1]) / 2.0,
(pa[2] + pb[2]) / 2.0,
];
let norm = (middle[0] * middle[0] +
middle[1] * middle[1] +
middle[2] * middle[2]).sqrt();
let index = vertex_data.len() as u16;
let v = vertex([middle[0]/norm, middle[1]/norm, middle[2]/norm]);
vertex_data.push(v);
cache.insert(key, index);
index
})
};
for _ in 0..recursion {
for tri in index_data.chunks(3) {
let i1 = tri[0];
let i2 = tri[1];
let i3 = tri[2];
let a = middle(i1, i2);
let b = middle(i2, i3);
let c = middle(i3, i1);
next_indices.extend_from_slice(&[
i1, a, c,
a, i2, b,
c, b, i3,
a, b, c,
]);
}
mem::swap(&mut next_indices, &mut index_data);
next_indices.clear();
}
}
debug_assert!(vertex_data.len() == vertex_count);
debug_assert!(index_data.len() == index_count);
(vertex_data, index_data)
}
| vertex | identifier_name |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) | vertex([ 0.0, u, v]),
vertex([ 0.0, -u, -v]),
vertex([ 0.0, u, -v]),
vertex([ v, 0.0, -u]),
vertex([ v, 0.0, u]),
vertex([ -v, 0.0, -u]),
vertex([ -v, 0.0, u]),
]);
let mut index_data: Vec<u16> = Vec::with_capacity(index_count);
index_data.extend_from_slice(&[
// 5 faces around point 0
0, 11, 5,
0, 5, 1,
0, 1, 7,
0, 7, 10,
0, 10, 11,
// 5 adjacent faces
1, 5, 9,
5, 11, 4,
11, 10, 2,
10, 7, 6,
7, 1, 8,
// 5 faces around point 3
3, 9, 4,
3, 4, 2,
3, 2, 6,
3, 6, 8,
3, 8, 9,
// 5 adjacent faces
4, 9, 5,
2, 4, 11,
6, 2, 10,
8, 6, 7,
9, 8, 1,
]);
let mut cache = HashMap::new();
let mut next_indices = Vec::with_capacity(index_count);
{
let mut middle = |ia, ib| {
let key = if ia < ib { (ia, ib) } else { (ib, ia) };
cache.get(&key).cloned().unwrap_or_else(|| {
let pa = vertex_data[ia as usize].pos;
let pb = vertex_data[ib as usize].pos;
let middle = [
(pa[0] + pb[0]) / 2.0,
(pa[1] + pb[1]) / 2.0,
(pa[2] + pb[2]) / 2.0,
];
let norm = (middle[0] * middle[0] +
middle[1] * middle[1] +
middle[2] * middle[2]).sqrt();
let index = vertex_data.len() as u16;
let v = vertex([middle[0]/norm, middle[1]/norm, middle[2]/norm]);
vertex_data.push(v);
cache.insert(key, index);
index
})
};
for _ in 0..recursion {
for tri in index_data.chunks(3) {
let i1 = tri[0];
let i2 = tri[1];
let i3 = tri[2];
let a = middle(i1, i2);
let b = middle(i2, i3);
let c = middle(i3, i1);
next_indices.extend_from_slice(&[
i1, a, c,
a, i2, b,
c, b, i3,
a, b, c,
]);
}
mem::swap(&mut next_indices, &mut index_data);
next_indices.clear();
}
}
debug_assert!(vertex_data.len() == vertex_count);
debug_assert!(index_data.len() == index_count);
(vertex_data, index_data)
}
| {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_count = face_count * 3;
let t = (1.0 + 5.0_f32.sqrt()) / 2.0;
let n = (1. + t * t).sqrt();
let u = 1. / n;
let v = t / n;
let mut vertex_data = Vec::with_capacity(vertex_count);
vertex_data.extend_from_slice(&[
vertex([-u, v, 0.0]),
vertex([ u, v, 0.0]),
vertex([ -u, -v, 0.0]),
vertex([ u, -v, 0.0]),
vertex([ 0.0, -u, v]), | identifier_body |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else | ;
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_count = face_count * 3;
let t = (1.0 + 5.0_f32.sqrt()) / 2.0;
let n = (1. + t * t).sqrt();
let u = 1. / n;
let v = t / n;
let mut vertex_data = Vec::with_capacity(vertex_count);
vertex_data.extend_from_slice(&[
vertex([-u, v, 0.0]),
vertex([ u, v, 0.0]),
vertex([ -u, -v, 0.0]),
vertex([ u, -v, 0.0]),
vertex([ 0.0, -u, v]),
vertex([ 0.0, u, v]),
vertex([ 0.0, -u, -v]),
vertex([ 0.0, u, -v]),
vertex([ v, 0.0, -u]),
vertex([ v, 0.0, u]),
vertex([ -v, 0.0, -u]),
vertex([ -v, 0.0, u]),
]);
let mut index_data: Vec<u16> = Vec::with_capacity(index_count);
index_data.extend_from_slice(&[
// 5 faces around point 0
0, 11, 5,
0, 5, 1,
0, 1, 7,
0, 7, 10,
0, 10, 11,
// 5 adjacent faces
1, 5, 9,
5, 11, 4,
11, 10, 2,
10, 7, 6,
7, 1, 8,
// 5 faces around point 3
3, 9, 4,
3, 4, 2,
3, 2, 6,
3, 6, 8,
3, 8, 9,
// 5 adjacent faces
4, 9, 5,
2, 4, 11,
6, 2, 10,
8, 6, 7,
9, 8, 1,
]);
let mut cache = HashMap::new();
let mut next_indices = Vec::with_capacity(index_count);
{
let mut middle = |ia, ib| {
let key = if ia < ib { (ia, ib) } else { (ib, ia) };
cache.get(&key).cloned().unwrap_or_else(|| {
let pa = vertex_data[ia as usize].pos;
let pb = vertex_data[ib as usize].pos;
let middle = [
(pa[0] + pb[0]) / 2.0,
(pa[1] + pb[1]) / 2.0,
(pa[2] + pb[2]) / 2.0,
];
let norm = (middle[0] * middle[0] +
middle[1] * middle[1] +
middle[2] * middle[2]).sqrt();
let index = vertex_data.len() as u16;
let v = vertex([middle[0]/norm, middle[1]/norm, middle[2]/norm]);
vertex_data.push(v);
cache.insert(key, index);
index
})
};
for _ in 0..recursion {
for tri in index_data.chunks(3) {
let i1 = tri[0];
let i2 = tri[1];
let i3 = tri[2];
let a = middle(i1, i2);
let b = middle(i2, i3);
let c = middle(i3, i1);
next_indices.extend_from_slice(&[
i1, a, c,
a, i2, b,
c, b, i3,
a, b, c,
]);
}
mem::swap(&mut next_indices, &mut index_data);
next_indices.clear();
}
}
debug_assert!(vertex_data.len() == vertex_count);
debug_assert!(index_data.len() == index_count);
(vertex_data, index_data)
}
| { u } | conditional_block |
icosphere.rs | use std::collections::HashMap;
use std::mem;
use scene::Vertex;
fn vertex(pos: [f32; 3]) -> Vertex {
use std::f32::consts::{PI};
let u = pos[0].atan2(pos[2]) / (-2.0 * PI);
let u = if u < 0. { u + 1. } else { u };
let v = pos[1].asin() / PI + 0.5;
Vertex::new(pos, [u, v])
}
pub fn generate(recursion: u16) -> (Vec<Vertex>, Vec<u16>) {
let face_count = 20 * 4usize.pow(recursion as u32);
let edge_count = 3 * face_count / 2;
// Euler's formula
let vertex_count = 2 + edge_count - face_count;
let index_count = face_count * 3;
let t = (1.0 + 5.0_f32.sqrt()) / 2.0;
let n = (1. + t * t).sqrt();
let u = 1. / n;
let v = t / n;
let mut vertex_data = Vec::with_capacity(vertex_count);
vertex_data.extend_from_slice(&[
vertex([-u, v, 0.0]),
vertex([ u, v, 0.0]),
vertex([ -u, -v, 0.0]),
vertex([ u, -v, 0.0]),
vertex([ 0.0, -u, v]),
vertex([ 0.0, u, v]),
vertex([ 0.0, -u, -v]),
vertex([ 0.0, u, -v]),
vertex([ v, 0.0, -u]),
vertex([ v, 0.0, u]),
vertex([ -v, 0.0, -u]),
vertex([ -v, 0.0, u]),
]);
let mut index_data: Vec<u16> = Vec::with_capacity(index_count);
index_data.extend_from_slice(&[
// 5 faces around point 0
0, 11, 5,
0, 5, 1,
0, 1, 7,
0, 7, 10,
0, 10, 11,
| 5, 11, 4,
11, 10, 2,
10, 7, 6,
7, 1, 8,
// 5 faces around point 3
3, 9, 4,
3, 4, 2,
3, 2, 6,
3, 6, 8,
3, 8, 9,
// 5 adjacent faces
4, 9, 5,
2, 4, 11,
6, 2, 10,
8, 6, 7,
9, 8, 1,
]);
let mut cache = HashMap::new();
let mut next_indices = Vec::with_capacity(index_count);
{
let mut middle = |ia, ib| {
let key = if ia < ib { (ia, ib) } else { (ib, ia) };
cache.get(&key).cloned().unwrap_or_else(|| {
let pa = vertex_data[ia as usize].pos;
let pb = vertex_data[ib as usize].pos;
let middle = [
(pa[0] + pb[0]) / 2.0,
(pa[1] + pb[1]) / 2.0,
(pa[2] + pb[2]) / 2.0,
];
let norm = (middle[0] * middle[0] +
middle[1] * middle[1] +
middle[2] * middle[2]).sqrt();
let index = vertex_data.len() as u16;
let v = vertex([middle[0]/norm, middle[1]/norm, middle[2]/norm]);
vertex_data.push(v);
cache.insert(key, index);
index
})
};
for _ in 0..recursion {
for tri in index_data.chunks(3) {
let i1 = tri[0];
let i2 = tri[1];
let i3 = tri[2];
let a = middle(i1, i2);
let b = middle(i2, i3);
let c = middle(i3, i1);
next_indices.extend_from_slice(&[
i1, a, c,
a, i2, b,
c, b, i3,
a, b, c,
]);
}
mem::swap(&mut next_indices, &mut index_data);
next_indices.clear();
}
}
debug_assert!(vertex_data.len() == vertex_count);
debug_assert!(index_data.len() == index_count);
(vertex_data, index_data)
} | // 5 adjacent faces
1, 5, 9, | random_line_split |
lib.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::BTreeMap;
use std::collections::HashMap;
use clidispatch::global_flags::HgGlobalOpts;
use cliparser::alias::expand_aliases;
use cliparser::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exception!(cliparser, OptionRequiresArgument);
py_exception!(cliparser, OptionArgumentInvalid);
py_exception!(cliparser, OptionAmbiguous);
}
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "cliparser"].join(".");
let m = PyModule::new(py, &name)?;
m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?;
m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?;
m.add(
py,
"parse",
py_fn!(py, parse(args: Vec<String>, keep_sep: bool)),
)?;
m.add(
py,
"expandargs",
py_fn!(
py,
expand_args(
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool = false
)
),
)?;
m.add(
py,
"parsecommand",
py_fn!(
py,
parse_command(args: Vec<String>, definitions: Vec<FlagDef>)
),
)?;
{
use exceptions::*;
m.add(py, "AmbiguousCommand", AmbiguousCommand::type_object(py))?;
m.add(py, "CircularReference", CircularReference::type_object(py))?;
m.add(py, "MalformedAlias", MalformedAlias::type_object(py))?;
m.add(
py,
"OptionNotRecognized",
OptionNotRecognized::type_object(py),
)?;
m.add(
py,
"OptionRequiresArgument",
OptionRequiresArgument::type_object(py),
)?;
m.add(
py,
"OptionArgumentInvalid",
OptionArgumentInvalid::type_object(py),
)?;
m.add(py, "OptionAmbiguous", OptionAmbiguous::type_object(py))?;
}
Ok(m)
}
struct FlagDef {
short: Option<char>,
long: String,
default: Value,
}
impl<'s> FromPyObject<'s> for FlagDef { | if tuple.len(py) < 3 {
let msg = format!("flag defintion requires at least 3 items");
return Err(PyErr::new::<exc::ValueError, _>(py, msg));
}
let short: String = tuple.get_item(py, 0).extract(py)?;
let long: String = tuple.get_item(py, 1).extract(py)?;
let default: Value = tuple.get_item(py, 2).extract(py)?;
Ok(FlagDef {
short: short.chars().next(),
long,
default,
})
}
}
impl Into<Flag> for FlagDef {
fn into(self) -> Flag {
let description = "";
(self.short, self.long, description, self.default).into()
}
}
fn parse_command(
py: Python,
args: Vec<String>,
definitions: Vec<FlagDef>,
) -> PyResult<(Vec<Str>, HashMap<Str, Value>)> {
let flags: Vec<Flag> = definitions.into_iter().map(Into::into).collect();
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(flags)
.error_on_unknown_opts(true)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments: Vec<Str> = result.args().clone().into_iter().map(Str::from).collect();
let opts = result.opts().clone();
let options: HashMap<Str, Value> = opts
.into_iter()
.map(|(k, v)| (k.replace('-', "_").into(), v))
.collect();
Ok((arguments, options))
}
fn expand_args(
py: Python,
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool,
) -> PyResult<(Vec<Str>, Vec<Str>)> {
let cfg = &config.get_cfg(py);
if!strict &&!args.is_empty() {
// Expand args[0] from a prefix to a full command name
let mut command_map = BTreeMap::new();
for (i, name) in command_names.into_iter().enumerate() {
let i: isize = i as isize + 1; // avoid using 0
let multiples = expand_command_name(name);
let is_debug = multiples.iter().any(|s| s.starts_with("debug"));
for multiple in multiples.into_iter() {
command_map.insert(multiple, if is_debug { -i } else { i });
}
}
// Add command names from the alias configuration.
// XXX: This duplicates with clidispatch. They should be de-duplicated.
for name in cfg.keys("alias") {
let name = name.to_string();
if name.contains(":") {
continue;
}
let is_debug = name.starts_with("debug");
let i = command_map.len() as isize;
command_map.insert(name, if is_debug { -i } else { i });
}
}
let lookup = move |name: &str| {
if name.contains(":") {
return None;
}
match (cfg.get("alias", name), cfg.get("defaults", name)) {
(None, None) => None,
(Some(v), None) => Some(v.to_string()),
(None, Some(v)) => Some(format!("{} {}", name, v.as_ref())),
(Some(a), Some(d)) => {
// XXX: This makes defaults override alias if there are conflicted
// flags. The desired behavior is to make alias override defaults.
// However, [defaults] is deprecated and is likely only used
// by tests. So this might be fine.
Some(format!("{} {}", a.as_ref(), d.as_ref()))
}
}
};
let (expanded_args, replaced_aliases) =
expand_aliases(lookup, &args).map_err(|e| map_to_python_err(py, e))?;
let expanded_args: Vec<Str> = expanded_args.into_iter().map(Str::from).collect();
let replaced_aliases: Vec<Str> = replaced_aliases.into_iter().map(Str::from).collect();
Ok((expanded_args, replaced_aliases))
}
fn expand_command_name(name: String) -> Vec<String> {
name.trim_start_matches("^")
.split("|")
.map(|s| s.to_string())
.collect()
}
fn early_parse(py: Python, args: Vec<String>) -> PyResult<HashMap<String, PyObject>> {
let result = ParseOptions::new()
.ignore_prefix(true)
.early_parse(true)
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let rust_opts = result.opts().clone();
let mut opts = HashMap::new();
for (key, value) in rust_opts {
let val: PyObject = value.into_py_object(py).into_object();
opts.insert(key, val);
}
Ok(opts)
}
fn parse_args(py: Python, args: Vec<String>) -> PyResult<Vec<String>> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().clone();
Ok(arguments)
}
fn parse(
py: Python,
args: Vec<String>,
keep_sep: bool,
) -> PyResult<(Vec<Str>, HashMap<Str, PyObject>, usize)> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.keep_sep(keep_sep)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().iter().cloned().map(Str::from).collect();
let opts = result
.opts()
.iter()
.map(|(k, v)| (Str::from(k.clone()), v.to_py_object(py).into_object()))
.collect();
Ok((arguments, opts, result.first_arg_index()))
}
fn map_to_python_err(py: Python, err: ParseError) -> PyErr {
let msg = format!("{}", err);
match err {
ParseError::OptionNotRecognized { option_name } => {
return PyErr::new::<exceptions::OptionNotRecognized, _>(py, (msg, option_name));
}
ParseError::OptionRequiresArgument { option_name } => {
return PyErr::new::<exceptions::OptionRequiresArgument, _>(py, (msg, option_name));
}
ParseError::OptionArgumentInvalid {
option_name,
given,
expected,
} => {
return PyErr::new::<exceptions::OptionArgumentInvalid, _>(
py,
(msg, option_name, given, expected),
);
}
ParseError::OptionAmbiguous {
option_name,
possibilities,
} => {
return PyErr::new::<exceptions::OptionAmbiguous, _>(
py,
(msg, option_name, possibilities),
);
}
ParseError::AmbiguousCommand {
command_name,
possibilities,
} => {
return PyErr::new::<exceptions::AmbiguousCommand, _>(
py,
(msg, command_name, possibilities),
);
}
ParseError::CircularReference { command_name } => {
return PyErr::new::<exceptions::CircularReference, _>(py, (msg, command_name));
}
ParseError::MalformedAlias { name, value } => {
return PyErr::new::<exceptions::MalformedAlias, _>(py, (msg, name, value));
}
}
} | fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> {
let tuple: PyTuple = obj.extract(py)?; | random_line_split |
lib.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::BTreeMap;
use std::collections::HashMap;
use clidispatch::global_flags::HgGlobalOpts;
use cliparser::alias::expand_aliases;
use cliparser::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exception!(cliparser, OptionRequiresArgument);
py_exception!(cliparser, OptionArgumentInvalid);
py_exception!(cliparser, OptionAmbiguous);
}
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "cliparser"].join(".");
let m = PyModule::new(py, &name)?;
m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?;
m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?;
m.add(
py,
"parse",
py_fn!(py, parse(args: Vec<String>, keep_sep: bool)),
)?;
m.add(
py,
"expandargs",
py_fn!(
py,
expand_args(
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool = false
)
),
)?;
m.add(
py,
"parsecommand",
py_fn!(
py,
parse_command(args: Vec<String>, definitions: Vec<FlagDef>)
),
)?;
{
use exceptions::*;
m.add(py, "AmbiguousCommand", AmbiguousCommand::type_object(py))?;
m.add(py, "CircularReference", CircularReference::type_object(py))?;
m.add(py, "MalformedAlias", MalformedAlias::type_object(py))?;
m.add(
py,
"OptionNotRecognized",
OptionNotRecognized::type_object(py),
)?;
m.add(
py,
"OptionRequiresArgument",
OptionRequiresArgument::type_object(py),
)?;
m.add(
py,
"OptionArgumentInvalid",
OptionArgumentInvalid::type_object(py),
)?;
m.add(py, "OptionAmbiguous", OptionAmbiguous::type_object(py))?;
}
Ok(m)
}
struct FlagDef {
short: Option<char>,
long: String,
default: Value,
}
impl<'s> FromPyObject<'s> for FlagDef {
fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> {
let tuple: PyTuple = obj.extract(py)?;
if tuple.len(py) < 3 {
let msg = format!("flag defintion requires at least 3 items");
return Err(PyErr::new::<exc::ValueError, _>(py, msg));
}
let short: String = tuple.get_item(py, 0).extract(py)?;
let long: String = tuple.get_item(py, 1).extract(py)?;
let default: Value = tuple.get_item(py, 2).extract(py)?;
Ok(FlagDef {
short: short.chars().next(),
long,
default,
})
}
}
impl Into<Flag> for FlagDef {
fn into(self) -> Flag {
let description = "";
(self.short, self.long, description, self.default).into()
}
}
fn parse_command(
py: Python,
args: Vec<String>,
definitions: Vec<FlagDef>,
) -> PyResult<(Vec<Str>, HashMap<Str, Value>)> {
let flags: Vec<Flag> = definitions.into_iter().map(Into::into).collect();
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(flags)
.error_on_unknown_opts(true)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments: Vec<Str> = result.args().clone().into_iter().map(Str::from).collect();
let opts = result.opts().clone();
let options: HashMap<Str, Value> = opts
.into_iter()
.map(|(k, v)| (k.replace('-', "_").into(), v))
.collect();
Ok((arguments, options))
}
fn expand_args(
py: Python,
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool,
) -> PyResult<(Vec<Str>, Vec<Str>)> {
let cfg = &config.get_cfg(py);
if!strict &&!args.is_empty() {
// Expand args[0] from a prefix to a full command name
let mut command_map = BTreeMap::new();
for (i, name) in command_names.into_iter().enumerate() {
let i: isize = i as isize + 1; // avoid using 0
let multiples = expand_command_name(name);
let is_debug = multiples.iter().any(|s| s.starts_with("debug"));
for multiple in multiples.into_iter() {
command_map.insert(multiple, if is_debug { -i } else { i });
}
}
// Add command names from the alias configuration.
// XXX: This duplicates with clidispatch. They should be de-duplicated.
for name in cfg.keys("alias") {
let name = name.to_string();
if name.contains(":") {
continue;
}
let is_debug = name.starts_with("debug");
let i = command_map.len() as isize;
command_map.insert(name, if is_debug { -i } else { i });
}
}
let lookup = move |name: &str| {
if name.contains(":") {
return None;
}
match (cfg.get("alias", name), cfg.get("defaults", name)) {
(None, None) => None,
(Some(v), None) => Some(v.to_string()),
(None, Some(v)) => Some(format!("{} {}", name, v.as_ref())),
(Some(a), Some(d)) => {
// XXX: This makes defaults override alias if there are conflicted
// flags. The desired behavior is to make alias override defaults.
// However, [defaults] is deprecated and is likely only used
// by tests. So this might be fine.
Some(format!("{} {}", a.as_ref(), d.as_ref()))
}
}
};
let (expanded_args, replaced_aliases) =
expand_aliases(lookup, &args).map_err(|e| map_to_python_err(py, e))?;
let expanded_args: Vec<Str> = expanded_args.into_iter().map(Str::from).collect();
let replaced_aliases: Vec<Str> = replaced_aliases.into_iter().map(Str::from).collect();
Ok((expanded_args, replaced_aliases))
}
fn expand_command_name(name: String) -> Vec<String> {
name.trim_start_matches("^")
.split("|")
.map(|s| s.to_string())
.collect()
}
fn early_parse(py: Python, args: Vec<String>) -> PyResult<HashMap<String, PyObject>> {
let result = ParseOptions::new()
.ignore_prefix(true)
.early_parse(true)
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let rust_opts = result.opts().clone();
let mut opts = HashMap::new();
for (key, value) in rust_opts {
let val: PyObject = value.into_py_object(py).into_object();
opts.insert(key, val);
}
Ok(opts)
}
fn parse_args(py: Python, args: Vec<String>) -> PyResult<Vec<String>> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().clone();
Ok(arguments)
}
fn parse(
py: Python,
args: Vec<String>,
keep_sep: bool,
) -> PyResult<(Vec<Str>, HashMap<Str, PyObject>, usize)> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.keep_sep(keep_sep)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().iter().cloned().map(Str::from).collect();
let opts = result
.opts()
.iter()
.map(|(k, v)| (Str::from(k.clone()), v.to_py_object(py).into_object()))
.collect();
Ok((arguments, opts, result.first_arg_index()))
}
fn map_to_python_err(py: Python, err: ParseError) -> PyErr {
let msg = format!("{}", err);
match err {
ParseError::OptionNotRecognized { option_name } => {
return PyErr::new::<exceptions::OptionNotRecognized, _>(py, (msg, option_name));
}
ParseError::OptionRequiresArgument { option_name } => {
return PyErr::new::<exceptions::OptionRequiresArgument, _>(py, (msg, option_name));
}
ParseError::OptionArgumentInvalid {
option_name,
given,
expected,
} => |
ParseError::OptionAmbiguous {
option_name,
possibilities,
} => {
return PyErr::new::<exceptions::OptionAmbiguous, _>(
py,
(msg, option_name, possibilities),
);
}
ParseError::AmbiguousCommand {
command_name,
possibilities,
} => {
return PyErr::new::<exceptions::AmbiguousCommand, _>(
py,
(msg, command_name, possibilities),
);
}
ParseError::CircularReference { command_name } => {
return PyErr::new::<exceptions::CircularReference, _>(py, (msg, command_name));
}
ParseError::MalformedAlias { name, value } => {
return PyErr::new::<exceptions::MalformedAlias, _>(py, (msg, name, value));
}
}
}
| {
return PyErr::new::<exceptions::OptionArgumentInvalid, _>(
py,
(msg, option_name, given, expected),
);
} | conditional_block |
lib.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::BTreeMap;
use std::collections::HashMap;
use clidispatch::global_flags::HgGlobalOpts;
use cliparser::alias::expand_aliases;
use cliparser::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exception!(cliparser, OptionRequiresArgument);
py_exception!(cliparser, OptionArgumentInvalid);
py_exception!(cliparser, OptionAmbiguous);
}
pub fn | (py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "cliparser"].join(".");
let m = PyModule::new(py, &name)?;
m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?;
m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?;
m.add(
py,
"parse",
py_fn!(py, parse(args: Vec<String>, keep_sep: bool)),
)?;
m.add(
py,
"expandargs",
py_fn!(
py,
expand_args(
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool = false
)
),
)?;
m.add(
py,
"parsecommand",
py_fn!(
py,
parse_command(args: Vec<String>, definitions: Vec<FlagDef>)
),
)?;
{
use exceptions::*;
m.add(py, "AmbiguousCommand", AmbiguousCommand::type_object(py))?;
m.add(py, "CircularReference", CircularReference::type_object(py))?;
m.add(py, "MalformedAlias", MalformedAlias::type_object(py))?;
m.add(
py,
"OptionNotRecognized",
OptionNotRecognized::type_object(py),
)?;
m.add(
py,
"OptionRequiresArgument",
OptionRequiresArgument::type_object(py),
)?;
m.add(
py,
"OptionArgumentInvalid",
OptionArgumentInvalid::type_object(py),
)?;
m.add(py, "OptionAmbiguous", OptionAmbiguous::type_object(py))?;
}
Ok(m)
}
struct FlagDef {
short: Option<char>,
long: String,
default: Value,
}
impl<'s> FromPyObject<'s> for FlagDef {
fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> {
let tuple: PyTuple = obj.extract(py)?;
if tuple.len(py) < 3 {
let msg = format!("flag defintion requires at least 3 items");
return Err(PyErr::new::<exc::ValueError, _>(py, msg));
}
let short: String = tuple.get_item(py, 0).extract(py)?;
let long: String = tuple.get_item(py, 1).extract(py)?;
let default: Value = tuple.get_item(py, 2).extract(py)?;
Ok(FlagDef {
short: short.chars().next(),
long,
default,
})
}
}
impl Into<Flag> for FlagDef {
fn into(self) -> Flag {
let description = "";
(self.short, self.long, description, self.default).into()
}
}
fn parse_command(
py: Python,
args: Vec<String>,
definitions: Vec<FlagDef>,
) -> PyResult<(Vec<Str>, HashMap<Str, Value>)> {
let flags: Vec<Flag> = definitions.into_iter().map(Into::into).collect();
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(flags)
.error_on_unknown_opts(true)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments: Vec<Str> = result.args().clone().into_iter().map(Str::from).collect();
let opts = result.opts().clone();
let options: HashMap<Str, Value> = opts
.into_iter()
.map(|(k, v)| (k.replace('-', "_").into(), v))
.collect();
Ok((arguments, options))
}
fn expand_args(
py: Python,
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool,
) -> PyResult<(Vec<Str>, Vec<Str>)> {
let cfg = &config.get_cfg(py);
if!strict &&!args.is_empty() {
// Expand args[0] from a prefix to a full command name
let mut command_map = BTreeMap::new();
for (i, name) in command_names.into_iter().enumerate() {
let i: isize = i as isize + 1; // avoid using 0
let multiples = expand_command_name(name);
let is_debug = multiples.iter().any(|s| s.starts_with("debug"));
for multiple in multiples.into_iter() {
command_map.insert(multiple, if is_debug { -i } else { i });
}
}
// Add command names from the alias configuration.
// XXX: This duplicates with clidispatch. They should be de-duplicated.
for name in cfg.keys("alias") {
let name = name.to_string();
if name.contains(":") {
continue;
}
let is_debug = name.starts_with("debug");
let i = command_map.len() as isize;
command_map.insert(name, if is_debug { -i } else { i });
}
}
let lookup = move |name: &str| {
if name.contains(":") {
return None;
}
match (cfg.get("alias", name), cfg.get("defaults", name)) {
(None, None) => None,
(Some(v), None) => Some(v.to_string()),
(None, Some(v)) => Some(format!("{} {}", name, v.as_ref())),
(Some(a), Some(d)) => {
// XXX: This makes defaults override alias if there are conflicted
// flags. The desired behavior is to make alias override defaults.
// However, [defaults] is deprecated and is likely only used
// by tests. So this might be fine.
Some(format!("{} {}", a.as_ref(), d.as_ref()))
}
}
};
let (expanded_args, replaced_aliases) =
expand_aliases(lookup, &args).map_err(|e| map_to_python_err(py, e))?;
let expanded_args: Vec<Str> = expanded_args.into_iter().map(Str::from).collect();
let replaced_aliases: Vec<Str> = replaced_aliases.into_iter().map(Str::from).collect();
Ok((expanded_args, replaced_aliases))
}
fn expand_command_name(name: String) -> Vec<String> {
name.trim_start_matches("^")
.split("|")
.map(|s| s.to_string())
.collect()
}
fn early_parse(py: Python, args: Vec<String>) -> PyResult<HashMap<String, PyObject>> {
let result = ParseOptions::new()
.ignore_prefix(true)
.early_parse(true)
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let rust_opts = result.opts().clone();
let mut opts = HashMap::new();
for (key, value) in rust_opts {
let val: PyObject = value.into_py_object(py).into_object();
opts.insert(key, val);
}
Ok(opts)
}
fn parse_args(py: Python, args: Vec<String>) -> PyResult<Vec<String>> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().clone();
Ok(arguments)
}
fn parse(
py: Python,
args: Vec<String>,
keep_sep: bool,
) -> PyResult<(Vec<Str>, HashMap<Str, PyObject>, usize)> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.keep_sep(keep_sep)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().iter().cloned().map(Str::from).collect();
let opts = result
.opts()
.iter()
.map(|(k, v)| (Str::from(k.clone()), v.to_py_object(py).into_object()))
.collect();
Ok((arguments, opts, result.first_arg_index()))
}
fn map_to_python_err(py: Python, err: ParseError) -> PyErr {
let msg = format!("{}", err);
match err {
ParseError::OptionNotRecognized { option_name } => {
return PyErr::new::<exceptions::OptionNotRecognized, _>(py, (msg, option_name));
}
ParseError::OptionRequiresArgument { option_name } => {
return PyErr::new::<exceptions::OptionRequiresArgument, _>(py, (msg, option_name));
}
ParseError::OptionArgumentInvalid {
option_name,
given,
expected,
} => {
return PyErr::new::<exceptions::OptionArgumentInvalid, _>(
py,
(msg, option_name, given, expected),
);
}
ParseError::OptionAmbiguous {
option_name,
possibilities,
} => {
return PyErr::new::<exceptions::OptionAmbiguous, _>(
py,
(msg, option_name, possibilities),
);
}
ParseError::AmbiguousCommand {
command_name,
possibilities,
} => {
return PyErr::new::<exceptions::AmbiguousCommand, _>(
py,
(msg, command_name, possibilities),
);
}
ParseError::CircularReference { command_name } => {
return PyErr::new::<exceptions::CircularReference, _>(py, (msg, command_name));
}
ParseError::MalformedAlias { name, value } => {
return PyErr::new::<exceptions::MalformedAlias, _>(py, (msg, name, value));
}
}
}
| init_module | identifier_name |
lib.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::BTreeMap;
use std::collections::HashMap;
use clidispatch::global_flags::HgGlobalOpts;
use cliparser::alias::expand_aliases;
use cliparser::parser::*;
use cpython::*;
use cpython_ext::Str;
use pyconfigparser::config;
mod exceptions {
use super::*;
py_exception!(cliparser, AmbiguousCommand);
py_exception!(cliparser, CircularReference);
py_exception!(cliparser, MalformedAlias);
py_exception!(cliparser, OptionNotRecognized);
py_exception!(cliparser, OptionRequiresArgument);
py_exception!(cliparser, OptionArgumentInvalid);
py_exception!(cliparser, OptionAmbiguous);
}
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "cliparser"].join(".");
let m = PyModule::new(py, &name)?;
m.add(py, "earlyparse", py_fn!(py, early_parse(args: Vec<String>)))?;
m.add(py, "parseargs", py_fn!(py, parse_args(args: Vec<String>)))?;
m.add(
py,
"parse",
py_fn!(py, parse(args: Vec<String>, keep_sep: bool)),
)?;
m.add(
py,
"expandargs",
py_fn!(
py,
expand_args(
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool = false
)
),
)?;
m.add(
py,
"parsecommand",
py_fn!(
py,
parse_command(args: Vec<String>, definitions: Vec<FlagDef>)
),
)?;
{
use exceptions::*;
m.add(py, "AmbiguousCommand", AmbiguousCommand::type_object(py))?;
m.add(py, "CircularReference", CircularReference::type_object(py))?;
m.add(py, "MalformedAlias", MalformedAlias::type_object(py))?;
m.add(
py,
"OptionNotRecognized",
OptionNotRecognized::type_object(py),
)?;
m.add(
py,
"OptionRequiresArgument",
OptionRequiresArgument::type_object(py),
)?;
m.add(
py,
"OptionArgumentInvalid",
OptionArgumentInvalid::type_object(py),
)?;
m.add(py, "OptionAmbiguous", OptionAmbiguous::type_object(py))?;
}
Ok(m)
}
struct FlagDef {
short: Option<char>,
long: String,
default: Value,
}
impl<'s> FromPyObject<'s> for FlagDef {
fn extract(py: Python, obj: &'s PyObject) -> PyResult<Self> {
let tuple: PyTuple = obj.extract(py)?;
if tuple.len(py) < 3 {
let msg = format!("flag defintion requires at least 3 items");
return Err(PyErr::new::<exc::ValueError, _>(py, msg));
}
let short: String = tuple.get_item(py, 0).extract(py)?;
let long: String = tuple.get_item(py, 1).extract(py)?;
let default: Value = tuple.get_item(py, 2).extract(py)?;
Ok(FlagDef {
short: short.chars().next(),
long,
default,
})
}
}
impl Into<Flag> for FlagDef {
fn into(self) -> Flag {
let description = "";
(self.short, self.long, description, self.default).into()
}
}
fn parse_command(
py: Python,
args: Vec<String>,
definitions: Vec<FlagDef>,
) -> PyResult<(Vec<Str>, HashMap<Str, Value>)> {
let flags: Vec<Flag> = definitions.into_iter().map(Into::into).collect();
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(flags)
.error_on_unknown_opts(true)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments: Vec<Str> = result.args().clone().into_iter().map(Str::from).collect();
let opts = result.opts().clone();
let options: HashMap<Str, Value> = opts
.into_iter()
.map(|(k, v)| (k.replace('-', "_").into(), v))
.collect();
Ok((arguments, options))
}
fn expand_args(
py: Python,
config: config,
command_names: Vec<String>,
args: Vec<String>,
strict: bool,
) -> PyResult<(Vec<Str>, Vec<Str>)> | continue;
}
let is_debug = name.starts_with("debug");
let i = command_map.len() as isize;
command_map.insert(name, if is_debug { -i } else { i });
}
}
let lookup = move |name: &str| {
if name.contains(":") {
return None;
}
match (cfg.get("alias", name), cfg.get("defaults", name)) {
(None, None) => None,
(Some(v), None) => Some(v.to_string()),
(None, Some(v)) => Some(format!("{} {}", name, v.as_ref())),
(Some(a), Some(d)) => {
// XXX: This makes defaults override alias if there are conflicted
// flags. The desired behavior is to make alias override defaults.
// However, [defaults] is deprecated and is likely only used
// by tests. So this might be fine.
Some(format!("{} {}", a.as_ref(), d.as_ref()))
}
}
};
let (expanded_args, replaced_aliases) =
expand_aliases(lookup, &args).map_err(|e| map_to_python_err(py, e))?;
let expanded_args: Vec<Str> = expanded_args.into_iter().map(Str::from).collect();
let replaced_aliases: Vec<Str> = replaced_aliases.into_iter().map(Str::from).collect();
Ok((expanded_args, replaced_aliases))
}
fn expand_command_name(name: String) -> Vec<String> {
name.trim_start_matches("^")
.split("|")
.map(|s| s.to_string())
.collect()
}
fn early_parse(py: Python, args: Vec<String>) -> PyResult<HashMap<String, PyObject>> {
let result = ParseOptions::new()
.ignore_prefix(true)
.early_parse(true)
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let rust_opts = result.opts().clone();
let mut opts = HashMap::new();
for (key, value) in rust_opts {
let val: PyObject = value.into_py_object(py).into_object();
opts.insert(key, val);
}
Ok(opts)
}
fn parse_args(py: Python, args: Vec<String>) -> PyResult<Vec<String>> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().clone();
Ok(arguments)
}
fn parse(
py: Python,
args: Vec<String>,
keep_sep: bool,
) -> PyResult<(Vec<Str>, HashMap<Str, PyObject>, usize)> {
let result = ParseOptions::new()
.flag_alias("repo", "repository")
.flags(HgGlobalOpts::flags())
.keep_sep(keep_sep)
.parse_args(&args)
.map_err(|e| map_to_python_err(py, e))?;
let arguments = result.args().iter().cloned().map(Str::from).collect();
let opts = result
.opts()
.iter()
.map(|(k, v)| (Str::from(k.clone()), v.to_py_object(py).into_object()))
.collect();
Ok((arguments, opts, result.first_arg_index()))
}
fn map_to_python_err(py: Python, err: ParseError) -> PyErr {
let msg = format!("{}", err);
match err {
ParseError::OptionNotRecognized { option_name } => {
return PyErr::new::<exceptions::OptionNotRecognized, _>(py, (msg, option_name));
}
ParseError::OptionRequiresArgument { option_name } => {
return PyErr::new::<exceptions::OptionRequiresArgument, _>(py, (msg, option_name));
}
ParseError::OptionArgumentInvalid {
option_name,
given,
expected,
} => {
return PyErr::new::<exceptions::OptionArgumentInvalid, _>(
py,
(msg, option_name, given, expected),
);
}
ParseError::OptionAmbiguous {
option_name,
possibilities,
} => {
return PyErr::new::<exceptions::OptionAmbiguous, _>(
py,
(msg, option_name, possibilities),
);
}
ParseError::AmbiguousCommand {
command_name,
possibilities,
} => {
return PyErr::new::<exceptions::AmbiguousCommand, _>(
py,
(msg, command_name, possibilities),
);
}
ParseError::CircularReference { command_name } => {
return PyErr::new::<exceptions::CircularReference, _>(py, (msg, command_name));
}
ParseError::MalformedAlias { name, value } => {
return PyErr::new::<exceptions::MalformedAlias, _>(py, (msg, name, value));
}
}
}
| {
let cfg = &config.get_cfg(py);
if !strict && !args.is_empty() {
// Expand args[0] from a prefix to a full command name
let mut command_map = BTreeMap::new();
for (i, name) in command_names.into_iter().enumerate() {
let i: isize = i as isize + 1; // avoid using 0
let multiples = expand_command_name(name);
let is_debug = multiples.iter().any(|s| s.starts_with("debug"));
for multiple in multiples.into_iter() {
command_map.insert(multiple, if is_debug { -i } else { i });
}
}
// Add command names from the alias configuration.
// XXX: This duplicates with clidispatch. They should be de-duplicated.
for name in cfg.keys("alias") {
let name = name.to_string();
if name.contains(":") { | identifier_body |
seh.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // <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.
//! Win64 SEH (see http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx)
//!
//! On Windows (currently only on MSVC), the default exception handling
//! mechanism is Structured Exception Handling (SEH). This is quite different
//! than Dwarf-based exception handling (e.g. what other unix platforms use) in
//! terms of compiler internals, so LLVM is required to have a good deal of
//! extra support for SEH. Currently this support is somewhat lacking, so what's
//! here is the bare bones of SEH support.
//!
//! In a nutshell, what happens here is:
//!
//! 1. The `panic` function calls the standard Windows function `RaiseException`
//! with a Rust-specific code, triggering the unwinding process.
//! 2. All landing pads generated by the compiler (just "cleanup" landing pads)
//! use the personality function `__C_specific_handler`, a function in the
//! CRT, and the unwinding code in Windows will use this personality function
//! to execute all cleanup code on the stack.
//! 3. Eventually the "catch" code in `rust_try` (located in
//! src/rt/rust_try_msvc_64.ll) is executed, which will ensure that the
//! exception being caught is indeed a Rust exception, returning control back
//! into Rust.
//!
//! Some specific differences from the gcc-based exception handling are:
//!
//! * Rust has no custom personality function, it is instead *always*
//! __C_specific_handler, so the filtering is done in a C++-like manner
//! instead of in the personality function itself. Note that the specific
//! syntax for this (found in the rust_try_msvc_64.ll) is taken from an LLVM
//! test case for SEH.
//! * We've got some data to transmit across the unwinding boundary,
//! specifically a `Box<Any + Send +'static>`. In Dwarf-based unwinding this
//! data is part of the payload of the exception, but I have not currently
//! figured out how to do this with LLVM's bindings. Judging by some comments
//! in the LLVM test cases this may not even be possible currently with LLVM,
//! so this is just abandoned entirely. Instead the data is stored in a
//! thread-local in `panic` and retrieved during `cleanup`.
//!
//! So given all that, the bindings here are pretty small,
#![allow(bad_style)]
use prelude::v1::*;
use any::Any;
use libc::{c_ulong, DWORD, c_void};
use sys_common::thread_local::StaticKey;
// 0x R U S T
const RUST_PANIC: DWORD = 0x52555354;
static PANIC_DATA: StaticKey = StaticKey::new(None);
// This function is provided by kernel32.dll
extern "system" {
fn RaiseException(dwExceptionCode: DWORD,
dwExceptionFlags: DWORD,
nNumberOfArguments: DWORD,
lpArguments: *const c_ulong);
}
#[repr(C)]
pub struct EXCEPTION_POINTERS {
ExceptionRecord: *mut EXCEPTION_RECORD,
ContextRecord: *mut CONTEXT,
}
enum CONTEXT {}
#[repr(C)]
struct EXCEPTION_RECORD {
ExceptionCode: DWORD,
ExceptionFlags: DWORD,
ExceptionRecord: *mut _EXCEPTION_RECORD,
ExceptionAddress: *mut c_void,
NumberParameters: DWORD,
ExceptionInformation: [*mut c_ulong; EXCEPTION_MAXIMUM_PARAMETERS],
}
enum _EXCEPTION_RECORD {}
const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15;
pub unsafe fn panic(data: Box<Any + Send +'static>) ->! {
// See module docs above for an explanation of why `data` is stored in a
// thread local instead of being passed as an argument to the
// `RaiseException` function (which can in theory carry along arbitrary
// data).
let exception = Box::new(data);
rtassert!(PANIC_DATA.get().is_null());
PANIC_DATA.set(Box::into_raw(exception) as *mut u8);
RaiseException(RUST_PANIC, 0, 0, 0 as *const _);
rtabort!("could not unwind stack");
}
pub unsafe fn cleanup(ptr: *mut u8) -> Box<Any + Send +'static> {
// The `ptr` here actually corresponds to the code of the exception, and our
// real data is stored in our thread local.
rtassert!(ptr as DWORD == RUST_PANIC);
let data = PANIC_DATA.get() as *mut Box<Any + Send +'static>;
PANIC_DATA.set(0 as *mut u8);
rtassert!(!data.is_null());
*Box::from_raw(data)
}
// This is required by the compiler to exist (e.g. it's a lang item), but it's
// never actually called by the compiler because __C_specific_handler is the
// personality function that is always used. Hence this is just an aborting
// stub.
#[lang = "eh_personality"]
fn rust_eh_personality() {
unsafe { ::intrinsics::abort() }
}
// This is a function referenced from `rust_try_msvc_64.ll` which is used to
// filter the exceptions being caught by that function.
//
// In theory local variables can be accessed through the `rbp` parameter of this
// function, but a comment in an LLVM test case indicates that this is not
// implemented in LLVM, so this is just an idempotent function which doesn't
// ferry along any other information.
//
// This function just takes a look at the current EXCEPTION_RECORD being thrown
// to ensure that it's code is RUST_PANIC, which was set by the call to
// `RaiseException` above in the `panic` function.
#[no_mangle]
#[lang = "msvc_try_filter"]
pub extern fn __rust_try_filter(eh_ptrs: *mut EXCEPTION_POINTERS,
_rbp: *mut u8) -> i32 {
unsafe {
((*(*eh_ptrs).ExceptionRecord).ExceptionCode == RUST_PANIC) as i32
}
} | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
seh.rs | // Copyright 2015 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.
//! Win64 SEH (see http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx)
//!
//! On Windows (currently only on MSVC), the default exception handling
//! mechanism is Structured Exception Handling (SEH). This is quite different
//! than Dwarf-based exception handling (e.g. what other unix platforms use) in
//! terms of compiler internals, so LLVM is required to have a good deal of
//! extra support for SEH. Currently this support is somewhat lacking, so what's
//! here is the bare bones of SEH support.
//!
//! In a nutshell, what happens here is:
//!
//! 1. The `panic` function calls the standard Windows function `RaiseException`
//! with a Rust-specific code, triggering the unwinding process.
//! 2. All landing pads generated by the compiler (just "cleanup" landing pads)
//! use the personality function `__C_specific_handler`, a function in the
//! CRT, and the unwinding code in Windows will use this personality function
//! to execute all cleanup code on the stack.
//! 3. Eventually the "catch" code in `rust_try` (located in
//! src/rt/rust_try_msvc_64.ll) is executed, which will ensure that the
//! exception being caught is indeed a Rust exception, returning control back
//! into Rust.
//!
//! Some specific differences from the gcc-based exception handling are:
//!
//! * Rust has no custom personality function, it is instead *always*
//! __C_specific_handler, so the filtering is done in a C++-like manner
//! instead of in the personality function itself. Note that the specific
//! syntax for this (found in the rust_try_msvc_64.ll) is taken from an LLVM
//! test case for SEH.
//! * We've got some data to transmit across the unwinding boundary,
//! specifically a `Box<Any + Send +'static>`. In Dwarf-based unwinding this
//! data is part of the payload of the exception, but I have not currently
//! figured out how to do this with LLVM's bindings. Judging by some comments
//! in the LLVM test cases this may not even be possible currently with LLVM,
//! so this is just abandoned entirely. Instead the data is stored in a
//! thread-local in `panic` and retrieved during `cleanup`.
//!
//! So given all that, the bindings here are pretty small,
#![allow(bad_style)]
use prelude::v1::*;
use any::Any;
use libc::{c_ulong, DWORD, c_void};
use sys_common::thread_local::StaticKey;
// 0x R U S T
const RUST_PANIC: DWORD = 0x52555354;
static PANIC_DATA: StaticKey = StaticKey::new(None);
// This function is provided by kernel32.dll
extern "system" {
fn RaiseException(dwExceptionCode: DWORD,
dwExceptionFlags: DWORD,
nNumberOfArguments: DWORD,
lpArguments: *const c_ulong);
}
#[repr(C)]
pub struct EXCEPTION_POINTERS {
ExceptionRecord: *mut EXCEPTION_RECORD,
ContextRecord: *mut CONTEXT,
}
enum CONTEXT {}
#[repr(C)]
struct EXCEPTION_RECORD {
ExceptionCode: DWORD,
ExceptionFlags: DWORD,
ExceptionRecord: *mut _EXCEPTION_RECORD,
ExceptionAddress: *mut c_void,
NumberParameters: DWORD,
ExceptionInformation: [*mut c_ulong; EXCEPTION_MAXIMUM_PARAMETERS],
}
enum _EXCEPTION_RECORD {}
const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15;
pub unsafe fn panic(data: Box<Any + Send +'static>) ->! {
// See module docs above for an explanation of why `data` is stored in a
// thread local instead of being passed as an argument to the
// `RaiseException` function (which can in theory carry along arbitrary
// data).
let exception = Box::new(data);
rtassert!(PANIC_DATA.get().is_null());
PANIC_DATA.set(Box::into_raw(exception) as *mut u8);
RaiseException(RUST_PANIC, 0, 0, 0 as *const _);
rtabort!("could not unwind stack");
}
pub unsafe fn cleanup(ptr: *mut u8) -> Box<Any + Send +'static> {
// The `ptr` here actually corresponds to the code of the exception, and our
// real data is stored in our thread local.
rtassert!(ptr as DWORD == RUST_PANIC);
let data = PANIC_DATA.get() as *mut Box<Any + Send +'static>;
PANIC_DATA.set(0 as *mut u8);
rtassert!(!data.is_null());
*Box::from_raw(data)
}
// This is required by the compiler to exist (e.g. it's a lang item), but it's
// never actually called by the compiler because __C_specific_handler is the
// personality function that is always used. Hence this is just an aborting
// stub.
#[lang = "eh_personality"]
fn rust_eh_personality() {
unsafe { ::intrinsics::abort() }
}
// This is a function referenced from `rust_try_msvc_64.ll` which is used to
// filter the exceptions being caught by that function.
//
// In theory local variables can be accessed through the `rbp` parameter of this
// function, but a comment in an LLVM test case indicates that this is not
// implemented in LLVM, so this is just an idempotent function which doesn't
// ferry along any other information.
//
// This function just takes a look at the current EXCEPTION_RECORD being thrown
// to ensure that it's code is RUST_PANIC, which was set by the call to
// `RaiseException` above in the `panic` function.
#[no_mangle]
#[lang = "msvc_try_filter"]
pub extern fn __rust_try_filter(eh_ptrs: *mut EXCEPTION_POINTERS,
_rbp: *mut u8) -> i32 | {
unsafe {
((*(*eh_ptrs).ExceptionRecord).ExceptionCode == RUST_PANIC) as i32
}
} | identifier_body |
|
seh.rs | // Copyright 2015 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.
//! Win64 SEH (see http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx)
//!
//! On Windows (currently only on MSVC), the default exception handling
//! mechanism is Structured Exception Handling (SEH). This is quite different
//! than Dwarf-based exception handling (e.g. what other unix platforms use) in
//! terms of compiler internals, so LLVM is required to have a good deal of
//! extra support for SEH. Currently this support is somewhat lacking, so what's
//! here is the bare bones of SEH support.
//!
//! In a nutshell, what happens here is:
//!
//! 1. The `panic` function calls the standard Windows function `RaiseException`
//! with a Rust-specific code, triggering the unwinding process.
//! 2. All landing pads generated by the compiler (just "cleanup" landing pads)
//! use the personality function `__C_specific_handler`, a function in the
//! CRT, and the unwinding code in Windows will use this personality function
//! to execute all cleanup code on the stack.
//! 3. Eventually the "catch" code in `rust_try` (located in
//! src/rt/rust_try_msvc_64.ll) is executed, which will ensure that the
//! exception being caught is indeed a Rust exception, returning control back
//! into Rust.
//!
//! Some specific differences from the gcc-based exception handling are:
//!
//! * Rust has no custom personality function, it is instead *always*
//! __C_specific_handler, so the filtering is done in a C++-like manner
//! instead of in the personality function itself. Note that the specific
//! syntax for this (found in the rust_try_msvc_64.ll) is taken from an LLVM
//! test case for SEH.
//! * We've got some data to transmit across the unwinding boundary,
//! specifically a `Box<Any + Send +'static>`. In Dwarf-based unwinding this
//! data is part of the payload of the exception, but I have not currently
//! figured out how to do this with LLVM's bindings. Judging by some comments
//! in the LLVM test cases this may not even be possible currently with LLVM,
//! so this is just abandoned entirely. Instead the data is stored in a
//! thread-local in `panic` and retrieved during `cleanup`.
//!
//! So given all that, the bindings here are pretty small,
#![allow(bad_style)]
use prelude::v1::*;
use any::Any;
use libc::{c_ulong, DWORD, c_void};
use sys_common::thread_local::StaticKey;
// 0x R U S T
const RUST_PANIC: DWORD = 0x52555354;
static PANIC_DATA: StaticKey = StaticKey::new(None);
// This function is provided by kernel32.dll
extern "system" {
fn RaiseException(dwExceptionCode: DWORD,
dwExceptionFlags: DWORD,
nNumberOfArguments: DWORD,
lpArguments: *const c_ulong);
}
#[repr(C)]
pub struct EXCEPTION_POINTERS {
ExceptionRecord: *mut EXCEPTION_RECORD,
ContextRecord: *mut CONTEXT,
}
enum CONTEXT {}
#[repr(C)]
struct EXCEPTION_RECORD {
ExceptionCode: DWORD,
ExceptionFlags: DWORD,
ExceptionRecord: *mut _EXCEPTION_RECORD,
ExceptionAddress: *mut c_void,
NumberParameters: DWORD,
ExceptionInformation: [*mut c_ulong; EXCEPTION_MAXIMUM_PARAMETERS],
}
enum | {}
const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15;
pub unsafe fn panic(data: Box<Any + Send +'static>) ->! {
// See module docs above for an explanation of why `data` is stored in a
// thread local instead of being passed as an argument to the
// `RaiseException` function (which can in theory carry along arbitrary
// data).
let exception = Box::new(data);
rtassert!(PANIC_DATA.get().is_null());
PANIC_DATA.set(Box::into_raw(exception) as *mut u8);
RaiseException(RUST_PANIC, 0, 0, 0 as *const _);
rtabort!("could not unwind stack");
}
pub unsafe fn cleanup(ptr: *mut u8) -> Box<Any + Send +'static> {
// The `ptr` here actually corresponds to the code of the exception, and our
// real data is stored in our thread local.
rtassert!(ptr as DWORD == RUST_PANIC);
let data = PANIC_DATA.get() as *mut Box<Any + Send +'static>;
PANIC_DATA.set(0 as *mut u8);
rtassert!(!data.is_null());
*Box::from_raw(data)
}
// This is required by the compiler to exist (e.g. it's a lang item), but it's
// never actually called by the compiler because __C_specific_handler is the
// personality function that is always used. Hence this is just an aborting
// stub.
#[lang = "eh_personality"]
fn rust_eh_personality() {
unsafe { ::intrinsics::abort() }
}
// This is a function referenced from `rust_try_msvc_64.ll` which is used to
// filter the exceptions being caught by that function.
//
// In theory local variables can be accessed through the `rbp` parameter of this
// function, but a comment in an LLVM test case indicates that this is not
// implemented in LLVM, so this is just an idempotent function which doesn't
// ferry along any other information.
//
// This function just takes a look at the current EXCEPTION_RECORD being thrown
// to ensure that it's code is RUST_PANIC, which was set by the call to
// `RaiseException` above in the `panic` function.
#[no_mangle]
#[lang = "msvc_try_filter"]
pub extern fn __rust_try_filter(eh_ptrs: *mut EXCEPTION_POINTERS,
_rbp: *mut u8) -> i32 {
unsafe {
((*(*eh_ptrs).ExceptionRecord).ExceptionCode == RUST_PANIC) as i32
}
}
| _EXCEPTION_RECORD | identifier_name |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct | {
gl: GlGraphics, // OpenGL drawing backend.
rotation: f64 // Rotation for the square.
}
impl App {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0);
let rotation = self.rotation;
let (x, y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.gl.draw(args.viewport(), |c, gl| {
// Clear the screen.
clear(GREEN, gl);
let transform = c.transform.trans(x, y)
.rot_rad(rotation)
.trans(-25.0, -25.0);
// Draw a box rotating around the middle of the screen.
rectangle(RED, square, transform, gl);
});
}
fn update(&mut self, args: &UpdateArgs) {
// Rotate 2 radians per second.
self.rotation += 2.0 * args.dt;
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
// let opengl = OpenGL::V3_2;
let opengl = OpenGL::V2_1;
// Create an Glutin window.
let mut window: Window = WindowSettings::new(
"spinning-square",
[200, 200]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// Create a new game and run it.
let mut app = App {
gl: GlGraphics::new(opengl),
rotation: 0.0
};
let mut events = window.events();
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
app.update(&u);
}
}
}
| App | identifier_name |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
rotation: f64 // Rotation for the square.
}
impl App {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0);
let rotation = self.rotation;
let (x, y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.gl.draw(args.viewport(), |c, gl| {
// Clear the screen.
clear(GREEN, gl);
let transform = c.transform.trans(x, y)
.rot_rad(rotation)
.trans(-25.0, -25.0);
// Draw a box rotating around the middle of the screen.
rectangle(RED, square, transform, gl);
});
}
fn update(&mut self, args: &UpdateArgs) {
// Rotate 2 radians per second.
self.rotation += 2.0 * args.dt;
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
// let opengl = OpenGL::V3_2;
let opengl = OpenGL::V2_1;
// Create an Glutin window.
let mut window: Window = WindowSettings::new(
"spinning-square",
[200, 200]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// Create a new game and run it.
let mut app = App {
gl: GlGraphics::new(opengl),
rotation: 0.0
};
let mut events = window.events();
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() |
if let Some(u) = e.update_args() {
app.update(&u);
}
}
}
| {
app.render(&r);
} | conditional_block |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
rotation: f64 // Rotation for the square.
}
impl App {
fn render(&mut self, args: &RenderArgs) | rectangle(RED, square, transform, gl);
});
}
fn update(&mut self, args: &UpdateArgs) {
// Rotate 2 radians per second.
self.rotation += 2.0 * args.dt;
}
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
// let opengl = OpenGL::V3_2;
let opengl = OpenGL::V2_1;
// Create an Glutin window.
let mut window: Window = WindowSettings::new(
"spinning-square",
[200, 200]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// Create a new game and run it.
let mut app = App {
gl: GlGraphics::new(opengl),
rotation: 0.0
};
let mut events = window.events();
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
app.update(&u);
}
}
}
| {
use graphics::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0);
let rotation = self.rotation;
let (x, y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.gl.draw(args.viewport(), |c, gl| {
// Clear the screen.
clear(GREEN, gl);
let transform = c.transform.trans(x, y)
.rot_rad(rotation)
.trans(-25.0, -25.0);
// Draw a box rotating around the middle of the screen. | identifier_body |
main.rs | extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
use piston::window::WindowSettings;
use piston::event_loop::*;
use piston::input::*;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::{ GlGraphics, OpenGL };
pub struct App {
gl: GlGraphics, // OpenGL drawing backend.
rotation: f64 // Rotation for the square.
}
impl App {
fn render(&mut self, args: &RenderArgs) {
use graphics::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, 50.0);
let rotation = self.rotation;
let (x, y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.gl.draw(args.viewport(), |c, gl| {
// Clear the screen.
clear(GREEN, gl);
let transform = c.transform.trans(x, y)
.rot_rad(rotation)
.trans(-25.0, -25.0);
// Draw a box rotating around the middle of the screen.
rectangle(RED, square, transform, gl);
});
}
fn update(&mut self, args: &UpdateArgs) { | }
}
fn main() {
// Change this to OpenGL::V2_1 if not working.
// let opengl = OpenGL::V3_2;
let opengl = OpenGL::V2_1;
// Create an Glutin window.
let mut window: Window = WindowSettings::new(
"spinning-square",
[200, 200]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// Create a new game and run it.
let mut app = App {
gl: GlGraphics::new(opengl),
rotation: 0.0
};
let mut events = window.events();
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
app.update(&u);
}
}
} | // Rotate 2 radians per second.
self.rotation += 2.0 * args.dt; | random_line_split |
primitive_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! List of primitives.
use traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder,
PrimitiveElement};
use Result;
#[derive(Clone, Copy)]
pub struct Owned<T> {
marker: ::std::marker::PhantomData<T>,
}
impl <'a, T> ::traits::Owned<'a> for Owned<T> where T: PrimitiveElement {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
#[derive(Clone, Copy)]
pub struct Reader<'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
reader : ListReader<'a>
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b, T> {
Reader::<'b, T> { reader : reader, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, T>{
let l = self.len();
ListIter::new(self, l)
}
}
impl <'a, T : PrimitiveElement> FromPointerReader<'a> for Reader<'a, T> {
fn get_from_pointer(reader : &PointerReader<'a>) -> Result<Reader<'a, T>> {
Ok(Reader { reader : try!(reader.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T: PrimitiveElement> IndexMove<u32, T> for Reader<'a, T>{
fn index_move(&self, index : u32) -> T {
self.get(index)
}
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn get(&self, index : u32) -> T {
assert!(index < self.len());
PrimitiveElement::get(&self.reader, index)
}
}
pub struct | <'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
builder : ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: PrimitiveElement {
pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> {
Builder { builder : builder, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.builder.len() }
pub fn set(&mut self, index : u32, value : T) {
PrimitiveElement::set(&self.builder, index, value);
}
}
impl <'a, T: PrimitiveElement> FromPointerBuilder<'a> for Builder<'a, T> {
fn init_pointer(builder : PointerBuilder<'a>, size : u32) -> Builder<'a, T> {
Builder { builder : builder.init_list(T::element_size(), size),
marker : ::std::marker::PhantomData }
}
fn get_from_pointer(builder : PointerBuilder<'a>) -> Result<Builder<'a, T>> {
Ok(Builder { builder : try!(builder.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T : PrimitiveElement> Builder<'a, T> {
pub fn get(&self, index : u32) -> T {
assert!(index < self.len());
PrimitiveElement::get_from_builder(&self.builder, index)
}
}
impl <'a, T> ::traits::SetPointerBuilder<Builder<'a, T>> for Reader<'a, T>
where T: PrimitiveElement
{
fn set_pointer_builder<'b>(pointer: ::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>) -> Result<()> {
pointer.set_list(&value.reader)
}
}
| Builder | identifier_name |
primitive_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
// | // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! List of primitives.
use traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder,
PrimitiveElement};
use Result;
#[derive(Clone, Copy)]
pub struct Owned<T> {
marker: ::std::marker::PhantomData<T>,
}
impl <'a, T> ::traits::Owned<'a> for Owned<T> where T: PrimitiveElement {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
#[derive(Clone, Copy)]
pub struct Reader<'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
reader : ListReader<'a>
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b, T> {
Reader::<'b, T> { reader : reader, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, T>{
let l = self.len();
ListIter::new(self, l)
}
}
impl <'a, T : PrimitiveElement> FromPointerReader<'a> for Reader<'a, T> {
fn get_from_pointer(reader : &PointerReader<'a>) -> Result<Reader<'a, T>> {
Ok(Reader { reader : try!(reader.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T: PrimitiveElement> IndexMove<u32, T> for Reader<'a, T>{
fn index_move(&self, index : u32) -> T {
self.get(index)
}
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn get(&self, index : u32) -> T {
assert!(index < self.len());
PrimitiveElement::get(&self.reader, index)
}
}
pub struct Builder<'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
builder : ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: PrimitiveElement {
pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> {
Builder { builder : builder, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.builder.len() }
pub fn set(&mut self, index : u32, value : T) {
PrimitiveElement::set(&self.builder, index, value);
}
}
impl <'a, T: PrimitiveElement> FromPointerBuilder<'a> for Builder<'a, T> {
fn init_pointer(builder : PointerBuilder<'a>, size : u32) -> Builder<'a, T> {
Builder { builder : builder.init_list(T::element_size(), size),
marker : ::std::marker::PhantomData }
}
fn get_from_pointer(builder : PointerBuilder<'a>) -> Result<Builder<'a, T>> {
Ok(Builder { builder : try!(builder.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T : PrimitiveElement> Builder<'a, T> {
pub fn get(&self, index : u32) -> T {
assert!(index < self.len());
PrimitiveElement::get_from_builder(&self.builder, index)
}
}
impl <'a, T> ::traits::SetPointerBuilder<Builder<'a, T>> for Reader<'a, T>
where T: PrimitiveElement
{
fn set_pointer_builder<'b>(pointer: ::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>) -> Result<()> {
pointer.set_list(&value.reader)
}
} | // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | random_line_split |
primitive_list.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! List of primitives.
use traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder,
PrimitiveElement};
use Result;
#[derive(Clone, Copy)]
pub struct Owned<T> {
marker: ::std::marker::PhantomData<T>,
}
impl <'a, T> ::traits::Owned<'a> for Owned<T> where T: PrimitiveElement {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
#[derive(Clone, Copy)]
pub struct Reader<'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
reader : ListReader<'a>
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn new<'b>(reader : ListReader<'b>) -> Reader<'b, T> {
Reader::<'b, T> { reader : reader, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, T>{
let l = self.len();
ListIter::new(self, l)
}
}
impl <'a, T : PrimitiveElement> FromPointerReader<'a> for Reader<'a, T> {
fn get_from_pointer(reader : &PointerReader<'a>) -> Result<Reader<'a, T>> {
Ok(Reader { reader : try!(reader.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T: PrimitiveElement> IndexMove<u32, T> for Reader<'a, T>{
fn index_move(&self, index : u32) -> T {
self.get(index)
}
}
impl <'a, T : PrimitiveElement> Reader<'a, T> {
pub fn get(&self, index : u32) -> T |
}
pub struct Builder<'a, T> where T: PrimitiveElement {
marker : ::std::marker::PhantomData<T>,
builder : ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: PrimitiveElement {
pub fn new(builder : ListBuilder<'a>) -> Builder<'a, T> {
Builder { builder : builder, marker : ::std::marker::PhantomData }
}
pub fn len(&self) -> u32 { self.builder.len() }
pub fn set(&mut self, index : u32, value : T) {
PrimitiveElement::set(&self.builder, index, value);
}
}
impl <'a, T: PrimitiveElement> FromPointerBuilder<'a> for Builder<'a, T> {
fn init_pointer(builder : PointerBuilder<'a>, size : u32) -> Builder<'a, T> {
Builder { builder : builder.init_list(T::element_size(), size),
marker : ::std::marker::PhantomData }
}
fn get_from_pointer(builder : PointerBuilder<'a>) -> Result<Builder<'a, T>> {
Ok(Builder { builder : try!(builder.get_list(T::element_size(), ::std::ptr::null())),
marker : ::std::marker::PhantomData })
}
}
impl <'a, T : PrimitiveElement> Builder<'a, T> {
pub fn get(&self, index : u32) -> T {
assert!(index < self.len());
PrimitiveElement::get_from_builder(&self.builder, index)
}
}
impl <'a, T> ::traits::SetPointerBuilder<Builder<'a, T>> for Reader<'a, T>
where T: PrimitiveElement
{
fn set_pointer_builder<'b>(pointer: ::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>) -> Result<()> {
pointer.set_list(&value.reader)
}
}
| {
assert!(index < self.len());
PrimitiveElement::get(&self.reader, index)
} | identifier_body |
eg-enum-use.rs | #![allow(dead_code)]
enum HTTPGood {
HTTP200,
HTTP300,
}
enum HTTPBad {
HTTP400,
HTTP500,
}
fn server_debug() {
use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping
use HTTPBad::*; // automatically use each name
let good = HTTP200; // equivalent to HTTPGood::HTTP200
let bad = HTTP500; // equivalent to HTTPBad::HTTP500 | match bad {
HTTP400 => println!("bad client"),
HTTP500 => println!("bad server"),
}
}
enum BrowserEvent {
// may be unit like
Render,
Clear,
// tuple structs
KeyPress(char),
LoadFrame(String),
// or structs
Click { x: i64, y: i64 },
}
fn browser_debug(event: BrowserEvent) {
match event {
BrowserEvent::Render => println!("render page"),
BrowserEvent::Clear => println!("..."),
BrowserEvent::KeyPress(c) => println!("pressed `{}`", c),
BrowserEvent::LoadFrame(u) => println!("fetch `{}`", u),
BrowserEvent::Click {x,y} => {
println!("clicked at `{},{}`", x,y);
},
}
}
fn main(){
server_debug();
let render = BrowserEvent::Render;
let clear = BrowserEvent::Clear;
let keypress = BrowserEvent::KeyPress('z');
let frame = BrowserEvent::LoadFrame("example.com".to_owned()); // creates an owned String from string slice
let click = BrowserEvent::Click {x: 120, y: 240};
browser_debug(render);
browser_debug(clear);
browser_debug(keypress);
browser_debug(frame);
browser_debug(click);
} |
match good {
HTTP200 => println!("okay"),
HTTP300 => println!("redirect"),
} | random_line_split |
eg-enum-use.rs | #![allow(dead_code)]
enum HTTPGood {
HTTP200,
HTTP300,
}
enum HTTPBad {
HTTP400,
HTTP500,
}
fn server_debug() {
use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping
use HTTPBad::*; // automatically use each name
let good = HTTP200; // equivalent to HTTPGood::HTTP200
let bad = HTTP500; // equivalent to HTTPBad::HTTP500
match good {
HTTP200 => println!("okay"),
HTTP300 => println!("redirect"),
}
match bad {
HTTP400 => println!("bad client"),
HTTP500 => println!("bad server"),
}
}
enum | {
// may be unit like
Render,
Clear,
// tuple structs
KeyPress(char),
LoadFrame(String),
// or structs
Click { x: i64, y: i64 },
}
fn browser_debug(event: BrowserEvent) {
match event {
BrowserEvent::Render => println!("render page"),
BrowserEvent::Clear => println!("..."),
BrowserEvent::KeyPress(c) => println!("pressed `{}`", c),
BrowserEvent::LoadFrame(u) => println!("fetch `{}`", u),
BrowserEvent::Click {x,y} => {
println!("clicked at `{},{}`", x,y);
},
}
}
fn main(){
server_debug();
let render = BrowserEvent::Render;
let clear = BrowserEvent::Clear;
let keypress = BrowserEvent::KeyPress('z');
let frame = BrowserEvent::LoadFrame("example.com".to_owned()); // creates an owned String from string slice
let click = BrowserEvent::Click {x: 120, y: 240};
browser_debug(render);
browser_debug(clear);
browser_debug(keypress);
browser_debug(frame);
browser_debug(click);
}
| BrowserEvent | identifier_name |
eg-enum-use.rs | #![allow(dead_code)]
enum HTTPGood {
HTTP200,
HTTP300,
}
enum HTTPBad {
HTTP400,
HTTP500,
}
fn server_debug() {
use HTTPGood::{HTTP200, HTTP300}; // explicitly pick name without manual scoping
use HTTPBad::*; // automatically use each name
let good = HTTP200; // equivalent to HTTPGood::HTTP200
let bad = HTTP500; // equivalent to HTTPBad::HTTP500
match good {
HTTP200 => println!("okay"),
HTTP300 => println!("redirect"),
}
match bad {
HTTP400 => println!("bad client"),
HTTP500 => println!("bad server"),
}
}
enum BrowserEvent {
// may be unit like
Render,
Clear,
// tuple structs
KeyPress(char),
LoadFrame(String),
// or structs
Click { x: i64, y: i64 },
}
fn browser_debug(event: BrowserEvent) {
match event {
BrowserEvent::Render => println!("render page"),
BrowserEvent::Clear => println!("..."),
BrowserEvent::KeyPress(c) => println!("pressed `{}`", c),
BrowserEvent::LoadFrame(u) => println!("fetch `{}`", u),
BrowserEvent::Click {x,y} => {
println!("clicked at `{},{}`", x,y);
},
}
}
fn main() | {
server_debug();
let render = BrowserEvent::Render;
let clear = BrowserEvent::Clear;
let keypress = BrowserEvent::KeyPress('z');
let frame = BrowserEvent::LoadFrame("example.com".to_owned()); // creates an owned String from string slice
let click = BrowserEvent::Click {x: 120, y: 240};
browser_debug(render);
browser_debug(clear);
browser_debug(keypress);
browser_debug(frame);
browser_debug(click);
} | identifier_body |
|
pratparser.rs | enum | {
Atom(String),
Cons(String, Vec<S>),
}
impl std::fmt::Display for S {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
S::Atom(i) => write!(f, "{}", i),
S::Cons(head, rest) => {
write!(f, "({}", head)?;
for s in rest {
write!(f, " {}", s)?
}
write!(f, ")")
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token {
Atom(char),
Op(char),
Eof,
}
struct Lexer {
tokens: Vec<Token>,
}
impl Lexer {
fn new(input: &str) -> Lexer {
let mut tokens = input
.chars()
.filter(|it|!it.is_ascii_whitespace())
.map(|c| match c {
'0'..='9' | 'a'..='z' | 'A'..='Z' => Token::Atom(c),
_ => Token::Op(c),
})
.collect::<Vec<_>>();
tokens.reverse();
Lexer { tokens }
}
fn next(&mut self) -> Token {
self.tokens.pop().unwrap_or(Token::Eof)
}
fn peek(&mut self) -> Token {
self.tokens.last().copied().unwrap_or(Token::Eof)
}
}
fn expr(input: &str) -> S {
let mut lexer = Lexer::new(input);
expr_bp(&mut lexer, 0)
}
fn expr_bp(lexer: &mut Lexer, min_bp: u8) -> S {
let mut lhs = match lexer.next() {
Token::Atom(it) => S::Atom(it.to_string()),
Token::Op('(') => {
let lhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(')'));
lhs
}
Token::Op(op) => {
let ((), r_bp) = prefix_binding_power(op);
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![rhs])
}
t => panic!("bad token: {:?}", t),
};
loop {
let op = match lexer.peek() {
Token::Eof => break,
Token::Op(op) => op,
t => panic!("bad token: {:?}", t),
};
if let Some((l_bp, ())) = postfix_binding_power(op) {
if l_bp < min_bp {
break;
}
lexer.next();
lhs = match op {
'[' => {
let rhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(']'));
S::Cons(op.to_string(), vec![lhs, rhs])
}
'(' => {
let mut args = vec![expr_bp(lexer, 0)];
while lexer.peek() == Token::Op(',') {
lexer.next();
let arg = expr_bp(lexer, 0);
args.push(arg);
}
assert_eq!(lexer.next(), Token::Op(')'));
let mut v = vec![lhs];
v.append(&mut args);
S::Cons("invoke".to_string(), v)
}
_ => S::Cons(op.to_string(), vec![lhs]),
};
continue;
}
if let Some((l_bp, r_bp)) = infix_binding_power(op) {
if l_bp < min_bp {
break;
}
lexer.next();
lhs = if op == '?' {
let mhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(':'));
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![lhs, mhs, rhs])
} else {
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![lhs, rhs])
};
continue;
}
break;
}
lhs
}
fn prefix_binding_power(op: char) -> ((), u8) {
match op {
'+' | '-' => ((), 9),
_ => panic!("bad op: {:?}", op),
}
}
fn postfix_binding_power(op: char) -> Option<(u8, ())> {
let res = match op {
'!' => (11, ()),
'[' | '(' => (11, ()),
_ => return None,
};
Some(res)
}
fn infix_binding_power(op: char) -> Option<(u8, u8)> {
let res = match op {
'=' => (2, 1),
'?' => (4, 3),
'+' | '-' => (5, 6),
'*' | '/' => (7, 8),
'.' => (14, 13),
_ => return None,
};
Some(res)
}
#[test]
fn tests() {
let s = expr("1");
assert_eq!(s.to_string(), "1");
let s = expr("1 + 2 * 3");
assert_eq!(s.to_string(), "(+ 1 (* 2 3))");
let s = expr("a + b * c * d + e");
assert_eq!(s.to_string(), "(+ (+ a (* (* b c) d)) e)");
let s = expr("f. g. h");
assert_eq!(s.to_string(), "(. f (. g h))");
let s = expr(" 1 + 2 + f. g. h * 3 * 4");
assert_eq!(s.to_string(), "(+ (+ 1 2) (* (* (. f (. g h)) 3) 4))",);
let s = expr("--1 * 2");
assert_eq!(s.to_string(), "(* (- (- 1)) 2)");
let s = expr("--f. g");
assert_eq!(s.to_string(), "(- (- (. f g)))");
let s = expr("-9!");
assert_eq!(s.to_string(), "(- (! 9))");
let s = expr("f. g!");
assert_eq!(s.to_string(), "(! (. f g))");
let s = expr("(((0)))");
assert_eq!(s.to_string(), "0");
let s = expr("x[0][1]");
assert_eq!(s.to_string(), "([ ([ x 0) 1)");
let s = expr(
"a? b :
c? d
: e",
);
assert_eq!(s.to_string(), "(? a b (? c d e))");
let s = expr("a = 0? b : c = d");
assert_eq!(s.to_string(), "(= a (= (? 0 b c) d))");
let s = expr("a(b)");
assert_eq!(s.to_string(), "(invoke a b)");
let s = expr("a(b,c)");
assert_eq!(s.to_string(), "(invoke a b c)");
let s = expr("b = a(b,1 + 1)");
assert_eq!(s.to_string(), "(= b (invoke a b (+ 1 1)))");
}
| S | identifier_name |
pratparser.rs | enum S {
Atom(String),
Cons(String, Vec<S>),
}
impl std::fmt::Display for S {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
S::Atom(i) => write!(f, "{}", i),
S::Cons(head, rest) => {
write!(f, "({}", head)?;
for s in rest {
write!(f, " {}", s)?
}
write!(f, ")")
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token {
Atom(char),
Op(char),
Eof,
}
struct Lexer {
tokens: Vec<Token>,
}
impl Lexer {
fn new(input: &str) -> Lexer {
let mut tokens = input
.chars()
.filter(|it|!it.is_ascii_whitespace())
.map(|c| match c {
'0'..='9' | 'a'..='z' | 'A'..='Z' => Token::Atom(c),
_ => Token::Op(c),
})
.collect::<Vec<_>>();
tokens.reverse();
Lexer { tokens }
}
fn next(&mut self) -> Token {
self.tokens.pop().unwrap_or(Token::Eof)
}
fn peek(&mut self) -> Token {
self.tokens.last().copied().unwrap_or(Token::Eof)
}
}
fn expr(input: &str) -> S {
let mut lexer = Lexer::new(input);
expr_bp(&mut lexer, 0)
}
fn expr_bp(lexer: &mut Lexer, min_bp: u8) -> S {
let mut lhs = match lexer.next() {
Token::Atom(it) => S::Atom(it.to_string()),
Token::Op('(') => {
let lhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(')'));
lhs
}
Token::Op(op) => {
let ((), r_bp) = prefix_binding_power(op);
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![rhs])
}
t => panic!("bad token: {:?}", t),
};
loop {
let op = match lexer.peek() {
Token::Eof => break,
Token::Op(op) => op,
t => panic!("bad token: {:?}", t),
};
if let Some((l_bp, ())) = postfix_binding_power(op) {
if l_bp < min_bp {
break;
} | '[' => {
let rhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(']'));
S::Cons(op.to_string(), vec![lhs, rhs])
}
'(' => {
let mut args = vec![expr_bp(lexer, 0)];
while lexer.peek() == Token::Op(',') {
lexer.next();
let arg = expr_bp(lexer, 0);
args.push(arg);
}
assert_eq!(lexer.next(), Token::Op(')'));
let mut v = vec![lhs];
v.append(&mut args);
S::Cons("invoke".to_string(), v)
}
_ => S::Cons(op.to_string(), vec![lhs]),
};
continue;
}
if let Some((l_bp, r_bp)) = infix_binding_power(op) {
if l_bp < min_bp {
break;
}
lexer.next();
lhs = if op == '?' {
let mhs = expr_bp(lexer, 0);
assert_eq!(lexer.next(), Token::Op(':'));
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![lhs, mhs, rhs])
} else {
let rhs = expr_bp(lexer, r_bp);
S::Cons(op.to_string(), vec![lhs, rhs])
};
continue;
}
break;
}
lhs
}
fn prefix_binding_power(op: char) -> ((), u8) {
match op {
'+' | '-' => ((), 9),
_ => panic!("bad op: {:?}", op),
}
}
fn postfix_binding_power(op: char) -> Option<(u8, ())> {
let res = match op {
'!' => (11, ()),
'[' | '(' => (11, ()),
_ => return None,
};
Some(res)
}
fn infix_binding_power(op: char) -> Option<(u8, u8)> {
let res = match op {
'=' => (2, 1),
'?' => (4, 3),
'+' | '-' => (5, 6),
'*' | '/' => (7, 8),
'.' => (14, 13),
_ => return None,
};
Some(res)
}
#[test]
fn tests() {
let s = expr("1");
assert_eq!(s.to_string(), "1");
let s = expr("1 + 2 * 3");
assert_eq!(s.to_string(), "(+ 1 (* 2 3))");
let s = expr("a + b * c * d + e");
assert_eq!(s.to_string(), "(+ (+ a (* (* b c) d)) e)");
let s = expr("f. g. h");
assert_eq!(s.to_string(), "(. f (. g h))");
let s = expr(" 1 + 2 + f. g. h * 3 * 4");
assert_eq!(s.to_string(), "(+ (+ 1 2) (* (* (. f (. g h)) 3) 4))",);
let s = expr("--1 * 2");
assert_eq!(s.to_string(), "(* (- (- 1)) 2)");
let s = expr("--f. g");
assert_eq!(s.to_string(), "(- (- (. f g)))");
let s = expr("-9!");
assert_eq!(s.to_string(), "(- (! 9))");
let s = expr("f. g!");
assert_eq!(s.to_string(), "(! (. f g))");
let s = expr("(((0)))");
assert_eq!(s.to_string(), "0");
let s = expr("x[0][1]");
assert_eq!(s.to_string(), "([ ([ x 0) 1)");
let s = expr(
"a? b :
c? d
: e",
);
assert_eq!(s.to_string(), "(? a b (? c d e))");
let s = expr("a = 0? b : c = d");
assert_eq!(s.to_string(), "(= a (= (? 0 b c) d))");
let s = expr("a(b)");
assert_eq!(s.to_string(), "(invoke a b)");
let s = expr("a(b,c)");
assert_eq!(s.to_string(), "(invoke a b c)");
let s = expr("b = a(b,1 + 1)");
assert_eq!(s.to_string(), "(= b (invoke a b (+ 1 1)))");
} | lexer.next();
lhs = match op { | random_line_split |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::Element;
use dom::node::window_from_node;
use std::borrow::ToOwned;
use string_cache::Atom;
use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join};
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_ref(element),
local_name: local_name,
}
}
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> {
let window = window_from_node(element);
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
fn attribute(&self) -> Option<Root<Attr>> {
let element = self.element.root();
element.r().get_attribute(&ns!(""), &self.local_name)
}
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Error::Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// https://dom.spec.whatwg.org/#domtokenlist
impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(&self) -> u32 {
self.attribute().map(|attr| { | let attr = attr.r();
attr.value().as_tokens().len()
}).unwrap_or(0) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
let attr = attr.r();
Some(attr.value().as_tokens()).and_then(|tokens| {
tokens.get(index as usize).map(|token| (**token).to_owned())
})
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(&self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(&token).map(|token| {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value()
.as_tokens()
.iter()
.any(|atom: &Atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
atoms.iter().position(|atom| *atom == token).map(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(&token));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
} | random_line_split |
|
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::Element;
use dom::node::window_from_node;
use std::borrow::ToOwned;
use string_cache::Atom;
use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join};
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_ref(element),
local_name: local_name,
}
}
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> {
let window = window_from_node(element);
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
fn attribute(&self) -> Option<Root<Attr>> {
let element = self.element.root();
element.r().get_attribute(&ns!(""), &self.local_name)
}
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Error::Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// https://dom.spec.whatwg.org/#domtokenlist
impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(&self) -> u32 {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value().as_tokens().len()
}).unwrap_or(0) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
let attr = attr.r();
Some(attr.value().as_tokens()).and_then(|tokens| {
tokens.get(index as usize).map(|token| (**token).to_owned())
})
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(&self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(&token).map(|token| {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value()
.as_tokens()
.iter()
.any(|atom: &Atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
if!atoms.iter().any(|atom| *atom == token) |
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
atoms.iter().position(|atom| *atom == token).map(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(&token));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
}
| {
atoms.push(token);
} | conditional_block |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::Element;
use dom::node::window_from_node;
use std::borrow::ToOwned;
use string_cache::Atom;
use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join};
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList |
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> {
let window = window_from_node(element);
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
fn attribute(&self) -> Option<Root<Attr>> {
let element = self.element.root();
element.r().get_attribute(&ns!(""), &self.local_name)
}
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Error::Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// https://dom.spec.whatwg.org/#domtokenlist
impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(&self) -> u32 {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value().as_tokens().len()
}).unwrap_or(0) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
let attr = attr.r();
Some(attr.value().as_tokens()).and_then(|tokens| {
tokens.get(index as usize).map(|token| (**token).to_owned())
})
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(&self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(&token).map(|token| {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value()
.as_tokens()
.iter()
.any(|atom: &Atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
atoms.iter().position(|atom| *atom == token).map(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(&token));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
}
| {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_ref(element),
local_name: local_name,
}
} | identifier_body |
domtokenlist.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::Element;
use dom::node::window_from_node;
use std::borrow::ToOwned;
use string_cache::Atom;
use util::str::{DOMString, HTML_SPACE_CHARACTERS, str_join};
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_ref(element),
local_name: local_name,
}
}
pub fn new(element: &Element, local_name: &Atom) -> Root<DOMTokenList> {
let window = window_from_node(element);
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
fn attribute(&self) -> Option<Root<Attr>> {
let element = self.element.root();
element.r().get_attribute(&ns!(""), &self.local_name)
}
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Error::Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// https://dom.spec.whatwg.org/#domtokenlist
impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-length
fn | (&self) -> u32 {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value().as_tokens().len()
}).unwrap_or(0) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
let attr = attr.r();
Some(attr.value().as_tokens()).and_then(|tokens| {
tokens.get(index as usize).map(|token| (**token).to_owned())
})
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(&self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(&token).map(|token| {
self.attribute().map(|attr| {
let attr = attr.r();
attr.value()
.as_tokens()
.iter()
.any(|atom: &Atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = try!(self.check_token_exceptions(&token));
atoms.iter().position(|atom| *atom == token).map(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(&token));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
// https://dom.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
let tokenlist = self.element.root().r().get_tokenlist_attribute(&self.local_name);
str_join(&tokenlist, "\x20")
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
}
| Length | identifier_name |
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of PushCommand
pub fn new() -> PushCommand |
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn execute(&self, river: &str, message: &str) {
River::new(river).push(message);
}
}
/// Peek command - stateless
///
/// Used to peek messages from rivers like this:
///
/// ```
/// // read latest message from river
/// john::PushCommand::new().execute("river name", "a message");
/// john::PushCommand::new().execute("river name", "a message 1");
/// john::PushCommand::new().execute("river name", "a message 2");
/// john::PushCommand::new().execute("river name", "a message 3");
/// john::PeekCommand::new().execute("river name", None);
///
/// // read message from river at specific offset
/// john::PeekCommand::new().execute("river name", Some(2));
/// ```
///
/// It returns Option < PeekResult >. When it was able to peek a message, the result will contain
/// peeked message and new offset to specify to peek command (if you want to get next message)
pub struct PeekCommand;
impl PeekCommand {
/// Constructor ::new()
///
/// Creates new instance of PeekCommand
pub fn new() -> PeekCommand {
PeekCommand
}
/// Used to execute peek command, specifying a river name and optionally offset to peek at
pub fn execute(&self, river: &str, offset: Option < uint >) -> Option < PeekResult > {
River::new(river).peek_at(offset)
}
}
/// Clear command - stateless
///
/// Used to clear messages from rivers like this:
///
/// ```
/// john::ClearCommand::new().execute("river_name");
/// ```
pub struct ClearCommand;
impl ClearCommand {
/// Constructor ::new()
///
/// Creates new instance of ClearCommand
pub fn new() -> ClearCommand {
ClearCommand
}
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn execute(&self, river: &str) {
River::new(river).destroy();
}
}
| {
PushCommand
} | identifier_body |
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of PushCommand
pub fn new() -> PushCommand {
PushCommand
}
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn execute(&self, river: &str, message: &str) {
River::new(river).push(message);
}
}
/// Peek command - stateless
///
/// Used to peek messages from rivers like this:
///
/// ```
/// // read latest message from river
/// john::PushCommand::new().execute("river name", "a message");
/// john::PushCommand::new().execute("river name", "a message 1");
/// john::PushCommand::new().execute("river name", "a message 2");
/// john::PushCommand::new().execute("river name", "a message 3");
/// john::PeekCommand::new().execute("river name", None);
///
/// // read message from river at specific offset
/// john::PeekCommand::new().execute("river name", Some(2));
/// ```
///
/// It returns Option < PeekResult >. When it was able to peek a message, the result will contain
/// peeked message and new offset to specify to peek command (if you want to get next message)
pub struct PeekCommand;
impl PeekCommand {
/// Constructor ::new()
///
/// Creates new instance of PeekCommand
pub fn new() -> PeekCommand {
PeekCommand
}
/// Used to execute peek command, specifying a river name and optionally offset to peek at
pub fn execute(&self, river: &str, offset: Option < uint >) -> Option < PeekResult > {
River::new(river).peek_at(offset)
}
}
/// Clear command - stateless
///
/// Used to clear messages from rivers like this:
///
/// ```
/// john::ClearCommand::new().execute("river_name");
/// ```
pub struct ClearCommand;
impl ClearCommand {
/// Constructor ::new()
///
/// Creates new instance of ClearCommand
pub fn new() -> ClearCommand {
ClearCommand
}
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless | pub fn execute(&self, river: &str) {
River::new(river).destroy();
}
} | random_line_split |
|
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of PushCommand
pub fn new() -> PushCommand {
PushCommand
}
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn execute(&self, river: &str, message: &str) {
River::new(river).push(message);
}
}
/// Peek command - stateless
///
/// Used to peek messages from rivers like this:
///
/// ```
/// // read latest message from river
/// john::PushCommand::new().execute("river name", "a message");
/// john::PushCommand::new().execute("river name", "a message 1");
/// john::PushCommand::new().execute("river name", "a message 2");
/// john::PushCommand::new().execute("river name", "a message 3");
/// john::PeekCommand::new().execute("river name", None);
///
/// // read message from river at specific offset
/// john::PeekCommand::new().execute("river name", Some(2));
/// ```
///
/// It returns Option < PeekResult >. When it was able to peek a message, the result will contain
/// peeked message and new offset to specify to peek command (if you want to get next message)
pub struct PeekCommand;
impl PeekCommand {
/// Constructor ::new()
///
/// Creates new instance of PeekCommand
pub fn new() -> PeekCommand {
PeekCommand
}
/// Used to execute peek command, specifying a river name and optionally offset to peek at
pub fn execute(&self, river: &str, offset: Option < uint >) -> Option < PeekResult > {
River::new(river).peek_at(offset)
}
}
/// Clear command - stateless
///
/// Used to clear messages from rivers like this:
///
/// ```
/// john::ClearCommand::new().execute("river_name");
/// ```
pub struct ClearCommand;
impl ClearCommand {
/// Constructor ::new()
///
/// Creates new instance of ClearCommand
pub fn new() -> ClearCommand {
ClearCommand
}
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn | (&self, river: &str) {
River::new(river).destroy();
}
}
| execute | identifier_name |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self {
List::Empty
}
pub fn head(&self) -> Option<&T> {
match self {
&List::Empty => None,
&List::Cons(ref head, _) => Some(&head)
}
}
pub fn tail(self) -> Self {
match self {
List::Empty => self,
List::Cons(_, tail) => *tail
}
}
}
impl <T> Add<T> for List<T> {
type Output = Self;
fn add(self, item: T) -> Self::Output {
List::Cons(item, Box::new(self))
}
}
impl <T> Add<List<T>> for List<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
match self {
List::Empty => other,
List::Cons(head, tail) => (*tail + other) + head
}
}
}
impl <T> FromIterator<T> for List<T> {
fn from_iter<I: IntoIterator<Item=T>>(items: I) -> Self {
let mut list = List::empty();
for item in items {
list = list + item
}
list
}
}
impl <T: ToString> fmt::Debug for List<T> {
fn | (&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.to_string())
}
}
impl <T: ToString> ToString for List<T> {
fn to_string(&self) -> String {
fn internal<E: ToString>(list: &List<E>) -> String {
match list {
&List::Empty => "".to_owned(),
&List::Cons(ref head, ref tail) => ", ".to_owned() + head.to_string().as_str() + internal(&*tail).as_str()
}
}
match self {
&List::Empty => "[]".to_owned(),
&List::Cons(ref head, ref tail) => "[".to_owned() + head.to_string().as_str() + internal(&*tail).as_str() + "]"
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.to_string(), "[]");
}
#[test]
fn prepend_items_to_list() {
let list = List::empty() + 1 + 2 + 3;
assert_eq!(list.to_string(), "[3, 2, 1]");
}
#[test]
fn head_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.head(), None);
}
#[test]
fn head_of_nonempty_list() {
let list = List::from_iter(vec![1, 2, 3]);
assert_eq!(list.head(), Some(&3));
}
#[test]
fn tail_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.tail(), List::empty());
}
#[test]
fn tail_of_nonempty_list() {
assert_eq!(List::from_iter(vec![1, 2, 3]).tail(), List::from_iter(vec![1, 2]));
}
#[test]
fn concatenation_of_two_empty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::empty(), List::empty());
}
#[test]
fn concatenation_of_empty_and_nonempty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3]));
assert_eq!(List::from_iter(vec![1, 2, 3]) + List::empty(), List::from_iter(vec![1, 2, 3]));
}
#[test]
fn concatenation_of_two_nonempty_lists() {
assert_eq!(List::from_iter(vec![4, 5, 6]) + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3, 4, 5, 6]));
}
}
| fmt | identifier_name |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self |
pub fn head(&self) -> Option<&T> {
match self {
&List::Empty => None,
&List::Cons(ref head, _) => Some(&head)
}
}
pub fn tail(self) -> Self {
match self {
List::Empty => self,
List::Cons(_, tail) => *tail
}
}
}
impl <T> Add<T> for List<T> {
type Output = Self;
fn add(self, item: T) -> Self::Output {
List::Cons(item, Box::new(self))
}
}
impl <T> Add<List<T>> for List<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
match self {
List::Empty => other,
List::Cons(head, tail) => (*tail + other) + head
}
}
}
impl <T> FromIterator<T> for List<T> {
fn from_iter<I: IntoIterator<Item=T>>(items: I) -> Self {
let mut list = List::empty();
for item in items {
list = list + item
}
list
}
}
impl <T: ToString> fmt::Debug for List<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.to_string())
}
}
impl <T: ToString> ToString for List<T> {
fn to_string(&self) -> String {
fn internal<E: ToString>(list: &List<E>) -> String {
match list {
&List::Empty => "".to_owned(),
&List::Cons(ref head, ref tail) => ", ".to_owned() + head.to_string().as_str() + internal(&*tail).as_str()
}
}
match self {
&List::Empty => "[]".to_owned(),
&List::Cons(ref head, ref tail) => "[".to_owned() + head.to_string().as_str() + internal(&*tail).as_str() + "]"
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.to_string(), "[]");
}
#[test]
fn prepend_items_to_list() {
let list = List::empty() + 1 + 2 + 3;
assert_eq!(list.to_string(), "[3, 2, 1]");
}
#[test]
fn head_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.head(), None);
}
#[test]
fn head_of_nonempty_list() {
let list = List::from_iter(vec![1, 2, 3]);
assert_eq!(list.head(), Some(&3));
}
#[test]
fn tail_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.tail(), List::empty());
}
#[test]
fn tail_of_nonempty_list() {
assert_eq!(List::from_iter(vec![1, 2, 3]).tail(), List::from_iter(vec![1, 2]));
}
#[test]
fn concatenation_of_two_empty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::empty(), List::empty());
}
#[test]
fn concatenation_of_empty_and_nonempty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3]));
assert_eq!(List::from_iter(vec![1, 2, 3]) + List::empty(), List::from_iter(vec![1, 2, 3]));
}
#[test]
fn concatenation_of_two_nonempty_lists() {
assert_eq!(List::from_iter(vec![4, 5, 6]) + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3, 4, 5, 6]));
}
}
| {
List::Empty
} | identifier_body |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self {
List::Empty
}
| match self {
&List::Empty => None,
&List::Cons(ref head, _) => Some(&head)
}
}
pub fn tail(self) -> Self {
match self {
List::Empty => self,
List::Cons(_, tail) => *tail
}
}
}
impl <T> Add<T> for List<T> {
type Output = Self;
fn add(self, item: T) -> Self::Output {
List::Cons(item, Box::new(self))
}
}
impl <T> Add<List<T>> for List<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
match self {
List::Empty => other,
List::Cons(head, tail) => (*tail + other) + head
}
}
}
impl <T> FromIterator<T> for List<T> {
fn from_iter<I: IntoIterator<Item=T>>(items: I) -> Self {
let mut list = List::empty();
for item in items {
list = list + item
}
list
}
}
impl <T: ToString> fmt::Debug for List<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.to_string())
}
}
impl <T: ToString> ToString for List<T> {
fn to_string(&self) -> String {
fn internal<E: ToString>(list: &List<E>) -> String {
match list {
&List::Empty => "".to_owned(),
&List::Cons(ref head, ref tail) => ", ".to_owned() + head.to_string().as_str() + internal(&*tail).as_str()
}
}
match self {
&List::Empty => "[]".to_owned(),
&List::Cons(ref head, ref tail) => "[".to_owned() + head.to_string().as_str() + internal(&*tail).as_str() + "]"
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.to_string(), "[]");
}
#[test]
fn prepend_items_to_list() {
let list = List::empty() + 1 + 2 + 3;
assert_eq!(list.to_string(), "[3, 2, 1]");
}
#[test]
fn head_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.head(), None);
}
#[test]
fn head_of_nonempty_list() {
let list = List::from_iter(vec![1, 2, 3]);
assert_eq!(list.head(), Some(&3));
}
#[test]
fn tail_of_empty_list() {
let empty: List<i32> = List::empty();
assert_eq!(empty.tail(), List::empty());
}
#[test]
fn tail_of_nonempty_list() {
assert_eq!(List::from_iter(vec![1, 2, 3]).tail(), List::from_iter(vec![1, 2]));
}
#[test]
fn concatenation_of_two_empty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::empty(), List::empty());
}
#[test]
fn concatenation_of_empty_and_nonempty_lists() {
let empty: List<i32> = List::empty();
assert_eq!(empty + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3]));
assert_eq!(List::from_iter(vec![1, 2, 3]) + List::empty(), List::from_iter(vec![1, 2, 3]));
}
#[test]
fn concatenation_of_two_nonempty_lists() {
assert_eq!(List::from_iter(vec![4, 5, 6]) + List::from_iter(vec![1, 2, 3]), List::from_iter(vec![1, 2, 3, 4, 5, 6]));
}
} | pub fn head(&self) -> Option<&T> { | random_line_split |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use darwin_rs::{Individual, SimulationBuilder, Population, PopulationBuilder, simulation_builder};
#[derive(Debug, Clone)]
struct Queens {
board: Vec<u8>,
}
// Chech one straight line in one specific direction
fn one_trace(board: &[u8], row: usize, col: usize, dy: i8, dx: i8) -> u8 {
let mut num_of_collisions = 0;
let mut x: i16 = col as i16;
let mut y: i16 = row as i16;
loop {
x += dx as i16;
if (x < 0) || (x > 7) {
break;
}
y += dy as i16;
if (y < 0) || (y > 7) {
break;
}
if board[((y * 8) + x) as usize] == 1 {
num_of_collisions += 1;
}
}
num_of_collisions
}
// Check all eight directions:
fn find_collisions(board: &[u8], row: usize, col: usize) -> u8 {
let mut num_of_collisions = 0;
// up
num_of_collisions += one_trace(board, row, col, -1, 0);
// up right
num_of_collisions += one_trace(board, row, col, -1, 1);
// right
num_of_collisions += one_trace(board, row, col, 0, 1);
// right down
num_of_collisions += one_trace(board, row, col, 1, 1);
// down
num_of_collisions += one_trace(board, row, col, 1, 0);
// down left
num_of_collisions += one_trace(board, row, col, 1, -1);
// left
num_of_collisions += one_trace(board, row, col, 0, -1);
// left top
num_of_collisions += one_trace(board, row, col, -1, -1);
num_of_collisions
}
fn make_population(count: u32) -> Vec<Queens> {
let mut result = Vec::new();
for _ in 0..count {
result.push(
Queens {
// Start with all queens in one row
board: vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
]
}
);
}
result
}
fn make_all_populations(individuals: u32, populations: u32) -> Vec<Population<Queens>> {
let mut result = Vec::new();
let initial_population = make_population(individuals);
for i in 1..(populations + 1) {
let pop = PopulationBuilder::<Queens>::new()
.set_id(i)
.initial_population(&initial_population)
.mutation_rate((1..10).cycle().take(individuals as usize).collect())
.reset_limit_end(0) // disable the resetting of all individuals
.finalize().unwrap();
result.push(pop);
}
result
}
// implement trait functions mutate and calculate_fitness:
impl Individual for Queens {
fn mutate(&mut self) {
let mut rng = rand::thread_rng();
let mut index1: usize = rng.gen_range(0, self.board.len());
let mut index2: usize = rng.gen_range(0, self.board.len());
// Pick a position where a queen is placed.
// Try random position until it finds a queen
while self.board[index1]!= 1 {
index1 = rng.gen_range(0, self.board.len());
}
// Pick a position where no queen is placed and this index is different from the other
while (index1 == index2) && (self.board[index2]!= 0) {
index2 = rng.gen_range(0, self.board.len());
}
// Move queen onto an empty position
self.board.swap(index1, index2);
}
// fitness means here: how many queens are colliding
fn calculate_fitness(&mut self) -> f64 {
let mut num_of_collisions = 0;
for row in 0..8 {
for col in 0..8 {
// Found a queen, so check for collisions
if self.board[(row * 8) + col] == 1 {
num_of_collisions += find_collisions(&self.board, row, col);
}
}
}
num_of_collisions as f64
}
fn reset(&mut self) {
self.board = vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
];
}
}
fn | () {
println!("Darwin test: queens problem");
let _ = SimpleLogger::init(LogLevelFilter::Info, Config::default());
let queens = SimulationBuilder::<Queens>::new()
.fitness(0.0)
.threads(2)
.add_multiple_populations(make_all_populations(100, 8))
.finalize();
match queens {
Err(simulation_builder::Error(simulation_builder::ErrorKind::EndIterationTooLow, _)) => println!("more than 10 iteratons needed"),
Err(e) => println!("unexpected error: {}", e),
Ok(mut queens_simulation) => {
queens_simulation.run();
// A fitness of zero means a solution was found.
queens_simulation.print_fitness();
// print solution
for row in 0..8 {
for col in 0..8 {
print!("{} | ",
queens_simulation.simulation_result.fittest[0].individual.board[(row * 8) + col]);
}
println!("\n");
}
println!("total run time: {} ms", queens_simulation.total_time_in_ms);
println!("improvement factor: {}",
queens_simulation.simulation_result.improvement_factor);
println!("number of iterations: {}",
queens_simulation.simulation_result.iteration_counter);
}
}
}
| main | identifier_name |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use darwin_rs::{Individual, SimulationBuilder, Population, PopulationBuilder, simulation_builder};
#[derive(Debug, Clone)]
struct Queens {
board: Vec<u8>,
}
// Chech one straight line in one specific direction
fn one_trace(board: &[u8], row: usize, col: usize, dy: i8, dx: i8) -> u8 {
let mut num_of_collisions = 0;
let mut x: i16 = col as i16;
let mut y: i16 = row as i16;
loop {
x += dx as i16;
if (x < 0) || (x > 7) {
break;
}
y += dy as i16;
if (y < 0) || (y > 7) {
break;
}
if board[((y * 8) + x) as usize] == 1 {
num_of_collisions += 1;
}
}
num_of_collisions
}
// Check all eight directions:
fn find_collisions(board: &[u8], row: usize, col: usize) -> u8 |
// left
num_of_collisions += one_trace(board, row, col, 0, -1);
// left top
num_of_collisions += one_trace(board, row, col, -1, -1);
num_of_collisions
}
fn make_population(count: u32) -> Vec<Queens> {
let mut result = Vec::new();
for _ in 0..count {
result.push(
Queens {
// Start with all queens in one row
board: vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
]
}
);
}
result
}
fn make_all_populations(individuals: u32, populations: u32) -> Vec<Population<Queens>> {
let mut result = Vec::new();
let initial_population = make_population(individuals);
for i in 1..(populations + 1) {
let pop = PopulationBuilder::<Queens>::new()
.set_id(i)
.initial_population(&initial_population)
.mutation_rate((1..10).cycle().take(individuals as usize).collect())
.reset_limit_end(0) // disable the resetting of all individuals
.finalize().unwrap();
result.push(pop);
}
result
}
// implement trait functions mutate and calculate_fitness:
impl Individual for Queens {
fn mutate(&mut self) {
let mut rng = rand::thread_rng();
let mut index1: usize = rng.gen_range(0, self.board.len());
let mut index2: usize = rng.gen_range(0, self.board.len());
// Pick a position where a queen is placed.
// Try random position until it finds a queen
while self.board[index1]!= 1 {
index1 = rng.gen_range(0, self.board.len());
}
// Pick a position where no queen is placed and this index is different from the other
while (index1 == index2) && (self.board[index2]!= 0) {
index2 = rng.gen_range(0, self.board.len());
}
// Move queen onto an empty position
self.board.swap(index1, index2);
}
// fitness means here: how many queens are colliding
fn calculate_fitness(&mut self) -> f64 {
let mut num_of_collisions = 0;
for row in 0..8 {
for col in 0..8 {
// Found a queen, so check for collisions
if self.board[(row * 8) + col] == 1 {
num_of_collisions += find_collisions(&self.board, row, col);
}
}
}
num_of_collisions as f64
}
fn reset(&mut self) {
self.board = vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
];
}
}
fn main() {
println!("Darwin test: queens problem");
let _ = SimpleLogger::init(LogLevelFilter::Info, Config::default());
let queens = SimulationBuilder::<Queens>::new()
.fitness(0.0)
.threads(2)
.add_multiple_populations(make_all_populations(100, 8))
.finalize();
match queens {
Err(simulation_builder::Error(simulation_builder::ErrorKind::EndIterationTooLow, _)) => println!("more than 10 iteratons needed"),
Err(e) => println!("unexpected error: {}", e),
Ok(mut queens_simulation) => {
queens_simulation.run();
// A fitness of zero means a solution was found.
queens_simulation.print_fitness();
// print solution
for row in 0..8 {
for col in 0..8 {
print!("{} | ",
queens_simulation.simulation_result.fittest[0].individual.board[(row * 8) + col]);
}
println!("\n");
}
println!("total run time: {} ms", queens_simulation.total_time_in_ms);
println!("improvement factor: {}",
queens_simulation.simulation_result.improvement_factor);
println!("number of iterations: {}",
queens_simulation.simulation_result.iteration_counter);
}
}
}
| {
let mut num_of_collisions = 0;
// up
num_of_collisions += one_trace(board, row, col, -1, 0);
// up right
num_of_collisions += one_trace(board, row, col, -1, 1);
// right
num_of_collisions += one_trace(board, row, col, 0, 1);
// right down
num_of_collisions += one_trace(board, row, col, 1, 1);
// down
num_of_collisions += one_trace(board, row, col, 1, 0);
// down left
num_of_collisions += one_trace(board, row, col, 1, -1); | identifier_body |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use darwin_rs::{Individual, SimulationBuilder, Population, PopulationBuilder, simulation_builder};
#[derive(Debug, Clone)]
struct Queens {
board: Vec<u8>,
}
// Chech one straight line in one specific direction
fn one_trace(board: &[u8], row: usize, col: usize, dy: i8, dx: i8) -> u8 {
let mut num_of_collisions = 0;
let mut x: i16 = col as i16;
let mut y: i16 = row as i16;
loop {
x += dx as i16;
if (x < 0) || (x > 7) {
break;
}
y += dy as i16;
if (y < 0) || (y > 7) {
break;
}
if board[((y * 8) + x) as usize] == 1 {
num_of_collisions += 1;
}
}
num_of_collisions
}
// Check all eight directions:
fn find_collisions(board: &[u8], row: usize, col: usize) -> u8 {
let mut num_of_collisions = 0;
// up
num_of_collisions += one_trace(board, row, col, -1, 0);
// up right
num_of_collisions += one_trace(board, row, col, -1, 1);
// right
num_of_collisions += one_trace(board, row, col, 0, 1);
// right down
num_of_collisions += one_trace(board, row, col, 1, 1);
// down
num_of_collisions += one_trace(board, row, col, 1, 0);
// down left
num_of_collisions += one_trace(board, row, col, 1, -1);
// left
num_of_collisions += one_trace(board, row, col, 0, -1);
// left top
num_of_collisions += one_trace(board, row, col, -1, -1);
num_of_collisions
}
fn make_population(count: u32) -> Vec<Queens> {
let mut result = Vec::new();
for _ in 0..count {
result.push(
Queens {
// Start with all queens in one row
board: vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
]
}
);
}
result
}
fn make_all_populations(individuals: u32, populations: u32) -> Vec<Population<Queens>> {
let mut result = Vec::new();
let initial_population = make_population(individuals);
for i in 1..(populations + 1) {
let pop = PopulationBuilder::<Queens>::new()
.set_id(i)
.initial_population(&initial_population)
.mutation_rate((1..10).cycle().take(individuals as usize).collect())
.reset_limit_end(0) // disable the resetting of all individuals | .finalize().unwrap();
result.push(pop);
}
result
}
// implement trait functions mutate and calculate_fitness:
impl Individual for Queens {
fn mutate(&mut self) {
let mut rng = rand::thread_rng();
let mut index1: usize = rng.gen_range(0, self.board.len());
let mut index2: usize = rng.gen_range(0, self.board.len());
// Pick a position where a queen is placed.
// Try random position until it finds a queen
while self.board[index1]!= 1 {
index1 = rng.gen_range(0, self.board.len());
}
// Pick a position where no queen is placed and this index is different from the other
while (index1 == index2) && (self.board[index2]!= 0) {
index2 = rng.gen_range(0, self.board.len());
}
// Move queen onto an empty position
self.board.swap(index1, index2);
}
// fitness means here: how many queens are colliding
fn calculate_fitness(&mut self) -> f64 {
let mut num_of_collisions = 0;
for row in 0..8 {
for col in 0..8 {
// Found a queen, so check for collisions
if self.board[(row * 8) + col] == 1 {
num_of_collisions += find_collisions(&self.board, row, col);
}
}
}
num_of_collisions as f64
}
fn reset(&mut self) {
self.board = vec![
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
];
}
}
fn main() {
println!("Darwin test: queens problem");
let _ = SimpleLogger::init(LogLevelFilter::Info, Config::default());
let queens = SimulationBuilder::<Queens>::new()
.fitness(0.0)
.threads(2)
.add_multiple_populations(make_all_populations(100, 8))
.finalize();
match queens {
Err(simulation_builder::Error(simulation_builder::ErrorKind::EndIterationTooLow, _)) => println!("more than 10 iteratons needed"),
Err(e) => println!("unexpected error: {}", e),
Ok(mut queens_simulation) => {
queens_simulation.run();
// A fitness of zero means a solution was found.
queens_simulation.print_fitness();
// print solution
for row in 0..8 {
for col in 0..8 {
print!("{} | ",
queens_simulation.simulation_result.fittest[0].individual.board[(row * 8) + col]);
}
println!("\n");
}
println!("total run time: {} ms", queens_simulation.total_time_in_ms);
println!("improvement factor: {}",
queens_simulation.simulation_result.improvement_factor);
println!("number of iterations: {}",
queens_simulation.simulation_result.iteration_counter);
}
}
} | random_line_split |
|
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Texture {
/// Sample the textured value at texture coordinates u,v
/// at some time. u and v should be in [0, 1]
fn sample_f32(&self, u: f32, v: f32, time: f32) -> f32;
fn sample_color(&self, u: f32, v: f32, time: f32) -> Colorf;
}
fn bilinear_interpolate<T, F>(x: f32, y: f32, get: F) -> T
where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>,
F: Fn(u32, u32) -> T
{
let p00 = (x as u32, y as u32);
let p10 = (p00.0 + 1, p00.1);
let p01 = (p00.0, p00.1 + 1);
let p11 = (p00.0 + 1, p00.1 + 1);
let s00 = get(p00.0, p00.1);
let s10 = get(p10.0, p10.1);
let s01 = get(p01.0, p01.1);
let s11 = get(p11.0, p11.1);
let sx = x - p00.0 as f32;
let sy = y - p00.1 as f32;
s00 * (1.0 - sx) * (1.0 - sy) + s10 * sx * (1.0 - sy)
+ s01 * (1.0 - sx) * sy + s11 * sx * sy
}
/// A single valued, solid scalar texture
pub struct ConstantScalar {
val: f32,
}
impl ConstantScalar {
pub fn new(val: f32) -> ConstantScalar {
ConstantScalar { val: val }
}
}
impl Texture for ConstantScalar {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
Colorf::broadcast(self.val)
}
}
/// A single valued, solid color texture
pub struct ConstantColor {
val: Colorf,
} | impl ConstantColor {
pub fn new(val: Colorf) -> ConstantColor {
ConstantColor { val: val }
}
}
impl Texture for ConstantColor {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val.luminance()
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
self.val
}
}
pub struct UVColor;
impl Texture for UVColor {
fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 {
Colorf::new(u, v, 0.0).luminance()
}
fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf {
Colorf::new(u, v, 0.0)
}
} | random_line_split |
|
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Texture {
/// Sample the textured value at texture coordinates u,v
/// at some time. u and v should be in [0, 1]
fn sample_f32(&self, u: f32, v: f32, time: f32) -> f32;
fn sample_color(&self, u: f32, v: f32, time: f32) -> Colorf;
}
fn | <T, F>(x: f32, y: f32, get: F) -> T
where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>,
F: Fn(u32, u32) -> T
{
let p00 = (x as u32, y as u32);
let p10 = (p00.0 + 1, p00.1);
let p01 = (p00.0, p00.1 + 1);
let p11 = (p00.0 + 1, p00.1 + 1);
let s00 = get(p00.0, p00.1);
let s10 = get(p10.0, p10.1);
let s01 = get(p01.0, p01.1);
let s11 = get(p11.0, p11.1);
let sx = x - p00.0 as f32;
let sy = y - p00.1 as f32;
s00 * (1.0 - sx) * (1.0 - sy) + s10 * sx * (1.0 - sy)
+ s01 * (1.0 - sx) * sy + s11 * sx * sy
}
/// A single valued, solid scalar texture
pub struct ConstantScalar {
val: f32,
}
impl ConstantScalar {
pub fn new(val: f32) -> ConstantScalar {
ConstantScalar { val: val }
}
}
impl Texture for ConstantScalar {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
Colorf::broadcast(self.val)
}
}
/// A single valued, solid color texture
pub struct ConstantColor {
val: Colorf,
}
impl ConstantColor {
pub fn new(val: Colorf) -> ConstantColor {
ConstantColor { val: val }
}
}
impl Texture for ConstantColor {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val.luminance()
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
self.val
}
}
pub struct UVColor;
impl Texture for UVColor {
fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 {
Colorf::new(u, v, 0.0).luminance()
}
fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf {
Colorf::new(u, v, 0.0)
}
}
| bilinear_interpolate | identifier_name |
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Texture {
/// Sample the textured value at texture coordinates u,v
/// at some time. u and v should be in [0, 1]
fn sample_f32(&self, u: f32, v: f32, time: f32) -> f32;
fn sample_color(&self, u: f32, v: f32, time: f32) -> Colorf;
}
fn bilinear_interpolate<T, F>(x: f32, y: f32, get: F) -> T
where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>,
F: Fn(u32, u32) -> T
{
let p00 = (x as u32, y as u32);
let p10 = (p00.0 + 1, p00.1);
let p01 = (p00.0, p00.1 + 1);
let p11 = (p00.0 + 1, p00.1 + 1);
let s00 = get(p00.0, p00.1);
let s10 = get(p10.0, p10.1);
let s01 = get(p01.0, p01.1);
let s11 = get(p11.0, p11.1);
let sx = x - p00.0 as f32;
let sy = y - p00.1 as f32;
s00 * (1.0 - sx) * (1.0 - sy) + s10 * sx * (1.0 - sy)
+ s01 * (1.0 - sx) * sy + s11 * sx * sy
}
/// A single valued, solid scalar texture
pub struct ConstantScalar {
val: f32,
}
impl ConstantScalar {
pub fn new(val: f32) -> ConstantScalar {
ConstantScalar { val: val }
}
}
impl Texture for ConstantScalar {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
Colorf::broadcast(self.val)
}
}
/// A single valued, solid color texture
pub struct ConstantColor {
val: Colorf,
}
impl ConstantColor {
pub fn new(val: Colorf) -> ConstantColor {
ConstantColor { val: val }
}
}
impl Texture for ConstantColor {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val.luminance()
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf |
}
pub struct UVColor;
impl Texture for UVColor {
fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 {
Colorf::new(u, v, 0.0).luminance()
}
fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf {
Colorf::new(u, v, 0.0)
}
}
| {
self.val
} | identifier_body |
packet.rs | use std::io;
use byteorder::{ReadBytesExt, WriteBytesExt};
use protocol::raknet::packet::Packet;
use protocol::raknet::types;
use protocol::raknet::{NetworkSerializable, NetworkDeserializable, NetworkSize};
macro_rules! define_mcpe_packets {
($(($id:expr, $name:ident) => {$($field_name:ident: $field_type:ty),*}),+) => (
#[derive(Debug)]
pub enum PacketTypes {
$($name($name)),+
}
impl PacketTypes {
pub fn packet_id(&self) -> u8 {
match self {
$(&PacketTypes::$name(ref packet) => packet.packet_id()),+
}
}
}
impl NetworkSerializable for PacketTypes {
fn write_serialize(&self, stream: &mut io::Write) -> io::Result<()> {
Ok(match self {
$(&PacketTypes::$name(ref packet) => {
stream.write_u8(packet.packet_id())?;
packet.write_serialize(stream)?;
},)+
})
}
}
impl NetworkDeserializable for PacketTypes {
fn read_deserialize(stream: &mut io::Read) -> io::Result<Self> {
Ok(match stream.read_u8()? {
$($id => PacketTypes::$name($name::read_deserialize(stream)?),)+
_ => return Err(io::Error::new(io::ErrorKind::InvalidData,
"Unidentified MCPE packet"))
})
}
}
$(
define_network_struct!($name => {$($field_name: $field_type),*});
impl Packet for $name { | }
impl Into<PacketTypes> for $name {
fn into(self) -> PacketTypes {
PacketTypes::$name(self)
}
}
)+
)
}
define_mcpe_packets!(
(0x01, Login) => {
protocol: u32,
edition: u8
}
); |
fn packet_id(&self) -> u8 {
$id as u8
} | random_line_split |
namespaced-enum-emulate-flat.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.
#![feature(globs)]
pub use Foo::*;
use nest::{Bar, D, E, F};
pub enum Foo {
A,
B(int),
C { a: int },
}
impl Foo {
pub fn foo() {}
}
| A | B(_) | C {.. } => {}
}
}
mod nest {
pub use self::Bar::*;
pub enum Bar {
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
fn _f2(f: Bar) {
match f {
D | E(_) | F {.. } => {}
}
}
fn main() {} | fn _f(f: Foo) {
match f { | random_line_split |
namespaced-enum-emulate-flat.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.
#![feature(globs)]
pub use Foo::*;
use nest::{Bar, D, E, F};
pub enum Foo {
A,
B(int),
C { a: int },
}
impl Foo {
pub fn foo() {}
}
fn _f(f: Foo) {
match f {
A | B(_) | C {.. } => {}
}
}
mod nest {
pub use self::Bar::*;
pub enum Bar {
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
fn _f2(f: Bar) {
match f {
D | E(_) | F {.. } => |
}
}
fn main() {}
| {} | conditional_block |
namespaced-enum-emulate-flat.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.
#![feature(globs)]
pub use Foo::*;
use nest::{Bar, D, E, F};
pub enum Foo {
A,
B(int),
C { a: int },
}
impl Foo {
pub fn foo() {}
}
fn _f(f: Foo) {
match f {
A | B(_) | C {.. } => {}
}
}
mod nest {
pub use self::Bar::*;
pub enum | {
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
fn _f2(f: Bar) {
match f {
D | E(_) | F {.. } => {}
}
}
fn main() {}
| Bar | identifier_name |
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, TransactionId};
/// The content of an `m.key.verification.request` event.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.key.verification.request", kind = ToDevice)]
pub struct ToDeviceKeyVerificationRequestEventContent {
/// The device ID which is initiating the request.
pub from_device: Box<DeviceId>,
/// An opaque identifier for the verification request.
///
/// Must be unique with respect to the devices involved.
pub transaction_id: Box<TransactionId>,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The time in milliseconds for when the request was made.
///
/// If the request is in the future by more than 5 minutes or more than 10 minutes in
/// the past, the message should be ignored by the receiver.
pub timestamp: MilliSecondsSinceUnixEpoch,
}
impl ToDeviceKeyVerificationRequestEventContent {
/// Creates a new `ToDeviceKeyVerificationRequestEventContent` with the given device ID,
/// transaction ID, methods and timestamp.
pub fn new(
from_device: Box<DeviceId>,
transaction_id: Box<TransactionId>,
methods: Vec<VerificationMethod>,
timestamp: MilliSecondsSinceUnixEpoch,
) -> Self |
}
| {
Self { from_device, transaction_id, methods, timestamp }
} | identifier_body |
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, TransactionId};
/// The content of an `m.key.verification.request` event.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.key.verification.request", kind = ToDevice)]
pub struct ToDeviceKeyVerificationRequestEventContent {
/// The device ID which is initiating the request.
pub from_device: Box<DeviceId>,
| /// An opaque identifier for the verification request.
///
/// Must be unique with respect to the devices involved.
pub transaction_id: Box<TransactionId>,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The time in milliseconds for when the request was made.
///
/// If the request is in the future by more than 5 minutes or more than 10 minutes in
/// the past, the message should be ignored by the receiver.
pub timestamp: MilliSecondsSinceUnixEpoch,
}
impl ToDeviceKeyVerificationRequestEventContent {
/// Creates a new `ToDeviceKeyVerificationRequestEventContent` with the given device ID,
/// transaction ID, methods and timestamp.
pub fn new(
from_device: Box<DeviceId>,
transaction_id: Box<TransactionId>,
methods: Vec<VerificationMethod>,
timestamp: MilliSecondsSinceUnixEpoch,
) -> Self {
Self { from_device, transaction_id, methods, timestamp }
}
} | random_line_split |
|
request.rs | //! Types for the [`m.key.verification.request`] event.
//!
//! [`m.key.verification.request`]: https://spec.matrix.org/v1.2/client-server-api/#mkeyverificationrequest
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};
use super::VerificationMethod;
use crate::{DeviceId, MilliSecondsSinceUnixEpoch, TransactionId};
/// The content of an `m.key.verification.request` event.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.key.verification.request", kind = ToDevice)]
pub struct ToDeviceKeyVerificationRequestEventContent {
/// The device ID which is initiating the request.
pub from_device: Box<DeviceId>,
/// An opaque identifier for the verification request.
///
/// Must be unique with respect to the devices involved.
pub transaction_id: Box<TransactionId>,
/// The verification methods supported by the sender.
pub methods: Vec<VerificationMethod>,
/// The time in milliseconds for when the request was made.
///
/// If the request is in the future by more than 5 minutes or more than 10 minutes in
/// the past, the message should be ignored by the receiver.
pub timestamp: MilliSecondsSinceUnixEpoch,
}
impl ToDeviceKeyVerificationRequestEventContent {
/// Creates a new `ToDeviceKeyVerificationRequestEventContent` with the given device ID,
/// transaction ID, methods and timestamp.
pub fn | (
from_device: Box<DeviceId>,
transaction_id: Box<TransactionId>,
methods: Vec<VerificationMethod>,
timestamp: MilliSecondsSinceUnixEpoch,
) -> Self {
Self { from_device, transaction_id, methods, timestamp }
}
}
| new | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::codegen::UnionTypes::BlobOrUSVString;
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::USVString;
use dom::blob::Blob;
use dom::file::File;
use dom::htmlformelement::HTMLFormElement;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use string_cache::Atom;
use util::str::DOMString;
#[derive(JSTraceable, Clone)]
#[must_root]
#[derive(HeapSizeOf)]
pub enum FormDatum {
StringData(String),
BlobData(JS<Blob>)
}
#[dom_struct]
pub struct FormData {
reflector_: Reflector,
data: DOMRefCell<HashMap<Atom, Vec<FormDatum>>>,
form: Option<JS<HTMLFormElement>>
}
impl FormData {
fn new_inherited(form: Option<&HTMLFormElement>) -> FormData {
FormData {
reflector_: Reflector::new(),
data: DOMRefCell::new(HashMap::new()),
form: form.map(|f| JS::from_ref(f)),
}
}
pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root<FormData> {
reflect_dom_object(box FormData::new_inherited(form),
global, FormDataBinding::Wrap)
}
pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> {
// TODO: Construct form data set for form if it is supplied
Ok(FormData::new(form, global))
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append(&self, name: USVString, value: USVString) {
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value.0)),
Vacant (entry) => { entry.insert(vec!(FormDatum::StringData(value.0))); }
}
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append_(&self, name: USVString, value: &Blob, filename: Option<USVString>) {
let blob = FormDatum::BlobData(JS::from_rooted(&self.get_file_or_blob(value, filename)));
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(blob),
Vacant(entry) => {
entry.insert(vec!(blob));
}
}
}
// https://xhr.spec.whatwg.org/#dom-formdata-delete
fn Delete(&self, name: USVString) {
self.data.borrow_mut().remove(&Atom::from(name.0));
}
// https://xhr.spec.whatwg.org/#dom-formdata-get
fn Get(&self, name: USVString) -> Option<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map(|entry| match entry[0] {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
})
}
// https://xhr.spec.whatwg.org/#dom-formdata-getall
fn GetAll(&self, name: USVString) -> Vec<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map_or(vec![], |data|
data.iter().map(|item| match *item {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
}).collect()
)
}
// https://xhr.spec.whatwg.org/#dom-formdata-has
fn Has(&self, name: USVString) -> bool {
self.data.borrow().contains_key(&Atom::from(name.0))
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-set
fn Set(&self, name: USVString, value: BlobOrUSVString) {
let val = match value { | BlobOrUSVString::USVString(s) => FormDatum::StringData(s.0),
BlobOrUSVString::Blob(b) => FormDatum::BlobData(JS::from_rooted(&b))
};
self.data.borrow_mut().insert(Atom::from(name.0), vec!(val));
}
}
impl FormData {
fn get_file_or_blob(&self, value: &Blob, filename: Option<USVString>) -> Root<Blob> {
match filename {
Some(fname) => {
let global = self.global();
let name = DOMString::from(fname.0);
Root::upcast(File::new(global.r(), value, name))
}
None => Root::from_ref(value)
}
}
} | random_line_split |
|
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::codegen::UnionTypes::BlobOrUSVString;
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::USVString;
use dom::blob::Blob;
use dom::file::File;
use dom::htmlformelement::HTMLFormElement;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use string_cache::Atom;
use util::str::DOMString;
#[derive(JSTraceable, Clone)]
#[must_root]
#[derive(HeapSizeOf)]
pub enum FormDatum {
StringData(String),
BlobData(JS<Blob>)
}
#[dom_struct]
pub struct FormData {
reflector_: Reflector,
data: DOMRefCell<HashMap<Atom, Vec<FormDatum>>>,
form: Option<JS<HTMLFormElement>>
}
impl FormData {
fn new_inherited(form: Option<&HTMLFormElement>) -> FormData {
FormData {
reflector_: Reflector::new(),
data: DOMRefCell::new(HashMap::new()),
form: form.map(|f| JS::from_ref(f)),
}
}
pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root<FormData> {
reflect_dom_object(box FormData::new_inherited(form),
global, FormDataBinding::Wrap)
}
pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> {
// TODO: Construct form data set for form if it is supplied
Ok(FormData::new(form, global))
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append(&self, name: USVString, value: USVString) {
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value.0)),
Vacant (entry) => { entry.insert(vec!(FormDatum::StringData(value.0))); }
}
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append_(&self, name: USVString, value: &Blob, filename: Option<USVString>) {
let blob = FormDatum::BlobData(JS::from_rooted(&self.get_file_or_blob(value, filename)));
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(blob),
Vacant(entry) => {
entry.insert(vec!(blob));
}
}
}
// https://xhr.spec.whatwg.org/#dom-formdata-delete
fn | (&self, name: USVString) {
self.data.borrow_mut().remove(&Atom::from(name.0));
}
// https://xhr.spec.whatwg.org/#dom-formdata-get
fn Get(&self, name: USVString) -> Option<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map(|entry| match entry[0] {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
})
}
// https://xhr.spec.whatwg.org/#dom-formdata-getall
fn GetAll(&self, name: USVString) -> Vec<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map_or(vec![], |data|
data.iter().map(|item| match *item {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
}).collect()
)
}
// https://xhr.spec.whatwg.org/#dom-formdata-has
fn Has(&self, name: USVString) -> bool {
self.data.borrow().contains_key(&Atom::from(name.0))
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-set
fn Set(&self, name: USVString, value: BlobOrUSVString) {
let val = match value {
BlobOrUSVString::USVString(s) => FormDatum::StringData(s.0),
BlobOrUSVString::Blob(b) => FormDatum::BlobData(JS::from_rooted(&b))
};
self.data.borrow_mut().insert(Atom::from(name.0), vec!(val));
}
}
impl FormData {
fn get_file_or_blob(&self, value: &Blob, filename: Option<USVString>) -> Root<Blob> {
match filename {
Some(fname) => {
let global = self.global();
let name = DOMString::from(fname.0);
Root::upcast(File::new(global.r(), value, name))
}
None => Root::from_ref(value)
}
}
}
| Delete | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::codegen::UnionTypes::BlobOrUSVString;
use dom::bindings::error::{Fallible};
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::USVString;
use dom::blob::Blob;
use dom::file::File;
use dom::htmlformelement::HTMLFormElement;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use string_cache::Atom;
use util::str::DOMString;
#[derive(JSTraceable, Clone)]
#[must_root]
#[derive(HeapSizeOf)]
pub enum FormDatum {
StringData(String),
BlobData(JS<Blob>)
}
#[dom_struct]
pub struct FormData {
reflector_: Reflector,
data: DOMRefCell<HashMap<Atom, Vec<FormDatum>>>,
form: Option<JS<HTMLFormElement>>
}
impl FormData {
fn new_inherited(form: Option<&HTMLFormElement>) -> FormData {
FormData {
reflector_: Reflector::new(),
data: DOMRefCell::new(HashMap::new()),
form: form.map(|f| JS::from_ref(f)),
}
}
pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root<FormData> {
reflect_dom_object(box FormData::new_inherited(form),
global, FormDataBinding::Wrap)
}
pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> {
// TODO: Construct form data set for form if it is supplied
Ok(FormData::new(form, global))
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append(&self, name: USVString, value: USVString) {
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(FormDatum::StringData(value.0)),
Vacant (entry) => { entry.insert(vec!(FormDatum::StringData(value.0))); }
}
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append_(&self, name: USVString, value: &Blob, filename: Option<USVString>) {
let blob = FormDatum::BlobData(JS::from_rooted(&self.get_file_or_blob(value, filename)));
let mut data = self.data.borrow_mut();
match data.entry(Atom::from(name.0)) {
Occupied(entry) => entry.into_mut().push(blob),
Vacant(entry) => |
}
}
// https://xhr.spec.whatwg.org/#dom-formdata-delete
fn Delete(&self, name: USVString) {
self.data.borrow_mut().remove(&Atom::from(name.0));
}
// https://xhr.spec.whatwg.org/#dom-formdata-get
fn Get(&self, name: USVString) -> Option<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map(|entry| match entry[0] {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
})
}
// https://xhr.spec.whatwg.org/#dom-formdata-getall
fn GetAll(&self, name: USVString) -> Vec<BlobOrUSVString> {
self.data.borrow()
.get(&Atom::from(name.0))
.map_or(vec![], |data|
data.iter().map(|item| match *item {
FormDatum::StringData(ref s) => BlobOrUSVString::USVString(USVString(s.clone())),
FormDatum::BlobData(ref b) => BlobOrUSVString::Blob(Root::from_ref(&*b)),
}).collect()
)
}
// https://xhr.spec.whatwg.org/#dom-formdata-has
fn Has(&self, name: USVString) -> bool {
self.data.borrow().contains_key(&Atom::from(name.0))
}
#[allow(unrooted_must_root)]
// https://xhr.spec.whatwg.org/#dom-formdata-set
fn Set(&self, name: USVString, value: BlobOrUSVString) {
let val = match value {
BlobOrUSVString::USVString(s) => FormDatum::StringData(s.0),
BlobOrUSVString::Blob(b) => FormDatum::BlobData(JS::from_rooted(&b))
};
self.data.borrow_mut().insert(Atom::from(name.0), vec!(val));
}
}
impl FormData {
fn get_file_or_blob(&self, value: &Blob, filename: Option<USVString>) -> Root<Blob> {
match filename {
Some(fname) => {
let global = self.global();
let name = DOMString::from(fname.0);
Root::upcast(File::new(global.r(), value, name))
}
None => Root::from_ref(value)
}
}
}
| {
entry.insert(vec!(blob));
} | conditional_block |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
H256::from(Sha256::digest(data).as_ref())
}
pub fn hmac_sha256(key: &[u8], input: &[&[u8]], auth_data: &[u8]) -> H256 {
let mut hmac = Hmac::<Sha256>::new_varkey(key).unwrap();
for input in input {
hmac.update(input);
}
hmac.update(auth_data);
H256::from_slice(&*hmac.finalize().into_bytes())
}
pub fn pk2id(pk: &PublicKey) -> PeerId {
PeerId::from_slice(&pk.serialize_uncompressed()[1..])
}
pub fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> {
let mut s = [0_u8; 65];
s[0] = 4;
s[1..].copy_from_slice(&id.as_bytes());
PublicKey::from_slice(&s)
}
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &mut Formatter) -> fmt::Result {
f.write_str(&hex::encode(&s))
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::{SecretKey, SECP256K1}; | let pubkey = PublicKey::from_secret_key(SECP256K1, &prikey);
assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
}
} |
#[test]
fn pk2id2pk() {
let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng()); | random_line_split |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
H256::from(Sha256::digest(data).as_ref())
}
pub fn hmac_sha256(key: &[u8], input: &[&[u8]], auth_data: &[u8]) -> H256 {
let mut hmac = Hmac::<Sha256>::new_varkey(key).unwrap();
for input in input {
hmac.update(input);
}
hmac.update(auth_data);
H256::from_slice(&*hmac.finalize().into_bytes())
}
pub fn pk2id(pk: &PublicKey) -> PeerId {
PeerId::from_slice(&pk.serialize_uncompressed()[1..])
}
pub fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> |
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &mut Formatter) -> fmt::Result {
f.write_str(&hex::encode(&s))
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::{SecretKey, SECP256K1};
#[test]
fn pk2id2pk() {
let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng());
let pubkey = PublicKey::from_secret_key(SECP256K1, &prikey);
assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
}
}
| {
let mut s = [0_u8; 65];
s[0] = 4;
s[1..].copy_from_slice(&id.as_bytes());
PublicKey::from_slice(&s)
} | identifier_body |
util.rs | use crate::types::*;
use ethereum_types::H256;
use hmac::{Hmac, Mac, NewMac};
use secp256k1::PublicKey;
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::fmt::{self, Formatter};
pub fn keccak256(data: &[u8]) -> H256 {
H256::from(Keccak256::digest(data).as_ref())
}
pub fn sha256(data: &[u8]) -> H256 {
H256::from(Sha256::digest(data).as_ref())
}
pub fn hmac_sha256(key: &[u8], input: &[&[u8]], auth_data: &[u8]) -> H256 {
let mut hmac = Hmac::<Sha256>::new_varkey(key).unwrap();
for input in input {
hmac.update(input);
}
hmac.update(auth_data);
H256::from_slice(&*hmac.finalize().into_bytes())
}
pub fn | (pk: &PublicKey) -> PeerId {
PeerId::from_slice(&pk.serialize_uncompressed()[1..])
}
pub fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> {
let mut s = [0_u8; 65];
s[0] = 4;
s[1..].copy_from_slice(&id.as_bytes());
PublicKey::from_slice(&s)
}
pub fn hex_debug<T: AsRef<[u8]>>(s: &T, f: &mut Formatter) -> fmt::Result {
f.write_str(&hex::encode(&s))
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::{SecretKey, SECP256K1};
#[test]
fn pk2id2pk() {
let prikey = SecretKey::new(&mut secp256k1::rand::thread_rng());
let pubkey = PublicKey::from_secret_key(SECP256K1, &prikey);
assert_eq!(pubkey, id2pk(pk2id(&pubkey)).unwrap());
}
}
| pk2id | identifier_name |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n!= s3.len() {
return false;
}
// f[i][j] 表示 s1 的前 i 个和 s2 的前 j 个是否能组合成 s3.
let mut f = vec![vec![false; n + 1]; m + 1];
f[0][0] = true;
for i in 0..=m {
for j in 0..=n {
// 当 i=0,j=0 时,这里的 p 是 -1,但 p 的类型是 usize,所以我们移到下面再计算。
// let p = i + j - 1; // 对应的 s3 的下标
if i > 0 {
f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1];
}
if j > 0 {
// 可能上面计算出来了 f[i][j] == true 了,那这里就不用再计算了
f[i][j] = f[i][j] || (f[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
}
f[m][n]
}
// by zhangyuchen. 通过了,但是 用时 804ms,内存 2M。用时过长。
pub fn is_interleave1(s1: String, s2: String, s3: String) -> bool {
if s1.len() + s2.len()!= s3.len() {
return false;
}
Self::is_interleave1_helper(s1.as_bytes(), 0, s2.as_bytes(), 0, s3.as_bytes(), 0)
}
fn is_interleave1_helper(
s1: &[u8],
i: usize,
s2: &[u8],
j: usize,
s3: &[u8],
k: usize,
) -> bool {
// 都到达终点了,匹配
if k == s3.len() {
return i == s1.len() && j == s2.len();
}
if i < s1.len()
&& s3[k] == s1[i]
&& Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1)
{
return true;
}
if j < s2.len()
&& s3[k] == s2[j]
&& Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1)
{
return true;
}
false
}
}
#[cfg(test)] | #[test]
fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbbaccc".to_owned(),
),
false
);
}
} | mod tests {
use super::*;
| random_line_split |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n!= s3.len() {
return false;
}
// f[i][j] 表示 s1 的前 i 个和 s2 的前 j 个是否能组合成 s3.
let mut f = vec![vec![false; n + 1]; m + 1];
f[0][0] = true;
for i in 0..=m {
for j in 0..=n {
// 当 i=0,j=0 时,这里的 p 是 -1,但 p 的类型是 usize,所以我们移到下面再计算。
// let p = i + j - 1; // 对应的 s3 的下标
if i > 0 {
f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1];
}
if j > 0 {
// 可能上面计算出来了 f[i][j] == true 了,那这里就不用再计算了
f[i][j] = f[i][j] || (f[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
}
f[m][n]
}
// by zhangyuchen. 通过了,但是 用时 804ms,内存 2M。用时过长。
pub fn is_interleave1(s1: String, s2: String, s3: String) -> bool {
if s1.len() + s2.len()!= s3.len() {
return false;
}
Self::is_interleave1_helper(s1.as_bytes(), 0, s2.as_bytes(), 0, s3.as_bytes(), 0)
}
fn is_interleave1_helper(
s1: &[u8],
i: usize,
s2: &[u8],
j: usize,
s3: &[u8],
k: usize,
) -> bool {
// 都到达终点了,匹配
if k == s3.len() {
return i == s1.len() && j == s2.len();
}
if i < s1.len()
&& s3[k] == s1[i]
&& Self::is_interleave1_helper(s1, | fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbbaccc".to_owned(),
),
false
);
}
}
| i + 1, s2, j, s3, k + 1)
{
return true;
}
if j < s2.len()
&& s3[k] == s2[j]
&& Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1)
{
return true;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test] | identifier_body |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n!= s3.len() {
return false;
}
// f[i][j] 表示 s1 的前 i 个和 s2 的前 j 个是否能组合成 s3.
let mut f = vec![vec![false; n + 1]; m + 1];
f[0][0] = true;
for i in 0..=m {
for j in 0..=n {
// 当 i=0,j=0 时,这里的 p 是 -1,但 p 的类型是 usize,所以我们移到下面再计算。
// let p = i + j - 1; // 对应的 s3 的下标
if i > 0 {
f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1];
}
if j > 0 {
// 可能上面计算出来了 f[i][j] == true 了,那这里就不用再计算了
f[i][j] = f[i][j] || (f[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
}
f[m][n]
}
// by zhangyuchen. 通过了,但是 用时 804ms,内存 2M。用时过长。
pub fn is_interleave1(s1: String, s2: String, s3: String) -> bool {
if s1.len() + s2.len()!= s3.len() {
return false;
}
Self::is_interleave1_helper(s1.as_bytes(), 0, s2.as_bytes(), 0, s3.as_bytes(), 0)
}
fn is_interleave1_helper(
s1: &[u8],
i: usize,
s2 | : &[u8],
k: usize,
) -> bool {
// 都到达终点了,匹配
if k == s3.len() {
return i == s1.len() && j == s2.len();
}
if i < s1.len()
&& s3[k] == s1[i]
&& Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1)
{
return true;
}
if j < s2.len()
&& s3[k] == s2[j]
&& Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1)
{
return true;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbbaccc".to_owned(),
),
false
);
}
}
| : &[u8],
j: usize,
s3 | conditional_block |
no_0097_interleaving_string.rs | struct Solution;
impl Solution {
// 题解中没有使用滚动数组优化的动态规划解法。
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes());
let (m, n) = (s1.len(), s2.len());
if m + n!= s3.len() {
return false;
}
// f[i][j] 表示 s1 的前 i 个和 s2 的前 j 个是否能组合成 s3.
let mut f = vec![vec![false; n + 1]; m + 1];
f[0][0] = true;
for i in 0..=m {
for j in 0..=n {
// 当 i=0,j=0 时,这里的 p 是 -1,但 p 的类型是 usize,所以我们移到下面再计算。
// let p = i + j - 1; // 对应的 s3 的下标
if i > 0 {
f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1];
}
if j > 0 {
// 可能上面计算出来了 f[i][j] == true 了,那这里就不用再计算了
f[i][j] = f[i][j] || (f[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
}
f[m][n]
}
// by zhangyuchen. 通过了,但是 用时 804ms,内存 2M。用时过长。
pub fn is_interleave1(s1: String, s2: String, s3: String) -> bool {
if s1.len() + s2.len()!= s3.len() {
return false;
}
Self::is_interleave1_helper(s1.as_bytes(), 0, s2.as_bytes(), 0, s3.as_bytes(), 0)
}
fn is_interleave1_helper(
s1: &[u8],
i: usize,
s2: &[u8],
j: usize,
s3: &[u8],
k: usize,
) -> bool {
// 都到达终点了,匹配
if k == s3.len() {
return i == s1.len() && j == s2.len();
}
if i < s1.len()
&& s3[k] == s1[i]
&& Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1)
{
return true;
}
if j < s2.len()
&& s3[k] == s2[j]
&& Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1)
{
return true;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_interleave1() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbcbcac".to_owned(),
),
true
);
}
#[test]
fn test_is_interleave2() {
assert_eq!(
Solution::is_interleave(
"aabcc".to_owned(),
"dbbca".to_owned(),
"aadbbbaccc".to_owned(),
),
false
| );
}
}
| identifier_name |
|
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:trait_inheritance_auto_xc_2_aux.rs
extern crate "trait_inheritance_auto_xc_2_aux" as aux;
// aux defines impls of Foo, Bar and Baz for A
use aux::{Foo, Bar, Baz, A};
// We want to extend all Foo, Bar, Bazes to Quuxes
pub trait Quux: Foo + Bar + Baz { }
impl<T:Foo + Bar + Baz> Quux for T { }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn | () {
let a = &A { x: 3 };
f(a);
}
| main | identifier_name |
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:trait_inheritance_auto_xc_2_aux.rs
extern crate "trait_inheritance_auto_xc_2_aux" as aux;
// aux defines impls of Foo, Bar and Baz for A
use aux::{Foo, Bar, Baz, A};
// We want to extend all Foo, Bar, Bazes to Quuxes
pub trait Quux: Foo + Bar + Baz { }
impl<T:Foo + Bar + Baz> Quux for T { }
fn f<T:Quux>(a: &T) |
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
} | identifier_body |
trait-inheritance-auto-xc-2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| // aux-build:trait_inheritance_auto_xc_2_aux.rs
extern crate "trait_inheritance_auto_xc_2_aux" as aux;
// aux defines impls of Foo, Bar and Baz for A
use aux::{Foo, Bar, Baz, A};
// We want to extend all Foo, Bar, Bazes to Quuxes
pub trait Quux: Foo + Bar + Baz { }
impl<T:Foo + Bar + Baz> Quux for T { }
fn f<T:Quux>(a: &T) {
assert_eq!(a.f(), 10);
assert_eq!(a.g(), 20);
assert_eq!(a.h(), 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
} | random_line_split |
|
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String {
"0001".to_string()
}
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() -> String {
"application/json".to_string()
}
pub fn xml_datacontenttype() -> String {
"application/xml".to_string()
}
pub fn dataschema() -> String {
"http://localhost/schema".to_string()
}
pub fn json_data() -> Value {
json!({"hello": "world"})
}
pub fn json_data_binary() -> Vec<u8> {
serde_json::to_vec(&json!({"hello": "world"})).unwrap()
}
pub fn xml_data() -> String {
"<hello>world</hello>".to_string()
}
| }
pub fn time() -> DateTime<Utc> {
Utc.ymd(2020, 3, 16).and_hms(11, 50, 00)
}
pub fn string_extension() -> (String, String) {
("string_ex".to_string(), "val".to_string())
}
pub fn bool_extension() -> (String, bool) {
("bool_ex".to_string(), true)
}
pub fn int_extension() -> (String, i64) {
("int_ex".to_string(), 10)
} | pub fn subject() -> String {
"cloudevents-sdk".to_string() | random_line_split |
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String {
"0001".to_string()
}
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() -> String {
"application/json".to_string()
}
pub fn xml_datacontenttype() -> String {
"application/xml".to_string()
}
pub fn | () -> String {
"http://localhost/schema".to_string()
}
pub fn json_data() -> Value {
json!({"hello": "world"})
}
pub fn json_data_binary() -> Vec<u8> {
serde_json::to_vec(&json!({"hello": "world"})).unwrap()
}
pub fn xml_data() -> String {
"<hello>world</hello>".to_string()
}
pub fn subject() -> String {
"cloudevents-sdk".to_string()
}
pub fn time() -> DateTime<Utc> {
Utc.ymd(2020, 3, 16).and_hms(11, 50, 00)
}
pub fn string_extension() -> (String, String) {
("string_ex".to_string(), "val".to_string())
}
pub fn bool_extension() -> (String, bool) {
("bool_ex".to_string(), true)
}
pub fn int_extension() -> (String, i64) {
("int_ex".to_string(), 10)
}
| dataschema | identifier_name |
mod.rs | pub mod v03;
pub mod v10;
use chrono::{DateTime, TimeZone, Utc};
use serde_json::{json, Value};
pub fn id() -> String |
pub fn ty() -> String {
"test_event.test_application".to_string()
}
pub fn source() -> String {
"http://localhost/".to_string()
}
pub fn json_datacontenttype() -> String {
"application/json".to_string()
}
pub fn xml_datacontenttype() -> String {
"application/xml".to_string()
}
pub fn dataschema() -> String {
"http://localhost/schema".to_string()
}
pub fn json_data() -> Value {
json!({"hello": "world"})
}
pub fn json_data_binary() -> Vec<u8> {
serde_json::to_vec(&json!({"hello": "world"})).unwrap()
}
pub fn xml_data() -> String {
"<hello>world</hello>".to_string()
}
pub fn subject() -> String {
"cloudevents-sdk".to_string()
}
pub fn time() -> DateTime<Utc> {
Utc.ymd(2020, 3, 16).and_hms(11, 50, 00)
}
pub fn string_extension() -> (String, String) {
("string_ex".to_string(), "val".to_string())
}
pub fn bool_extension() -> (String, bool) {
("bool_ex".to_string(), true)
}
pub fn int_extension() -> (String, i64) {
("int_ex".to_string(), 10)
}
| {
"0001".to_string()
} | identifier_body |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum; | }
impl Into<BigNum> for BigNumComponent {
fn into(self) -> BigNum {
self.0
}
}
impl Part for BigNumComponent {
type Encoded = String;
fn to_base64(&self) -> JwtResult<String> {
Ok(ToBase64::to_base64(&self.to_vec()[..], URL_SAFE))
}
fn from_base64<B: AsRef<[u8]>>(encoded: B) -> JwtResult<BigNumComponent> {
let decoded = try!(encoded.as_ref().from_base64());
let bn = try!(BigNum::from_slice(&decoded));
Ok(BigNumComponent(bn))
}
}
#[cfg(test)]
mod test {
use super::*;
use Part;
#[test]
fn test_bignum_base64() {
let bn_b64 = "AQAB";
let bn = BigNumComponent::from_base64(bn_b64.as_bytes()).unwrap();
let result = bn.to_base64().unwrap();
assert_eq!(result, bn_b64);
}
} |
fn deref(&self) -> &Self::Target {
&self.0
} | random_line_split |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Into<BigNum> for BigNumComponent {
fn into(self) -> BigNum {
self.0
}
}
impl Part for BigNumComponent {
type Encoded = String;
fn to_base64(&self) -> JwtResult<String> {
Ok(ToBase64::to_base64(&self.to_vec()[..], URL_SAFE))
}
fn from_base64<B: AsRef<[u8]>>(encoded: B) -> JwtResult<BigNumComponent> |
}
#[cfg(test)]
mod test {
use super::*;
use Part;
#[test]
fn test_bignum_base64() {
let bn_b64 = "AQAB";
let bn = BigNumComponent::from_base64(bn_b64.as_bytes()).unwrap();
let result = bn.to_base64().unwrap();
assert_eq!(result, bn_b64);
}
} | {
let decoded = try!(encoded.as_ref().from_base64());
let bn = try!(BigNum::from_slice(&decoded));
Ok(BigNumComponent(bn))
} | identifier_body |
bignum.rs | use openssl::bn::BigNum;
use std::ops::Deref;
use super::Part;
use result::JwtResult;
use rustc_serialize::base64::*;
pub struct BigNumComponent(pub BigNum);
impl Deref for BigNumComponent {
type Target = BigNum;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Into<BigNum> for BigNumComponent {
fn into(self) -> BigNum {
self.0
}
}
impl Part for BigNumComponent {
type Encoded = String;
fn to_base64(&self) -> JwtResult<String> {
Ok(ToBase64::to_base64(&self.to_vec()[..], URL_SAFE))
}
fn | <B: AsRef<[u8]>>(encoded: B) -> JwtResult<BigNumComponent> {
let decoded = try!(encoded.as_ref().from_base64());
let bn = try!(BigNum::from_slice(&decoded));
Ok(BigNumComponent(bn))
}
}
#[cfg(test)]
mod test {
use super::*;
use Part;
#[test]
fn test_bignum_base64() {
let bn_b64 = "AQAB";
let bn = BigNumComponent::from_base64(bn_b64.as_bytes()).unwrap();
let result = bn.to_base64().unwrap();
assert_eq!(result, bn_b64);
}
} | from_base64 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.