file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess."); |
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} |
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess); | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() | Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) { | identifier_body |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn | (&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | get_exp | identifier_name |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() |
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
} | conditional_block |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex { | pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | self.position
}
}
impl Player { | random_line_split |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) |
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | {
self.position = tile;
dbg!("Player moved to {}", tile);
} | identifier_body |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn | () {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | parse_and_match_single_val | identifier_name |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap(); | }
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
}); | random_line_split |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint |
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | {
regex_body = regex_body + "$";
} | conditional_block |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() |
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
} | identifier_body |
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
pub fn spawn(task: Task) | {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
} | identifier_body |
|
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
| pub fn spawn(task: Task) {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
} | random_line_split |
|
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
pub fn | (task: Task) {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
}
| spawn | identifier_name |
sha2.rs | FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: uint);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> uint;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> uint;
/// Get the size of the buffer
fn size(&self) -> uint;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: uint,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx!= 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..i + size]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: uint) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[..64];
}
fn position(&self) -> uint { self.buffer_idx }
fn remaining(&self) -> uint { 64 - self.buffer_idx }
fn size(&self) -> uint { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: uint, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: uint, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> uint;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn process_block(&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0u, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48u, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> uint { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1u) / 2u;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog".to_string(),
output_str: "d7a8fbb307d7809469ca\
9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog.".to_string(), | output_str: "ef537f25c895bfa78252\
6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string()
});
let tests = wikipedia_tests; | random_line_split |
|
sha2.rs | self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
}
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modified
/// results in those bytes being marked as used by the buffer.
trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: uint);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> uint;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> uint;
/// Get the size of the buffer
fn size(&self) -> uint;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: uint,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx!= 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..i + size]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: uint) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[..64];
}
fn position(&self) -> uint { self.buffer_idx }
fn remaining(&self) -> uint { 64 - self.buffer_idx }
fn size(&self) -> uint { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: uint, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: uint, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> uint;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn | (&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0u, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48u, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> uint { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1u) / 2u;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
| process_block | identifier_name |
access_control_allow_methods.rs | use method::Method;
header! {
#[doc="`Access-Control-Allow-Methods` header, part of"]
#[doc="[CORS](http://www.w3.org/TR/cors/#access-control-allow-methods-response-header)"]
#[doc=""]
#[doc="The `Access-Control-Allow-Methods` header indicates, as part of the"]
#[doc="response to a preflight request, which methods can be used during the"]
#[doc="actual request."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Access-Control-Allow-Methods: \"Access-Control-Allow-Methods\" \":\" #Method"]
#[doc="```"]
#[doc=""] | #[doc="```"]
#[doc="use hyper::header::{Headers, AccessControlAllowMethods};"]
#[doc="use hyper::method::Method;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" AccessControlAllowMethods(vec![Method::Get])"]
#[doc=");"]
#[doc="```"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AccessControlAllowMethods};"]
#[doc="use hyper::method::Method;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" AccessControlAllowMethods(vec!["]
#[doc=" Method::Get,"]
#[doc=" Method::Post,"]
#[doc=" Method::Patch,"]
#[doc=" Method::Extension(\"COPY\".to_owned()),"]
#[doc=" ])"]
#[doc=");"]
#[doc="```"]
(AccessControlAllowMethods, "Access-Control-Allow-Methods") => (Method)*
test_access_control_allow_methods {
test_header!(test1, vec![b"PUT, DELETE, XMODIFY"]);
}
} | #[doc="# Example values"]
#[doc="* `PUT, DELETE, XMODIFY`"]
#[doc=""]
#[doc="# Examples"] | random_line_split |
issue-2356.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Groom {
fn shave(other: usize);
}
pub struct cat {
whiskers: isize,
}
pub enum MaybeDog {
Dog,
NoDog
}
impl MaybeDog {
fn bark() {
// If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom
shave();
//~^ ERROR cannot find function `shave`
}
}
impl Clone for cat {
fn clone(&self) -> Self {
clone();
//~^ ERROR cannot find function `clone`
loop {}
}
}
impl Default for cat {
fn default() -> Self {
default();
//~^ ERROR cannot find function `default`
loop {}
}
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn static_method() {}
fn purr_louder() {
static_method();
//~^ ERROR cannot find function `static_method`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn meow() {
if self.whiskers > 3 {
//~^ ERROR expected value, found module `self`
println!("MEOW");
}
}
fn purr(&self) {
grow_older();
//~^ ERROR cannot find function `grow_older`
shave();
//~^ ERROR cannot find function `shave`
}
fn burn_whiskers(&mut self) {
whiskers = 0;
//~^ ERROR cannot find value `whiskers`
}
pub fn | (other:usize) {
whiskers = 4;
//~^ ERROR cannot find value `whiskers`
purr_louder();
//~^ ERROR cannot find function `purr_louder`
}
}
fn main() {
self += 1;
//~^ ERROR expected value, found module `self`
}
| grow_older | identifier_name |
issue-2356.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Groom {
fn shave(other: usize);
}
pub struct cat {
whiskers: isize,
}
pub enum MaybeDog {
Dog,
NoDog
}
impl MaybeDog {
fn bark() {
// If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom
shave();
//~^ ERROR cannot find function `shave`
}
}
impl Clone for cat {
fn clone(&self) -> Self {
clone();
//~^ ERROR cannot find function `clone`
loop {}
}
}
impl Default for cat {
fn default() -> Self {
default();
//~^ ERROR cannot find function `default`
loop {}
}
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn static_method() {}
fn purr_louder() {
static_method();
//~^ ERROR cannot find function `static_method`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn meow() {
if self.whiskers > 3 |
}
fn purr(&self) {
grow_older();
//~^ ERROR cannot find function `grow_older`
shave();
//~^ ERROR cannot find function `shave`
}
fn burn_whiskers(&mut self) {
whiskers = 0;
//~^ ERROR cannot find value `whiskers`
}
pub fn grow_older(other:usize) {
whiskers = 4;
//~^ ERROR cannot find value `whiskers`
purr_louder();
//~^ ERROR cannot find function `purr_louder`
}
}
fn main() {
self += 1;
//~^ ERROR expected value, found module `self`
}
| {
//~^ ERROR expected value, found module `self`
println!("MEOW");
} | conditional_block |
issue-2356.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Groom {
fn shave(other: usize);
}
pub struct cat {
whiskers: isize,
}
pub enum MaybeDog {
Dog,
NoDog
}
impl MaybeDog {
fn bark() {
// If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom
shave();
//~^ ERROR cannot find function `shave`
}
}
impl Clone for cat {
fn clone(&self) -> Self {
clone();
//~^ ERROR cannot find function `clone`
loop {}
}
}
impl Default for cat {
fn default() -> Self |
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn static_method() {}
fn purr_louder() {
static_method();
//~^ ERROR cannot find function `static_method`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn meow() {
if self.whiskers > 3 {
//~^ ERROR expected value, found module `self`
println!("MEOW");
}
}
fn purr(&self) {
grow_older();
//~^ ERROR cannot find function `grow_older`
shave();
//~^ ERROR cannot find function `shave`
}
fn burn_whiskers(&mut self) {
whiskers = 0;
//~^ ERROR cannot find value `whiskers`
}
pub fn grow_older(other:usize) {
whiskers = 4;
//~^ ERROR cannot find value `whiskers`
purr_louder();
//~^ ERROR cannot find function `purr_louder`
}
}
fn main() {
self += 1;
//~^ ERROR expected value, found module `self`
}
| {
default();
//~^ ERROR cannot find function `default`
loop {}
} | identifier_body |
issue-2356.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Groom {
fn shave(other: usize);
}
pub struct cat {
whiskers: isize,
}
pub enum MaybeDog {
Dog,
NoDog
}
impl MaybeDog {
fn bark() {
// If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom
shave();
//~^ ERROR cannot find function `shave`
}
}
impl Clone for cat {
fn clone(&self) -> Self {
clone(); | impl Default for cat {
fn default() -> Self {
default();
//~^ ERROR cannot find function `default`
loop {}
}
}
impl Groom for cat {
fn shave(other: usize) {
whiskers -= other;
//~^ ERROR cannot find value `whiskers`
shave(4);
//~^ ERROR cannot find function `shave`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn static_method() {}
fn purr_louder() {
static_method();
//~^ ERROR cannot find function `static_method`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
purr();
//~^ ERROR cannot find function `purr`
}
}
impl cat {
fn meow() {
if self.whiskers > 3 {
//~^ ERROR expected value, found module `self`
println!("MEOW");
}
}
fn purr(&self) {
grow_older();
//~^ ERROR cannot find function `grow_older`
shave();
//~^ ERROR cannot find function `shave`
}
fn burn_whiskers(&mut self) {
whiskers = 0;
//~^ ERROR cannot find value `whiskers`
}
pub fn grow_older(other:usize) {
whiskers = 4;
//~^ ERROR cannot find value `whiskers`
purr_louder();
//~^ ERROR cannot find function `purr_louder`
}
}
fn main() {
self += 1;
//~^ ERROR expected value, found module `self`
} | //~^ ERROR cannot find function `clone`
loop {}
}
} | random_line_split |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ast;
use syntax::codemap::Span;
use CrateCtxt;
/// Check that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
/// method that is called)
pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) | };
span_err!(tcx.sess, span, E0174,
"explicit use of unboxed closure method `{}` is experimental",
method);
span_help!(tcx.sess, span,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
}
| {
let tcx = ccx.tcx;
let did = Some(trait_id);
let li = &tcx.lang_items;
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if !tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
let method = if did == li.fn_trait() {
"call"
} else if did == li.fn_mut_trait() {
"call_mut"
} else if did == li.fn_once_trait() {
"call_once"
} else {
return // not a closure method, everything is OK. | identifier_body |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ast;
use syntax::codemap::Span;
use CrateCtxt;
/// Check that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
/// method that is called)
pub fn | (ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) {
let tcx = ccx.tcx;
let did = Some(trait_id);
let li = &tcx.lang_items;
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if!tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
let method = if did == li.fn_trait() {
"call"
} else if did == li.fn_mut_trait() {
"call_mut"
} else if did == li.fn_once_trait() {
"call_once"
} else {
return // not a closure method, everything is OK.
};
span_err!(tcx.sess, span, E0174,
"explicit use of unboxed closure method `{}` is experimental",
method);
span_help!(tcx.sess, span,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
}
| check_legal_trait_for_method_call | identifier_name |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ast;
use syntax::codemap::Span;
use CrateCtxt;
/// Check that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
/// method that is called)
pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) {
let tcx = ccx.tcx;
let did = Some(trait_id);
let li = &tcx.lang_items;
if did == li.drop_trait() | else if!tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
let method = if did == li.fn_trait() {
"call"
} else if did == li.fn_mut_trait() {
"call_mut"
} else if did == li.fn_once_trait() {
"call_once"
} else {
return // not a closure method, everything is OK.
};
span_err!(tcx.sess, span, E0174,
"explicit use of unboxed closure method `{}` is experimental",
method);
span_help!(tcx.sess, span,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
}
| {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} | conditional_block |
callee.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::ast;
use syntax::codemap::Span;
use CrateCtxt;
/// Check that it is legal to call methods of the trait corresponding
/// to `trait_id` (this only cares about the trait, not the specific
/// method that is called)
pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) {
let tcx = ccx.tcx; |
if did == li.drop_trait() {
span_err!(tcx.sess, span, E0040, "explicit use of destructor method");
} else if!tcx.sess.features.borrow().unboxed_closures {
// the #[feature(unboxed_closures)] feature isn't
// activated so we need to enforce the closure
// restrictions.
let method = if did == li.fn_trait() {
"call"
} else if did == li.fn_mut_trait() {
"call_mut"
} else if did == li.fn_once_trait() {
"call_once"
} else {
return // not a closure method, everything is OK.
};
span_err!(tcx.sess, span, E0174,
"explicit use of unboxed closure method `{}` is experimental",
method);
span_help!(tcx.sess, span,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
} | let did = Some(trait_id);
let li = &tcx.lang_items; | random_line_split |
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// match s_b.cmp(&o_b) {
// Greater => return Greater,
// Less => return Less,
// Equal => ()
// }
// }
//
// self.len().cmp(&other.len())
// }
// }
#[test]
fn | () {
let x: &str = "日"; // '\u{65e5}'
let other: &str = "月"; // '\u{6708}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
#[test]
fn cmp_test2() {
let x: &str = "天"; // '\u{5929}'
let other: &str = "地"; // '\u{5730}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test3() {
let x: &str = "人";
let other: &str = x;
let result: Ordering = x.cmp(other);
assert_eq!(result, Equal);
}
#[test]
fn cmp_test4() {
let x: &str = "人口";
let other: &str = "人";
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test5() {
let x: &str = "人";
let other: &str = "人種";
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
}
| cmp_test1 | identifier_name |
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// match s_b.cmp(&o_b) {
// Greater => return Greater,
// Less => return Less,
// Equal => ()
// }
// }
//
// self.len().cmp(&other.len())
// }
// }
#[test]
fn cmp_test1() {
let x: &str = "日"; // '\u{65e5}'
let other: &str = "月"; // '\u{6708}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
#[test]
fn cmp_test2() {
let x: &str = "天"; // '\u{5929}'
let other: &str = "地"; // '\u{5730}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test3() {
let x: &str = "人";
let other: &str = x;
let result: Ordering = x.cmp(other);
assert_eq!(result, Equal);
}
#[test]
fn cmp_test4() {
let x: &str = "人口";
let other: &str = "人";
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test5() {
let x: &str = | "人";
let other: &str = "人種";
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
}
| identifier_body |
|
cmp.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl Ord for str {
// #[inline]
// fn cmp(&self, other: &str) -> Ordering {
// for (s_b, o_b) in self.bytes().zip(other.bytes()) {
// match s_b.cmp(&o_b) {
// Greater => return Greater,
// Less => return Less,
// Equal => ()
// }
// }
//
// self.len().cmp(&other.len())
// }
// }
#[test]
fn cmp_test1() {
let x: &str = "日"; // '\u{65e5}'
let other: &str = "月"; // '\u{6708}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
#[test]
fn cmp_test2() {
let x: &str = "天"; // '\u{5929}'
let other: &str = "地"; // '\u{5730}'
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test3() {
let x: &str = "人";
let other: &str = x;
let result: Ordering = x.cmp(other);
assert_eq!(result, Equal);
}
#[test]
fn cmp_test4() {
let x: &str = "人口"; | let other: &str = "人";
let result: Ordering = x.cmp(other);
assert_eq!(result, Greater);
}
#[test]
fn cmp_test5() {
let x: &str = "人";
let other: &str = "人種";
let result: Ordering = x.cmp(other);
assert_eq!(result, Less);
}
} | random_line_split |
|
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len))); |
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
}
32... 126 => {
// OK
}
_ => {
// Totally bogus character
return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0))));
}
}
}
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams
pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>)))
}
} | } | random_line_split |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
}
32... 126 => |
_ => {
// Totally bogus character
return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0))));
}
}
}
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams
pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>)))
}
}
| {
// OK
} | conditional_block |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> | }
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams
pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>)))
}
}
| {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
}
32 ... 126 => {
// OK
}
_ => {
// Totally bogus character
return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0))));
}
} | identifier_body |
util.rs | use std::str;
use nom::{self, InputLength, IResult, Needed};
pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> {
if input.len() < len {
return Err(nom::Err::Incomplete(Needed::Size(len)));
}
for i in 0..len {
match input[i] {
0 => {
// This is the end
let s = unsafe { str::from_utf8_unchecked(&input[..i]) };
return Ok((&input[len..], s));
}
32... 126 => {
// OK
}
_ => {
// Totally bogus character
return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0))));
}
}
}
Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) }))
}
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams
pub fn | (input: &[u8]) -> IResult<&[u8], ()> {
if input.input_len() == 0 {
Ok((input, ()))
} else {
Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>)))
}
}
| naive_eof | identifier_name |
mod.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! All available `MerkleDB` indexes.
| entry::Entry,
group::Group,
iter::{Entries, IndexIterator, Keys, Values},
key_set::KeySetIndex,
list::ListIndex,
map::MapIndex,
proof_entry::ProofEntry,
sparse_list::SparseListIndex,
value_set::ValueSetIndex,
};
mod entry;
mod group;
mod iter;
mod key_set;
mod list;
mod map;
mod proof_entry;
pub mod proof_list;
pub mod proof_map;
mod sparse_list;
mod value_set; | pub use self::{ | random_line_split |
client_stress_test.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! Safe client example.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.
// com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items,
unknown_crate_types, warnings)]
#![deny(deprecated, improper_ctypes, missing_docs,
non_shorthand_field_patterns, overflowing_literals, plugin_as_library,
private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion,
unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations,
missing_debug_implementations, variant_size_differences)]
#![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))]
#![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))]
extern crate docopt;
extern crate rand;
extern crate rustc_serialize;
extern crate futures;
extern crate routing;
extern crate rust_sodium;
#[macro_use]
extern crate safe_core;
extern crate tokio_core;
extern crate maidsafe_utilities;
#[macro_use]
extern crate unwrap;
use docopt::Docopt;
use futures::Future;
use futures::stream::{self, Stream};
use futures::sync::mpsc;
use rand::{Rng, SeedableRng};
use routing::{ImmutableData, MutableData};
use rust_sodium::crypto::sign::PublicKey;
use safe_core::{Client, CoreMsg, FutureExt, event_loop};
use tokio_core::reactor::Core;
#[cfg_attr(rustfmt, rustfmt_skip)]
static USAGE: &'static str = "
Usage:
client_stress_test [options]
Options:
-i <count>, --immutable=<count> Number of ImmutableData chunks to Put and
Get [default: 100].
-m <count>, --mutable=<count> Number of MutableData chunks to Put and
Get [default: 100].
--seed <seed> Seed for a pseudo-random number generator.
--get-only Only Get the data, don't Put it.
--invite INVITATION Use the given invite.
-h, --help Display this help message and exit.
";
#[derive(Debug, RustcDecodable)]
struct Args {
flag_immutable: Option<usize>,
flag_mutable: Option<usize>,
flag_seed: Option<u32>,
flag_get_only: bool,
flag_invite: Option<String>,
flag_help: bool,
}
fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData {
let permissions = btree_map![];
let data = btree_map![];
unwrap!(MutableData::new(
rng.gen(),
type_tag,
permissions,
data,
btree_set![*public_key],
))
}
enum Data {
Mutable(MutableData),
Immutable(ImmutableData),
}
fn main() {
unwrap!(maidsafe_utilities::log::init(true));
let args: Args = Docopt::new(USAGE)
.and_then(|docopt| docopt.decode())
.unwrap_or_else(|error| error.exit());
let immutable_data_count = unwrap!(args.flag_immutable);
let mutable_data_count = unwrap!(args.flag_mutable);
let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed {
Some(seed) => [0, 0, 0, seed],
None => {
[
rand::random(),
rand::random(),
rand::random(),
rand::random(),
]
}
});
let el = unwrap!(Core::new());
let el_h = el.handle();
let (core_tx, core_rx) = mpsc::unbounded();
let (net_tx, _net_rx) = mpsc::unbounded();
// Create account
let secret_0: String = rng.gen_ascii_chars().take(20).collect();
let secret_1: String = rng.gen_ascii_chars().take(20).collect();
let mut invitation = rng.gen_ascii_chars().take(20).collect();
if let Some(i) = args.flag_invite.clone() {
invitation = i;
}
let client = if args.flag_get_only | else {
println!("\n\tAccount Creation");
println!("\t================");
println!("\nTrying to create an account...");
unwrap!(Client::registered(
&secret_0,
&secret_1,
&invitation,
el_h,
core_tx.clone(),
net_tx,
))
};
println!("Logged in successfully!");
let public_key = unwrap!(client.public_signing_key());
let core_tx_clone = core_tx.clone();
unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| {
let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count);
for _ in 0..immutable_data_count {
// Construct data
let data = ImmutableData::new(rng.gen_iter().take(1024).collect());
stored_data.push(Data::Immutable(data));
}
for _ in immutable_data_count..(immutable_data_count + mutable_data_count) {
// Construct data
let mutable_data = random_mutable_data(100000, &public_key, &mut rng);
stored_data.push(Data::Mutable(mutable_data));
}
let message = format!(
"Generated {} items ({} immutable, {} mutable)",
stored_data.len(),
immutable_data_count,
mutable_data_count
);
let underline = (0..message.len()).map(|_| "=").collect::<String>();
println!("\n\t{}\n\t{}", message, underline);
stream::iter_ok(stored_data.into_iter().enumerate())
.fold((client.clone(), args, rng), |(client, args, rng),
(i, data)| {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
match data {
Data::Immutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_idata(data.clone())
.and_then(move |_| {
println!("Put ImmutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
})
})
.and_then(move |retrieved_data| {
println!(
"Retrieved ImmutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
fut.and_then(move |data| {
// Get all the chunks again
c4.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
})
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
Data::Mutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_mdata(data.clone())
.and_then(move |_| {
println!("Put MutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
},
)
})
.and_then(move |retrieved_data| {
println!(
"Retrieved MutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
// TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here
fut.and_then(move |data| {
// Get all the chunks again
c4.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
},
)
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
}
})
.map(move |_| {
unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator()))
})
.into_box()
.into()
})));
event_loop::run(el, &client, &(), core_rx);
}
| {
unwrap!(Client::login(
&secret_0,
&secret_1,
el_h,
core_tx.clone(),
net_tx,
))
} | conditional_block |
client_stress_test.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! Safe client example.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.
// com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items,
unknown_crate_types, warnings)]
#![deny(deprecated, improper_ctypes, missing_docs,
non_shorthand_field_patterns, overflowing_literals, plugin_as_library,
private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion,
unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations,
missing_debug_implementations, variant_size_differences)]
#![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))]
#![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))]
extern crate docopt;
extern crate rand;
extern crate rustc_serialize;
extern crate futures;
extern crate routing;
extern crate rust_sodium;
#[macro_use]
extern crate safe_core;
extern crate tokio_core;
extern crate maidsafe_utilities;
#[macro_use]
extern crate unwrap;
use docopt::Docopt;
use futures::Future;
use futures::stream::{self, Stream};
use futures::sync::mpsc;
use rand::{Rng, SeedableRng};
use routing::{ImmutableData, MutableData};
use rust_sodium::crypto::sign::PublicKey;
use safe_core::{Client, CoreMsg, FutureExt, event_loop};
use tokio_core::reactor::Core;
#[cfg_attr(rustfmt, rustfmt_skip)]
static USAGE: &'static str = "
Usage:
client_stress_test [options]
Options:
-i <count>, --immutable=<count> Number of ImmutableData chunks to Put and
Get [default: 100].
-m <count>, --mutable=<count> Number of MutableData chunks to Put and
Get [default: 100].
--seed <seed> Seed for a pseudo-random number generator.
--get-only Only Get the data, don't Put it.
--invite INVITATION Use the given invite.
-h, --help Display this help message and exit.
";
#[derive(Debug, RustcDecodable)]
struct Args {
flag_immutable: Option<usize>,
flag_mutable: Option<usize>,
flag_seed: Option<u32>,
flag_get_only: bool,
flag_invite: Option<String>,
flag_help: bool,
}
fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData {
let permissions = btree_map![];
let data = btree_map![];
unwrap!(MutableData::new(
rng.gen(),
type_tag,
permissions,
data,
btree_set![*public_key],
))
}
enum Data {
Mutable(MutableData),
Immutable(ImmutableData),
}
fn main() {
unwrap!(maidsafe_utilities::log::init(true));
let args: Args = Docopt::new(USAGE)
.and_then(|docopt| docopt.decode())
.unwrap_or_else(|error| error.exit());
let immutable_data_count = unwrap!(args.flag_immutable);
let mutable_data_count = unwrap!(args.flag_mutable);
let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed {
Some(seed) => [0, 0, 0, seed],
None => {
[
rand::random(),
rand::random(),
rand::random(),
rand::random(),
]
}
});
let el = unwrap!(Core::new());
let el_h = el.handle();
let (core_tx, core_rx) = mpsc::unbounded();
let (net_tx, _net_rx) = mpsc::unbounded();
// Create account
let secret_0: String = rng.gen_ascii_chars().take(20).collect();
let secret_1: String = rng.gen_ascii_chars().take(20).collect();
let mut invitation = rng.gen_ascii_chars().take(20).collect();
if let Some(i) = args.flag_invite.clone() {
invitation = i;
}
let client = if args.flag_get_only {
unwrap!(Client::login(
&secret_0,
&secret_1,
el_h,
core_tx.clone(),
net_tx,
))
} else {
println!("\n\tAccount Creation");
println!("\t================");
println!("\nTrying to create an account...");
unwrap!(Client::registered(
&secret_0,
&secret_1,
&invitation,
el_h,
core_tx.clone(),
net_tx,
))
};
println!("Logged in successfully!");
let public_key = unwrap!(client.public_signing_key());
let core_tx_clone = core_tx.clone();
unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| {
let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count);
for _ in 0..immutable_data_count {
// Construct data
let data = ImmutableData::new(rng.gen_iter().take(1024).collect());
stored_data.push(Data::Immutable(data));
}
for _ in immutable_data_count..(immutable_data_count + mutable_data_count) {
// Construct data
let mutable_data = random_mutable_data(100000, &public_key, &mut rng);
stored_data.push(Data::Mutable(mutable_data));
}
let message = format!(
"Generated {} items ({} immutable, {} mutable)",
stored_data.len(),
immutable_data_count,
mutable_data_count
);
let underline = (0..message.len()).map(|_| "=").collect::<String>();
println!("\n\t{}\n\t{}", message, underline);
stream::iter_ok(stored_data.into_iter().enumerate())
.fold((client.clone(), args, rng), |(client, args, rng),
(i, data)| {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
match data {
Data::Immutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_idata(data.clone())
.and_then(move |_| {
println!("Put ImmutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
})
})
.and_then(move |retrieved_data| {
println!(
"Retrieved ImmutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
fut.and_then(move |data| {
// Get all the chunks again
c4.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
})
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
Data::Mutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_mdata(data.clone())
.and_then(move |_| {
println!("Put MutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
},
)
})
.and_then(move |retrieved_data| {
println!(
"Retrieved MutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
// TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here
fut.and_then(move |data| {
// Get all the chunks again
c4.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
},
)
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
}
})
.map(move |_| {
unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator()))
}) | })));
event_loop::run(el, &client, &(), core_rx);
} | .into_box()
.into() | random_line_split |
client_stress_test.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! Safe client example.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.
// com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items,
unknown_crate_types, warnings)]
#![deny(deprecated, improper_ctypes, missing_docs,
non_shorthand_field_patterns, overflowing_literals, plugin_as_library,
private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion,
unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations,
missing_debug_implementations, variant_size_differences)]
#![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))]
#![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))]
extern crate docopt;
extern crate rand;
extern crate rustc_serialize;
extern crate futures;
extern crate routing;
extern crate rust_sodium;
#[macro_use]
extern crate safe_core;
extern crate tokio_core;
extern crate maidsafe_utilities;
#[macro_use]
extern crate unwrap;
use docopt::Docopt;
use futures::Future;
use futures::stream::{self, Stream};
use futures::sync::mpsc;
use rand::{Rng, SeedableRng};
use routing::{ImmutableData, MutableData};
use rust_sodium::crypto::sign::PublicKey;
use safe_core::{Client, CoreMsg, FutureExt, event_loop};
use tokio_core::reactor::Core;
#[cfg_attr(rustfmt, rustfmt_skip)]
static USAGE: &'static str = "
Usage:
client_stress_test [options]
Options:
-i <count>, --immutable=<count> Number of ImmutableData chunks to Put and
Get [default: 100].
-m <count>, --mutable=<count> Number of MutableData chunks to Put and
Get [default: 100].
--seed <seed> Seed for a pseudo-random number generator.
--get-only Only Get the data, don't Put it.
--invite INVITATION Use the given invite.
-h, --help Display this help message and exit.
";
#[derive(Debug, RustcDecodable)]
struct Args {
flag_immutable: Option<usize>,
flag_mutable: Option<usize>,
flag_seed: Option<u32>,
flag_get_only: bool,
flag_invite: Option<String>,
flag_help: bool,
}
fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData {
let permissions = btree_map![];
let data = btree_map![];
unwrap!(MutableData::new(
rng.gen(),
type_tag,
permissions,
data,
btree_set![*public_key],
))
}
enum Data {
Mutable(MutableData),
Immutable(ImmutableData),
}
fn | () {
unwrap!(maidsafe_utilities::log::init(true));
let args: Args = Docopt::new(USAGE)
.and_then(|docopt| docopt.decode())
.unwrap_or_else(|error| error.exit());
let immutable_data_count = unwrap!(args.flag_immutable);
let mutable_data_count = unwrap!(args.flag_mutable);
let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed {
Some(seed) => [0, 0, 0, seed],
None => {
[
rand::random(),
rand::random(),
rand::random(),
rand::random(),
]
}
});
let el = unwrap!(Core::new());
let el_h = el.handle();
let (core_tx, core_rx) = mpsc::unbounded();
let (net_tx, _net_rx) = mpsc::unbounded();
// Create account
let secret_0: String = rng.gen_ascii_chars().take(20).collect();
let secret_1: String = rng.gen_ascii_chars().take(20).collect();
let mut invitation = rng.gen_ascii_chars().take(20).collect();
if let Some(i) = args.flag_invite.clone() {
invitation = i;
}
let client = if args.flag_get_only {
unwrap!(Client::login(
&secret_0,
&secret_1,
el_h,
core_tx.clone(),
net_tx,
))
} else {
println!("\n\tAccount Creation");
println!("\t================");
println!("\nTrying to create an account...");
unwrap!(Client::registered(
&secret_0,
&secret_1,
&invitation,
el_h,
core_tx.clone(),
net_tx,
))
};
println!("Logged in successfully!");
let public_key = unwrap!(client.public_signing_key());
let core_tx_clone = core_tx.clone();
unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| {
let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count);
for _ in 0..immutable_data_count {
// Construct data
let data = ImmutableData::new(rng.gen_iter().take(1024).collect());
stored_data.push(Data::Immutable(data));
}
for _ in immutable_data_count..(immutable_data_count + mutable_data_count) {
// Construct data
let mutable_data = random_mutable_data(100000, &public_key, &mut rng);
stored_data.push(Data::Mutable(mutable_data));
}
let message = format!(
"Generated {} items ({} immutable, {} mutable)",
stored_data.len(),
immutable_data_count,
mutable_data_count
);
let underline = (0..message.len()).map(|_| "=").collect::<String>();
println!("\n\t{}\n\t{}", message, underline);
stream::iter_ok(stored_data.into_iter().enumerate())
.fold((client.clone(), args, rng), |(client, args, rng),
(i, data)| {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
match data {
Data::Immutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_idata(data.clone())
.and_then(move |_| {
println!("Put ImmutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
})
})
.and_then(move |retrieved_data| {
println!(
"Retrieved ImmutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
fut.and_then(move |data| {
// Get all the chunks again
c4.get_idata(*data.name()).map(move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
})
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
Data::Mutable(data) => {
let fut = if args.flag_get_only {
futures::finished(data).into_box()
} else {
// Put the data to the network
c2.put_mdata(data.clone())
.and_then(move |_| {
println!("Put MutableData chunk #{}: {:?}", i, data.name());
// Get the data
c3.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
retrieved_data
},
)
})
.and_then(move |retrieved_data| {
println!(
"Retrieved MutableData chunk #{}: {:?}",
i,
retrieved_data.name()
);
Ok(retrieved_data)
})
.into_box()
};
// TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here
fut.and_then(move |data| {
// Get all the chunks again
c4.get_mdata_shell(*data.name(), data.tag()).map(
move |retrieved_data| {
assert_eq!(data, retrieved_data);
println!("Retrieved chunk #{}: {:?}", i, data.name());
(args, rng)
},
)
}).map(move |(args, rng)| (client, args, rng))
.map_err(|e| println!("Error: {:?}", e))
.into_box()
}
}
})
.map(move |_| {
unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator()))
})
.into_box()
.into()
})));
event_loop::run(el, &client, &(), core_rx);
}
| main | identifier_name |
page.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::js::{JS, Root};
use dom::document::Document;
use dom::window::Window;
use msg::constellation_msg::PipelineId;
use std::cell::Cell;
use std::rc::Rc;
/// Encapsulates a handle to a frame in a frame tree.
#[derive(JSTraceable, HeapSizeOf)]
#[allow(unrooted_must_root)] // FIXME(#6687) this is wrong
pub struct Page {
/// Pipeline id associated with this page. |
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
// Child Pages.
pub children: DOMRefCell<Vec<Rc<Page>>>,
}
pub struct PageIterator {
stack: Vec<Rc<Page>>,
}
pub trait IterablePage {
fn iter(&self) -> PageIterator;
fn find(&self, id: PipelineId) -> Option<Rc<Page>>;
}
impl IterablePage for Rc<Page> {
fn iter(&self) -> PageIterator {
PageIterator {
stack: vec!(self.clone()),
}
}
fn find(&self, id: PipelineId) -> Option<Rc<Page>> {
if self.id == id { return Some(self.clone()); }
for page in &*self.children.borrow() {
let found = page.find(id);
if found.is_some() { return found; }
}
None
}
}
impl Page {
pub fn new(id: PipelineId) -> Page {
Page {
id: id,
frame: DOMRefCell::new(None),
needs_reflow: Cell::new(true),
children: DOMRefCell::new(vec!()),
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn window(&self) -> Root<Window> {
self.frame.borrow().as_ref().unwrap().window.root()
}
pub fn document(&self) -> Root<Document> {
self.frame.borrow().as_ref().unwrap().document.root()
}
// must handle root case separately
pub fn remove(&self, id: PipelineId) -> Option<Rc<Page>> {
let remove_idx = {
self.children
.borrow_mut()
.iter_mut()
.position(|page_tree| page_tree.id == id)
};
match remove_idx {
Some(idx) => Some(self.children.borrow_mut().remove(idx)),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|page_tree| page_tree.remove(id))
.next()
}
}
}
}
impl Iterator for PageIterator {
type Item = Rc<Page>;
fn next(&mut self) -> Option<Rc<Page>> {
match self.stack.pop() {
Some(next) => {
for child in &*next.children.borrow() {
self.stack.push(child.clone());
}
Some(next)
},
None => None,
}
}
}
impl Page {
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn set_frame(&self, frame: Option<Frame>) {
*self.frame.borrow_mut() = frame;
}
}
/// Information for one frame in the browsing context.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct Frame {
/// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame.
pub window: JS<Window>,
} | id: PipelineId,
/// The outermost frame containing the document and window.
frame: DOMRefCell<Option<Frame>>, | random_line_split |
page.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::js::{JS, Root};
use dom::document::Document;
use dom::window::Window;
use msg::constellation_msg::PipelineId;
use std::cell::Cell;
use std::rc::Rc;
/// Encapsulates a handle to a frame in a frame tree.
#[derive(JSTraceable, HeapSizeOf)]
#[allow(unrooted_must_root)] // FIXME(#6687) this is wrong
pub struct Page {
/// Pipeline id associated with this page.
id: PipelineId,
/// The outermost frame containing the document and window.
frame: DOMRefCell<Option<Frame>>,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
// Child Pages.
pub children: DOMRefCell<Vec<Rc<Page>>>,
}
pub struct PageIterator {
stack: Vec<Rc<Page>>,
}
pub trait IterablePage {
fn iter(&self) -> PageIterator;
fn find(&self, id: PipelineId) -> Option<Rc<Page>>;
}
impl IterablePage for Rc<Page> {
fn iter(&self) -> PageIterator {
PageIterator {
stack: vec!(self.clone()),
}
}
fn find(&self, id: PipelineId) -> Option<Rc<Page>> {
if self.id == id { return Some(self.clone()); }
for page in &*self.children.borrow() {
let found = page.find(id);
if found.is_some() { return found; }
}
None
}
}
impl Page {
pub fn new(id: PipelineId) -> Page {
Page {
id: id,
frame: DOMRefCell::new(None),
needs_reflow: Cell::new(true),
children: DOMRefCell::new(vec!()),
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn window(&self) -> Root<Window> {
self.frame.borrow().as_ref().unwrap().window.root()
}
pub fn document(&self) -> Root<Document> {
self.frame.borrow().as_ref().unwrap().document.root()
}
// must handle root case separately
pub fn | (&self, id: PipelineId) -> Option<Rc<Page>> {
let remove_idx = {
self.children
.borrow_mut()
.iter_mut()
.position(|page_tree| page_tree.id == id)
};
match remove_idx {
Some(idx) => Some(self.children.borrow_mut().remove(idx)),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|page_tree| page_tree.remove(id))
.next()
}
}
}
}
impl Iterator for PageIterator {
type Item = Rc<Page>;
fn next(&mut self) -> Option<Rc<Page>> {
match self.stack.pop() {
Some(next) => {
for child in &*next.children.borrow() {
self.stack.push(child.clone());
}
Some(next)
},
None => None,
}
}
}
impl Page {
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn set_frame(&self, frame: Option<Frame>) {
*self.frame.borrow_mut() = frame;
}
}
/// Information for one frame in the browsing context.
#[derive(JSTraceable, HeapSizeOf)]
#[must_root]
pub struct Frame {
/// The document for this frame.
pub document: JS<Document>,
/// The window object for this frame.
pub window: JS<Window>,
}
| remove | identifier_name |
clipboard_provider.rs | use msg::constellation_msg::ConstellationChan;
use msg::constellation_msg::Msg as ConstellationMsg;
use collections::borrow::ToOwned;
use std::sync::mpsc::channel;
pub trait ClipboardProvider {
// blocking method to get the clipboard contents
fn get_clipboard_contents(&mut self) -> String;
// blocking method to set the clipboard contents
fn set_clipboard_contents(&mut self, &str);
}
impl ClipboardProvider for ConstellationChan {
fn get_clipboard_contents(&mut self) -> String {
let (tx, rx) = channel();
self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap();
rx.recv().unwrap()
}
fn set_clipboard_contents(&mut self, _: &str) {
panic!("not yet implemented");
}
}
pub struct DummyClipboardContext {
content: String
}
impl DummyClipboardContext {
pub fn new(s: &str) -> DummyClipboardContext {
DummyClipboardContext {
content: s.to_owned()
}
}
}
impl ClipboardProvider for DummyClipboardContext {
fn get_clipboard_contents(&mut self) -> String {
self.content.clone()
}
fn set_clipboard_contents(&mut self, s: &str) {
self.content = s.to_owned();
}
} | /* 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/. */
| random_line_split |
|
clipboard_provider.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 msg::constellation_msg::ConstellationChan;
use msg::constellation_msg::Msg as ConstellationMsg;
use collections::borrow::ToOwned;
use std::sync::mpsc::channel;
pub trait ClipboardProvider {
// blocking method to get the clipboard contents
fn get_clipboard_contents(&mut self) -> String;
// blocking method to set the clipboard contents
fn set_clipboard_contents(&mut self, &str);
}
impl ClipboardProvider for ConstellationChan {
fn get_clipboard_contents(&mut self) -> String {
let (tx, rx) = channel();
self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap();
rx.recv().unwrap()
}
fn | (&mut self, _: &str) {
panic!("not yet implemented");
}
}
pub struct DummyClipboardContext {
content: String
}
impl DummyClipboardContext {
pub fn new(s: &str) -> DummyClipboardContext {
DummyClipboardContext {
content: s.to_owned()
}
}
}
impl ClipboardProvider for DummyClipboardContext {
fn get_clipboard_contents(&mut self) -> String {
self.content.clone()
}
fn set_clipboard_contents(&mut self, s: &str) {
self.content = s.to_owned();
}
}
| set_clipboard_contents | identifier_name |
clipboard_provider.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 msg::constellation_msg::ConstellationChan;
use msg::constellation_msg::Msg as ConstellationMsg;
use collections::borrow::ToOwned;
use std::sync::mpsc::channel;
pub trait ClipboardProvider {
// blocking method to get the clipboard contents
fn get_clipboard_contents(&mut self) -> String;
// blocking method to set the clipboard contents
fn set_clipboard_contents(&mut self, &str);
}
impl ClipboardProvider for ConstellationChan {
fn get_clipboard_contents(&mut self) -> String {
let (tx, rx) = channel();
self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap();
rx.recv().unwrap()
}
fn set_clipboard_contents(&mut self, _: &str) |
}
pub struct DummyClipboardContext {
content: String
}
impl DummyClipboardContext {
pub fn new(s: &str) -> DummyClipboardContext {
DummyClipboardContext {
content: s.to_owned()
}
}
}
impl ClipboardProvider for DummyClipboardContext {
fn get_clipboard_contents(&mut self) -> String {
self.content.clone()
}
fn set_clipboard_contents(&mut self, s: &str) {
self.content = s.to_owned();
}
}
| {
panic!("not yet implemented");
} | identifier_body |
codec.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::errors::*;
use crate::geometry::Cube;
use crate::proto;
use nalgebra::{Point3, Scalar, Vector3};
use num::clamp;
use std::fmt::Debug;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum | {
Uint8,
Uint16,
Float32,
Float64,
}
impl PositionEncoding {
pub fn new(bounding_cube: &Cube, resolution: f64) -> PositionEncoding {
let min_bits = (bounding_cube.edge_length() / resolution).log2() as u32 + 1;
match min_bits {
0..=8 => PositionEncoding::Uint8,
9..=16 => PositionEncoding::Uint16,
// Capping at 24 keeps the worst resolution at ~1 mm for an edge length of ~8389 km.
17..=24 => PositionEncoding::Float32,
_ => PositionEncoding::Float64,
}
}
// TODO(sirver): Returning a Result here makes this function more expensive than needed - since
// we require stack space for the full Result. This should be fixable to moving to failure.
pub fn from_proto(proto: proto::PositionEncoding) -> Result<Self> {
match proto {
proto::PositionEncoding::Uint8 => Ok(PositionEncoding::Uint8),
proto::PositionEncoding::Uint16 => Ok(PositionEncoding::Uint16),
proto::PositionEncoding::Float32 => Ok(PositionEncoding::Float32),
proto::PositionEncoding::Float64 => Ok(PositionEncoding::Float64),
proto::PositionEncoding::INVALID => Err(ErrorKind::InvalidInput(
"Proto: PositionEncoding is invalid".to_string(),
)
.into()),
}
}
pub fn to_proto(&self) -> proto::PositionEncoding {
match *self {
PositionEncoding::Uint8 => proto::PositionEncoding::Uint8,
PositionEncoding::Uint16 => proto::PositionEncoding::Uint16,
PositionEncoding::Float32 => proto::PositionEncoding::Float32,
PositionEncoding::Float64 => proto::PositionEncoding::Float64,
}
}
pub fn bytes_per_coordinate(&self) -> usize {
match *self {
PositionEncoding::Uint8 => 1,
PositionEncoding::Uint16 => 2,
PositionEncoding::Float32 => 4,
PositionEncoding::Float64 => 8,
}
}
}
/// The _encode and _decode functions are not methods of this type, because
/// we are sometimes able to pull the match outside the inner loop.
#[derive(Clone)]
pub enum Encoding {
Plain,
ScaledToCube(Point3<f64>, f64, PositionEncoding),
}
/// Encode float as integer.
pub fn fixpoint_encode<T>(value: f64, min: f64, edge_length: f64) -> T
where
T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let value =
clamp((value - min) / edge_length, 0., 1.) * nalgebra::convert::<T, f64>(T::max_value());
nalgebra::try_convert(value).unwrap()
}
/// Encode float as f32 or f64 unit interval float.
pub fn _encode<T>(value: f64, min: f64, edge_length: f64) -> T
where
T: simba::scalar::SubsetOf<f64>,
{
nalgebra::try_convert(clamp((value - min) / edge_length, 0., 1.)).unwrap()
}
pub fn vec3_fixpoint_encode<T>(
value: &Point3<f64>,
min: &Point3<f64>,
edge_length: f64,
) -> Vector3<T>
where
T: Scalar + num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let scale: f64 = nalgebra::convert(T::max_value());
let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0);
nalgebra::try_convert(scale * value).unwrap()
}
pub fn vec3_encode<T>(value: &Point3<f64>, min: &Point3<f64>, edge_length: f64) -> Vector3<T>
where
T: Scalar + simba::scalar::SubsetOf<f64>,
{
let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0);
nalgebra::try_convert(value).unwrap()
}
/// Decode integer as float.
pub fn fixpoint_decode<T>(value: T, min: f64, edge_length: f64) -> f64
where
T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let max: f64 = nalgebra::convert(T::max_value());
let v: f64 = nalgebra::convert(value);
(v / max).mul_add(edge_length, min)
}
/// Decode f32 or f64 unit interval float as f64.
pub fn decode<T>(value: T, min: f64, edge_length: f64) -> f64
where
T: simba::scalar::SubsetOf<f64>,
{
nalgebra::convert::<T, f64>(value).mul_add(edge_length, min)
}
// Careful: num's (or nalgebra's) clamp accepts Vector3 too, but does not work elementwise like this
fn clamp_elementwise(value: Vector3<f64>, lower: f64, upper: f64) -> Vector3<f64> {
Vector3::new(
clamp(value.x, lower, upper),
clamp(value.y, lower, upper),
clamp(value.z, lower, upper),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_scalar() {
let value = 41.33333;
let min = 40.0;
let edge_length = 2.0;
let value_f32 = _encode::<f32>(value, min, edge_length);
let value_f32_decoded = decode(value_f32, min, edge_length);
// We could use the approx crate here and elsewhere
assert!(
(value_f32_decoded - value).abs() < 1e-7,
"Reconstructed from f32: {}, original: {}",
value_f32_decoded,
value
);
let value_f64 = _encode::<f64>(value, min, edge_length);
let value_f64_decoded = decode(value_f64, min, edge_length);
assert!(
(value_f64_decoded - value).abs() < 1e-14,
"Reconstructed from f64: {}, original: {}",
value_f64_decoded,
value
);
}
#[test]
fn fixpoint_scalar() {
let value = 41.33333;
let min = 40.0;
let edge_length = 2.0;
let value_u8 = fixpoint_encode::<u8>(value, min, edge_length);
let value_u8_decoded = fixpoint_decode(value_u8, min, edge_length);
assert!(
(value_u8_decoded - value).abs() < 1e-2,
"Reconstructed from u8: {}, original: {}",
value_u8_decoded,
value
);
let value_u16 = fixpoint_encode::<u16>(value, min, edge_length);
let value_u16_decoded = fixpoint_decode(value_u16, min, edge_length);
assert!(
(value_u16_decoded - value).abs() < 1e-4,
"Reconstructed from u16: {}, original: {}",
value_u16_decoded,
value
);
let value_u32 = fixpoint_encode::<u32>(value, min, edge_length);
let value_u32_decoded = fixpoint_decode(value_u32, min, edge_length);
assert!(
(value_u32_decoded - value).abs() < 1e-7,
"Reconstructed from u32: {}, original: {}",
value_u32_decoded,
value
);
}
}
| PositionEncoding | identifier_name |
codec.rs | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::errors::*;
use crate::geometry::Cube;
use crate::proto;
use nalgebra::{Point3, Scalar, Vector3};
use num::clamp;
use std::fmt::Debug;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PositionEncoding {
Uint8,
Uint16,
Float32,
Float64,
}
impl PositionEncoding {
pub fn new(bounding_cube: &Cube, resolution: f64) -> PositionEncoding {
let min_bits = (bounding_cube.edge_length() / resolution).log2() as u32 + 1;
match min_bits {
0..=8 => PositionEncoding::Uint8,
9..=16 => PositionEncoding::Uint16, | // Capping at 24 keeps the worst resolution at ~1 mm for an edge length of ~8389 km.
17..=24 => PositionEncoding::Float32,
_ => PositionEncoding::Float64,
}
}
// TODO(sirver): Returning a Result here makes this function more expensive than needed - since
// we require stack space for the full Result. This should be fixable to moving to failure.
pub fn from_proto(proto: proto::PositionEncoding) -> Result<Self> {
match proto {
proto::PositionEncoding::Uint8 => Ok(PositionEncoding::Uint8),
proto::PositionEncoding::Uint16 => Ok(PositionEncoding::Uint16),
proto::PositionEncoding::Float32 => Ok(PositionEncoding::Float32),
proto::PositionEncoding::Float64 => Ok(PositionEncoding::Float64),
proto::PositionEncoding::INVALID => Err(ErrorKind::InvalidInput(
"Proto: PositionEncoding is invalid".to_string(),
)
.into()),
}
}
pub fn to_proto(&self) -> proto::PositionEncoding {
match *self {
PositionEncoding::Uint8 => proto::PositionEncoding::Uint8,
PositionEncoding::Uint16 => proto::PositionEncoding::Uint16,
PositionEncoding::Float32 => proto::PositionEncoding::Float32,
PositionEncoding::Float64 => proto::PositionEncoding::Float64,
}
}
pub fn bytes_per_coordinate(&self) -> usize {
match *self {
PositionEncoding::Uint8 => 1,
PositionEncoding::Uint16 => 2,
PositionEncoding::Float32 => 4,
PositionEncoding::Float64 => 8,
}
}
}
/// The _encode and _decode functions are not methods of this type, because
/// we are sometimes able to pull the match outside the inner loop.
#[derive(Clone)]
pub enum Encoding {
Plain,
ScaledToCube(Point3<f64>, f64, PositionEncoding),
}
/// Encode float as integer.
pub fn fixpoint_encode<T>(value: f64, min: f64, edge_length: f64) -> T
where
T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let value =
clamp((value - min) / edge_length, 0., 1.) * nalgebra::convert::<T, f64>(T::max_value());
nalgebra::try_convert(value).unwrap()
}
/// Encode float as f32 or f64 unit interval float.
pub fn _encode<T>(value: f64, min: f64, edge_length: f64) -> T
where
T: simba::scalar::SubsetOf<f64>,
{
nalgebra::try_convert(clamp((value - min) / edge_length, 0., 1.)).unwrap()
}
pub fn vec3_fixpoint_encode<T>(
value: &Point3<f64>,
min: &Point3<f64>,
edge_length: f64,
) -> Vector3<T>
where
T: Scalar + num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let scale: f64 = nalgebra::convert(T::max_value());
let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0);
nalgebra::try_convert(scale * value).unwrap()
}
pub fn vec3_encode<T>(value: &Point3<f64>, min: &Point3<f64>, edge_length: f64) -> Vector3<T>
where
T: Scalar + simba::scalar::SubsetOf<f64>,
{
let value = clamp_elementwise((value - min) / edge_length, 0.0, 1.0);
nalgebra::try_convert(value).unwrap()
}
/// Decode integer as float.
pub fn fixpoint_decode<T>(value: T, min: f64, edge_length: f64) -> f64
where
T: num_traits::PrimInt + num_traits::Bounded + simba::scalar::SubsetOf<f64>,
{
let max: f64 = nalgebra::convert(T::max_value());
let v: f64 = nalgebra::convert(value);
(v / max).mul_add(edge_length, min)
}
/// Decode f32 or f64 unit interval float as f64.
pub fn decode<T>(value: T, min: f64, edge_length: f64) -> f64
where
T: simba::scalar::SubsetOf<f64>,
{
nalgebra::convert::<T, f64>(value).mul_add(edge_length, min)
}
// Careful: num's (or nalgebra's) clamp accepts Vector3 too, but does not work elementwise like this
fn clamp_elementwise(value: Vector3<f64>, lower: f64, upper: f64) -> Vector3<f64> {
Vector3::new(
clamp(value.x, lower, upper),
clamp(value.y, lower, upper),
clamp(value.z, lower, upper),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_scalar() {
let value = 41.33333;
let min = 40.0;
let edge_length = 2.0;
let value_f32 = _encode::<f32>(value, min, edge_length);
let value_f32_decoded = decode(value_f32, min, edge_length);
// We could use the approx crate here and elsewhere
assert!(
(value_f32_decoded - value).abs() < 1e-7,
"Reconstructed from f32: {}, original: {}",
value_f32_decoded,
value
);
let value_f64 = _encode::<f64>(value, min, edge_length);
let value_f64_decoded = decode(value_f64, min, edge_length);
assert!(
(value_f64_decoded - value).abs() < 1e-14,
"Reconstructed from f64: {}, original: {}",
value_f64_decoded,
value
);
}
#[test]
fn fixpoint_scalar() {
let value = 41.33333;
let min = 40.0;
let edge_length = 2.0;
let value_u8 = fixpoint_encode::<u8>(value, min, edge_length);
let value_u8_decoded = fixpoint_decode(value_u8, min, edge_length);
assert!(
(value_u8_decoded - value).abs() < 1e-2,
"Reconstructed from u8: {}, original: {}",
value_u8_decoded,
value
);
let value_u16 = fixpoint_encode::<u16>(value, min, edge_length);
let value_u16_decoded = fixpoint_decode(value_u16, min, edge_length);
assert!(
(value_u16_decoded - value).abs() < 1e-4,
"Reconstructed from u16: {}, original: {}",
value_u16_decoded,
value
);
let value_u32 = fixpoint_encode::<u32>(value, min, edge_length);
let value_u32_decoded = fixpoint_decode(value_u32, min, edge_length);
assert!(
(value_u32_decoded - value).abs() < 1e-7,
"Reconstructed from u32: {}, original: {}",
value_u32_decoded,
value
);
}
} | random_line_split |
|
lib.rs | #![cfg_attr(feature = "nightly", feature(test))]
#![feature(nll, try_trait)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;
extern crate syntax;
#[macro_use]
extern crate derive_more;
extern crate rls_span;
#[macro_use]
mod testutils;
#[macro_use]
mod util;
mod ast;
mod ast_types;
mod codecleaner;
mod codeiter;
mod core;
mod fileres;
mod matchers;
#[cfg(feature = "metadata")]
mod metadata;
mod nameres;
mod primitive;
mod project_model;
mod scopes;
mod snippets;
mod typeinf;
| complete_from_file, complete_fully_qualified_name, find_definition, is_use_stmt, to_coords,
to_point,
};
pub use core::{
BytePos, ByteRange, Coordinate, FileCache, FileLoader, Location, Match, MatchType, Session,
};
pub use primitive::PrimKind;
pub use project_model::ProjectModelProvider;
pub use snippets::snippet_for_match;
pub use util::expand_ident;
pub use util::{get_rust_src_path, RustSrcPathError};
#[cfg(all(feature = "nightly", test))]
mod benches; | pub use ast_types::PathSearch;
pub use core::{ | random_line_split |
class-impl-very-parameterized-trait.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.
use std::cmp;
#[deriving(Show)]
enum cat_type { tuxedo, tabby, tortoiseshell }
impl cmp::PartialEq for cat_type {
fn eq(&self, other: &cat_type) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &cat_type) -> bool {!(*self).eq(other) }
}
// Very silly -- this just returns the value of the name field
// for any int value that's less than the meows field
// ok: T should be in scope when resolving the trait ref for map
struct cat<T> {
// Yes, you can have negative meows
meows : int,
how_hungry : int,
name : T,
}
impl<T> cat<T> {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} else {
println!("Not hungry!");
return false;
}
}
fn len(&self) -> uint { self.meows as uint }
fn is_empty(&self) -> bool { self.meows == 0 }
fn clear(&mut self) {}
fn contains_key(&self, k: &int) -> bool |
fn find(&self, k: &int) -> Option<&T> {
if *k <= self.meows {
Some(&self.name)
} else {
None
}
}
fn insert(&mut self, k: int, _: T) -> bool {
self.meows += k;
true
}
fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() }
fn remove(&mut self, k: &int) -> bool {
if self.find(k).is_some() {
self.meows -= *k; true
} else {
false
}
}
fn pop(&mut self, _k: &int) -> Option<T> { panic!() }
fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() }
}
impl<T> cat<T> {
pub fn get(&self, k: &int) -> &T {
match self.find(k) {
Some(v) => { v }
None => { panic!("epic fail"); }
}
}
pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
cat{meows: in_x, how_hungry: in_y, name: in_name }
}
}
impl<T> cat<T> {
fn meow(&mut self) {
self.meows += 1;
println!("Meow {}", self.meows);
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
pub fn main() {
let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string());
for _ in range(1u, 5) { nyan.speak(); }
assert!(*nyan.find(&1).unwrap() == "nyan".to_string());
assert_eq!(nyan.find(&10), None);
let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo);
for _ in range(0u, 6) { spotty.speak(); }
assert_eq!(spotty.len(), 8);
assert!((spotty.contains_key(&2)));
assert_eq!(spotty.get(&3), &cat_type::tuxedo);
}
| { *k <= self.meows } | identifier_body |
class-impl-very-parameterized-trait.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.
use std::cmp;
#[deriving(Show)]
enum cat_type { tuxedo, tabby, tortoiseshell }
impl cmp::PartialEq for cat_type {
fn eq(&self, other: &cat_type) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &cat_type) -> bool {!(*self).eq(other) }
}
// Very silly -- this just returns the value of the name field
// for any int value that's less than the meows field
// ok: T should be in scope when resolving the trait ref for map
struct | <T> {
// Yes, you can have negative meows
meows : int,
how_hungry : int,
name : T,
}
impl<T> cat<T> {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} else {
println!("Not hungry!");
return false;
}
}
fn len(&self) -> uint { self.meows as uint }
fn is_empty(&self) -> bool { self.meows == 0 }
fn clear(&mut self) {}
fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
fn find(&self, k: &int) -> Option<&T> {
if *k <= self.meows {
Some(&self.name)
} else {
None
}
}
fn insert(&mut self, k: int, _: T) -> bool {
self.meows += k;
true
}
fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() }
fn remove(&mut self, k: &int) -> bool {
if self.find(k).is_some() {
self.meows -= *k; true
} else {
false
}
}
fn pop(&mut self, _k: &int) -> Option<T> { panic!() }
fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() }
}
impl<T> cat<T> {
pub fn get(&self, k: &int) -> &T {
match self.find(k) {
Some(v) => { v }
None => { panic!("epic fail"); }
}
}
pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
cat{meows: in_x, how_hungry: in_y, name: in_name }
}
}
impl<T> cat<T> {
fn meow(&mut self) {
self.meows += 1;
println!("Meow {}", self.meows);
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
pub fn main() {
let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string());
for _ in range(1u, 5) { nyan.speak(); }
assert!(*nyan.find(&1).unwrap() == "nyan".to_string());
assert_eq!(nyan.find(&10), None);
let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo);
for _ in range(0u, 6) { spotty.speak(); }
assert_eq!(spotty.len(), 8);
assert!((spotty.contains_key(&2)));
assert_eq!(spotty.get(&3), &cat_type::tuxedo);
}
| cat | identifier_name |
class-impl-very-parameterized-trait.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.
use std::cmp;
#[deriving(Show)]
enum cat_type { tuxedo, tabby, tortoiseshell }
impl cmp::PartialEq for cat_type {
fn eq(&self, other: &cat_type) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &cat_type) -> bool {!(*self).eq(other) }
}
// Very silly -- this just returns the value of the name field
// for any int value that's less than the meows field
// ok: T should be in scope when resolving the trait ref for map
struct cat<T> {
// Yes, you can have negative meows
meows : int,
how_hungry : int,
name : T,
}
impl<T> cat<T> {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} else {
println!("Not hungry!");
return false;
}
}
fn len(&self) -> uint { self.meows as uint }
fn is_empty(&self) -> bool { self.meows == 0 }
fn clear(&mut self) {}
fn contains_key(&self, k: &int) -> bool { *k <= self.meows }
fn find(&self, k: &int) -> Option<&T> {
if *k <= self.meows {
Some(&self.name)
} else {
None
}
}
fn insert(&mut self, k: int, _: T) -> bool {
self.meows += k;
true
}
fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() }
fn remove(&mut self, k: &int) -> bool {
if self.find(k).is_some() {
self.meows -= *k; true
} else {
false
}
}
fn pop(&mut self, _k: &int) -> Option<T> { panic!() }
fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() }
}
impl<T> cat<T> {
pub fn get(&self, k: &int) -> &T {
match self.find(k) {
Some(v) => { v }
None => { panic!("epic fail"); }
} | pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> {
cat{meows: in_x, how_hungry: in_y, name: in_name }
}
}
impl<T> cat<T> {
fn meow(&mut self) {
self.meows += 1;
println!("Meow {}", self.meows);
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
pub fn main() {
let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_string());
for _ in range(1u, 5) { nyan.speak(); }
assert!(*nyan.find(&1).unwrap() == "nyan".to_string());
assert_eq!(nyan.find(&10), None);
let mut spotty: cat<cat_type> = cat::new(2, 57, cat_type::tuxedo);
for _ in range(0u, 6) { spotty.speak(); }
assert_eq!(spotty.len(), 8);
assert!((spotty.contains_key(&2)));
assert_eq!(spotty.get(&3), &cat_type::tuxedo);
} | }
| random_line_split |
async_cmd_desc_map.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::BTreeMap;
use crate::virtio::queue::DescriptorChain;
use crate::virtio::video::command::QueueType;
use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag};
use crate::virtio::video::error::VideoError;
use crate::virtio::video::protocol;
use crate::virtio::video::response::CmdResponse;
/// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous
/// responses will be written.
#[derive(Default)]
pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>);
impl AsyncCmdDescMap {
pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) {
self.0.insert(tag, descriptor_chain);
}
pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> {
self.0.remove(tag)
}
/// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target
/// stream `target_stream_id`.
/// If `target_queue_type` is specified, then only create the requests for the specified queue.
/// Otherwise, create the requests for both input and output queue.
/// If `processing_tag` is specified, a cancellation request for that tag will
/// not be created.
pub fn create_cancellation_responses(
&self,
target_stream_id: &u32,
target_queue_type: Option<QueueType>,
processing_tag: Option<AsyncCmdTag>,
) -> Vec<AsyncCmdResponse> {
let mut responses = vec![];
for tag in self.0.keys().filter(|&&k| Some(k)!= processing_tag) {
match tag {
AsyncCmdTag::Queue {
stream_id,
queue_type,
..
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
responses.push(AsyncCmdResponse::from_response(
*tag,
CmdResponse::ResourceQueue {
timestamp: 0,
flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR,
size: 0,
},
));
}
AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => {
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
AsyncCmdTag::Clear {
stream_id,
queue_type,
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
|
_ => {
// Keep commands for other streams.
}
}
}
responses
}
}
| {
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
} | conditional_block |
async_cmd_desc_map.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::BTreeMap;
use crate::virtio::queue::DescriptorChain;
use crate::virtio::video::command::QueueType;
use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag};
use crate::virtio::video::error::VideoError;
use crate::virtio::video::protocol;
use crate::virtio::video::response::CmdResponse;
/// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous
/// responses will be written.
#[derive(Default)]
pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>);
| impl AsyncCmdDescMap {
pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) {
self.0.insert(tag, descriptor_chain);
}
pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> {
self.0.remove(tag)
}
/// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target
/// stream `target_stream_id`.
/// If `target_queue_type` is specified, then only create the requests for the specified queue.
/// Otherwise, create the requests for both input and output queue.
/// If `processing_tag` is specified, a cancellation request for that tag will
/// not be created.
pub fn create_cancellation_responses(
&self,
target_stream_id: &u32,
target_queue_type: Option<QueueType>,
processing_tag: Option<AsyncCmdTag>,
) -> Vec<AsyncCmdResponse> {
let mut responses = vec![];
for tag in self.0.keys().filter(|&&k| Some(k)!= processing_tag) {
match tag {
AsyncCmdTag::Queue {
stream_id,
queue_type,
..
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
responses.push(AsyncCmdResponse::from_response(
*tag,
CmdResponse::ResourceQueue {
timestamp: 0,
flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR,
size: 0,
},
));
}
AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => {
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
AsyncCmdTag::Clear {
stream_id,
queue_type,
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
_ => {
// Keep commands for other streams.
}
}
}
responses
}
} | random_line_split |
|
async_cmd_desc_map.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::BTreeMap;
use crate::virtio::queue::DescriptorChain;
use crate::virtio::video::command::QueueType;
use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag};
use crate::virtio::video::error::VideoError;
use crate::virtio::video::protocol;
use crate::virtio::video::response::CmdResponse;
/// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous
/// responses will be written.
#[derive(Default)]
pub struct AsyncCmdDescMap(BTreeMap<AsyncCmdTag, DescriptorChain>);
impl AsyncCmdDescMap {
pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) {
self.0.insert(tag, descriptor_chain);
}
pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> {
self.0.remove(tag)
}
/// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target
/// stream `target_stream_id`.
/// If `target_queue_type` is specified, then only create the requests for the specified queue.
/// Otherwise, create the requests for both input and output queue.
/// If `processing_tag` is specified, a cancellation request for that tag will
/// not be created.
pub fn create_cancellation_responses(
&self,
target_stream_id: &u32,
target_queue_type: Option<QueueType>,
processing_tag: Option<AsyncCmdTag>,
) -> Vec<AsyncCmdResponse> | AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => {
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
AsyncCmdTag::Clear {
stream_id,
queue_type,
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
_ => {
// Keep commands for other streams.
}
}
}
responses
}
}
| {
let mut responses = vec![];
for tag in self.0.keys().filter(|&&k| Some(k) != processing_tag) {
match tag {
AsyncCmdTag::Queue {
stream_id,
queue_type,
..
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
responses.push(AsyncCmdResponse::from_response(
*tag,
CmdResponse::ResourceQueue {
timestamp: 0,
flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR,
size: 0,
},
));
} | identifier_body |
async_cmd_desc_map.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::BTreeMap;
use crate::virtio::queue::DescriptorChain;
use crate::virtio::video::command::QueueType;
use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag};
use crate::virtio::video::error::VideoError;
use crate::virtio::video::protocol;
use crate::virtio::video::response::CmdResponse;
/// AsyncCmdDescMap is a BTreeMap which stores descriptor chains in which asynchronous
/// responses will be written.
#[derive(Default)]
pub struct | (BTreeMap<AsyncCmdTag, DescriptorChain>);
impl AsyncCmdDescMap {
pub fn insert(&mut self, tag: AsyncCmdTag, descriptor_chain: DescriptorChain) {
self.0.insert(tag, descriptor_chain);
}
pub fn remove(&mut self, tag: &AsyncCmdTag) -> Option<DescriptorChain> {
self.0.remove(tag)
}
/// Returns a list of `AsyncCmdResponse`s to cancel pending commands that target
/// stream `target_stream_id`.
/// If `target_queue_type` is specified, then only create the requests for the specified queue.
/// Otherwise, create the requests for both input and output queue.
/// If `processing_tag` is specified, a cancellation request for that tag will
/// not be created.
pub fn create_cancellation_responses(
&self,
target_stream_id: &u32,
target_queue_type: Option<QueueType>,
processing_tag: Option<AsyncCmdTag>,
) -> Vec<AsyncCmdResponse> {
let mut responses = vec![];
for tag in self.0.keys().filter(|&&k| Some(k)!= processing_tag) {
match tag {
AsyncCmdTag::Queue {
stream_id,
queue_type,
..
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
responses.push(AsyncCmdResponse::from_response(
*tag,
CmdResponse::ResourceQueue {
timestamp: 0,
flags: protocol::VIRTIO_VIDEO_BUFFER_FLAG_ERR,
size: 0,
},
));
}
AsyncCmdTag::Drain { stream_id } if stream_id == target_stream_id => {
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
AsyncCmdTag::Clear {
stream_id,
queue_type,
} if stream_id == target_stream_id
&& target_queue_type.as_ref().unwrap_or(queue_type) == queue_type =>
{
// TODO(b/1518105): Use more appropriate error code if a new protocol supports
// one.
responses.push(AsyncCmdResponse::from_error(
*tag,
VideoError::InvalidOperation,
));
}
_ => {
// Keep commands for other streams.
}
}
}
responses
}
}
| AsyncCmdDescMap | identifier_name |
diagnostic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use codemap::{Pos, Span};
use codemap;
use std::cell::Cell;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub struct SpanHandler {
handler: @Handler,
cm: @codemap::CodeMap,
}
impl SpanHandler {
pub fn span_fatal(@self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&*self.cm, sp)), msg, Fatal);
fail!();
}
pub fn span_err(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Error);
self.handler.bump_err_count();
}
pub fn span_warn(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Warning);
}
pub fn span_note(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Note);
}
pub fn span_bug(@self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
pub fn span_unimpl(@self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
pub fn handler(@self) -> @Handler {
self.handler
}
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub struct Handler {
err_count: Cell<uint>,
emit: @Emitter,
}
impl Handler {
pub fn fatal(@self, msg: &str) ->! {
self.emit.emit(None, msg, Fatal);
fail!();
}
pub fn err(@self, msg: &str) {
self.emit.emit(None, msg, Error);
self.bump_err_count();
}
pub fn bump_err_count(@self) {
self.err_count.set(self.err_count.get() + 1u);
}
pub fn err_count(@self) -> uint {
self.err_count.get()
}
pub fn has_errors(@self) -> bool {
self.err_count.get()> 0u
}
pub fn abort_if_errors(@self) {
let s;
match self.err_count.get() {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(s);
}
pub fn warn(@self, msg: &str) {
self.emit.emit(None, msg, Warning);
}
pub fn note(@self, msg: &str) {
self.emit.emit(None, msg, Note);
}
pub fn bug(@self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
pub fn unimpl(@self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
pub fn emit(@self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap)
-> @SpanHandler {
@SpanHandler {
handler: handler,
cm: cm,
}
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@Handler {
err_count: Cell::new(0),
emit: emit,
}
}
#[deriving(Eq)]
pub enum Level {
Fatal,
Error,
Warning,
Note,
}
impl ToStr for Level {
fn to_str(&self) -> ~str {
match *self {
Fatal | Error => ~"error",
Warning => ~"warning",
Note => ~"note"
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN
}
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: Level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", lvl.to_str()),
term::attr::ForegroundColor(lvl.color()));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) |
}
fn highlight_lines(cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: &codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = lines.lines.as_slice();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines);
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color()));
}
}
fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, Note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, Note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
| {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
} | identifier_body |
diagnostic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use codemap::{Pos, Span};
use codemap;
use std::cell::Cell;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub struct SpanHandler {
handler: @Handler,
cm: @codemap::CodeMap,
}
impl SpanHandler {
pub fn span_fatal(@self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&*self.cm, sp)), msg, Fatal);
fail!();
}
pub fn span_err(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Error);
self.handler.bump_err_count();
}
pub fn span_warn(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Warning);
}
pub fn span_note(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Note);
}
pub fn span_bug(@self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
pub fn span_unimpl(@self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
pub fn handler(@self) -> @Handler {
self.handler
}
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub struct Handler {
err_count: Cell<uint>,
emit: @Emitter,
}
impl Handler {
pub fn fatal(@self, msg: &str) ->! {
self.emit.emit(None, msg, Fatal);
fail!();
}
pub fn err(@self, msg: &str) {
self.emit.emit(None, msg, Error);
self.bump_err_count();
}
pub fn bump_err_count(@self) {
self.err_count.set(self.err_count.get() + 1u);
}
pub fn err_count(@self) -> uint {
self.err_count.get()
}
pub fn has_errors(@self) -> bool {
self.err_count.get()> 0u
}
pub fn abort_if_errors(@self) {
let s;
match self.err_count.get() {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(s);
}
pub fn warn(@self, msg: &str) {
self.emit.emit(None, msg, Warning);
}
pub fn note(@self, msg: &str) {
self.emit.emit(None, msg, Note);
}
pub fn bug(@self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
pub fn unimpl(@self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
pub fn emit(@self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap)
-> @SpanHandler {
@SpanHandler {
handler: handler,
cm: cm,
}
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@Handler {
err_count: Cell::new(0),
emit: emit,
}
}
#[deriving(Eq)]
pub enum Level {
Fatal,
Error,
Warning,
Note,
}
impl ToStr for Level {
fn | (&self) -> ~str {
match *self {
Fatal | Error => ~"error",
Warning => ~"warning",
Note => ~"note"
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN
}
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: Level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", lvl.to_str()),
term::attr::ForegroundColor(lvl.color()));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: &codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer;
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = lines.lines.as_slice();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines);
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color()));
}
}
fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, Note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, Note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
}
| to_str | identifier_name |
diagnostic.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use codemap::{Pos, Span};
use codemap;
use std::cell::Cell;
use std::io;
use std::io::stdio::StdWriter;
use std::local_data;
use extra::term;
static BUG_REPORT_URL: &'static str =
"https://github.com/mozilla/rust/wiki/HOWTO-submit-a-Rust-bug-report";
pub trait Emitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level);
}
// a span-handler is like a handler but also
// accepts span information for source-location
// reporting.
pub struct SpanHandler {
handler: @Handler,
cm: @codemap::CodeMap,
}
impl SpanHandler {
pub fn span_fatal(@self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&*self.cm, sp)), msg, Fatal);
fail!();
}
pub fn span_err(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Error);
self.handler.bump_err_count();
}
pub fn span_warn(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Warning);
}
pub fn span_note(@self, sp: Span, msg: &str) {
self.handler.emit(Some((&*self.cm, sp)), msg, Note);
}
pub fn span_bug(@self, sp: Span, msg: &str) ->! {
self.span_fatal(sp, ice_msg(msg));
}
pub fn span_unimpl(@self, sp: Span, msg: &str) ->! {
self.span_bug(sp, ~"unimplemented " + msg);
}
pub fn handler(@self) -> @Handler {
self.handler
}
}
// a handler deals with errors; certain errors
// (fatal, bug, unimpl) may cause immediate exit,
// others log errors for later reporting.
pub struct Handler {
err_count: Cell<uint>,
emit: @Emitter,
}
impl Handler {
pub fn fatal(@self, msg: &str) ->! {
self.emit.emit(None, msg, Fatal);
fail!();
}
pub fn err(@self, msg: &str) {
self.emit.emit(None, msg, Error);
self.bump_err_count();
}
pub fn bump_err_count(@self) {
self.err_count.set(self.err_count.get() + 1u);
}
pub fn err_count(@self) -> uint {
self.err_count.get()
}
pub fn has_errors(@self) -> bool {
self.err_count.get()> 0u
}
pub fn abort_if_errors(@self) {
let s;
match self.err_count.get() {
0u => return,
1u => s = ~"aborting due to previous error",
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(s);
}
pub fn warn(@self, msg: &str) {
self.emit.emit(None, msg, Warning);
}
pub fn note(@self, msg: &str) {
self.emit.emit(None, msg, Note);
}
pub fn bug(@self, msg: &str) ->! {
self.fatal(ice_msg(msg));
}
pub fn unimpl(@self, msg: &str) ->! {
self.bug(~"unimplemented " + msg);
}
pub fn emit(@self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
self.emit.emit(cmsp, msg, lvl);
}
}
pub fn ice_msg(msg: &str) -> ~str {
format!("internal compiler error: {}\nThis message reflects a bug in the Rust compiler. \
\nWe would appreciate a bug report: {}", msg, BUG_REPORT_URL)
}
pub fn mk_span_handler(handler: @Handler, cm: @codemap::CodeMap)
-> @SpanHandler {
@SpanHandler {
handler: handler,
cm: cm,
}
}
pub fn mk_handler(emitter: Option<@Emitter>) -> @Handler {
let emit: @Emitter = match emitter {
Some(e) => e,
None => @DefaultEmitter as @Emitter
};
@Handler {
err_count: Cell::new(0),
emit: emit,
}
}
#[deriving(Eq)]
pub enum Level {
Fatal,
Error,
Warning,
Note,
}
impl ToStr for Level {
fn to_str(&self) -> ~str {
match *self {
Fatal | Error => ~"error",
Warning => ~"warning",
Note => ~"note"
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN
}
}
}
fn print_maybe_styled(msg: &str, color: term::attr::Attr) {
local_data_key!(tls_terminal: ~Option<term::Terminal<StdWriter>>)
fn is_stderr_screen() -> bool {
use std::libc;
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
fn write_pretty<T: Writer>(term: &mut term::Terminal<T>, s: &str, c: term::attr::Attr) {
term.attr(c);
term.write(s.as_bytes());
term.reset();
}
if is_stderr_screen() {
local_data::get_mut(tls_terminal, |term| {
match term {
Some(term) => {
match **term {
Some(ref mut term) => write_pretty(term, msg, color),
None => io::stderr().write(msg.as_bytes())
}
}
None => {
let t = ~match term::Terminal::new(io::stderr()) {
Ok(mut term) => {
write_pretty(&mut term, msg, color);
Some(term)
}
Err(_) => {
io::stderr().write(msg.as_bytes());
None
}
};
local_data::set(tls_terminal, t);
}
}
});
} else {
io::stderr().write(msg.as_bytes());
}
}
fn print_diagnostic(topic: &str, lvl: Level, msg: &str) {
let mut stderr = io::stderr();
if!topic.is_empty() {
write!(&mut stderr as &mut io::Writer, "{} ", topic);
}
print_maybe_styled(format!("{}: ", lvl.to_str()),
term::attr::ForegroundColor(lvl.color()));
print_maybe_styled(format!("{}\n", msg), term::attr::Bold);
}
pub struct DefaultEmitter;
impl Emitter for DefaultEmitter {
fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
match cmsp {
Some((cm, sp)) => {
let sp = cm.adjust_span(sp);
let ss = cm.span_to_str(sp);
let lines = cm.span_to_lines(sp);
print_diagnostic(ss, lvl, msg);
highlight_lines(cm, sp, lvl, lines);
print_macro_backtrace(cm, sp);
}
None => print_diagnostic("", lvl, msg),
}
}
}
fn highlight_lines(cm: &codemap::CodeMap,
sp: Span,
lvl: Level, |
// arbitrarily only print up to six lines of the error
let max_lines = 6u;
let mut elided = false;
let mut display_lines = lines.lines.as_slice();
if display_lines.len() > max_lines {
display_lines = display_lines.slice(0u, max_lines);
elided = true;
}
// Print the offending lines
for line in display_lines.iter() {
write!(err, "{}:{} {}\n", fm.name, *line + 1, fm.get_line(*line as int));
}
if elided {
let last_line = display_lines[display_lines.len() - 1u];
let s = format!("{}:{} ", fm.name, last_line + 1u);
write!(err, "{0:1$}...\n", "", s.len());
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1u {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0u;
let mut num = (lines.lines[0] + 1u) / 10u;
// how many digits must be indent past?
while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~"";
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.len() + digits + 3u;
skip.times(|| s.push_char(' '));
let orig = fm.get_line(lines.lines[0] as int);
for pos in range(0u, left-skip) {
let curChar = (orig[pos] as char);
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match curChar {
'\t' => s.push_char('\t'),
_ => s.push_char(' '),
};
}
write!(err, "{}", s);
let mut s = ~"^";
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
// the ^ already takes up one space
let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
num_squigglies.times(|| s.push_char('~'));
}
print_maybe_styled(s + "\n", term::attr::ForegroundColor(lvl.color()));
}
}
fn print_macro_backtrace(cm: &codemap::CodeMap, sp: Span) {
for ei in sp.expn_info.iter() {
let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!")
};
print_diagnostic(ss, Note,
format!("in expansion of {}{}{}", pre, ei.callee.name, post));
let ss = cm.span_to_str(ei.call_site);
print_diagnostic(ss, Note, "expansion site");
print_macro_backtrace(cm, ei.call_site);
}
}
pub fn expect<T:Clone>(diag: @SpanHandler, opt: Option<T>, msg: || -> ~str)
-> T {
match opt {
Some(ref t) => (*t).clone(),
None => diag.handler().bug(msg()),
}
} | lines: &codemap::FileLines) {
let fm = lines.file;
let mut err = io::stderr();
let err = &mut err as &mut io::Writer; | random_line_split |
plshadow.rs | use winapi::*;
use create_device;
use dxsafe::*;
use dxsafe::structwrappers::*;
use dxsems::VertexFormat;
use std::marker::PhantomData;
// Point Light Shadow
// The name isn't quite correct. This module just fills depth cubemap.
pub struct PLShadow<T: VertexFormat> {
pub pso: D3D12PipelineState,
pub root_sig: D3D12RootSignature,
_luid: Luid,
_phd: PhantomData<T>,
}
impl<T: VertexFormat> PLShadow<T> {
pub fn new(dev: &D3D12Device) -> HResult<PLShadow<T>> {
let mut vshader_bc = vec![];
let mut gshader_bc = vec![];
let mut pshader_bc = vec![];
let mut rsig_bc = vec![];
trace!("Compiling 'plshadow.hlsl'...");
match create_device::compile_shaders("plshadow.hlsl",&mut[
("VSMain", "vs_5_0", &mut vshader_bc),
("GSMain", "gs_5_0", &mut gshader_bc),
("PSMain", "ps_5_0", &mut pshader_bc),
("RSD", "rootsig_1_0", &mut rsig_bc), | Ok(_) => {},
};
trace!("Done");
trace!("Root signature creation");
let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..]));
try!(root_sig.set_name("plshadow RSD"));
let input_elts_desc = T::generate(0);
// pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe.
let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: root_sig.iptr() as *mut _,
VS: ShaderBytecode::from_vec(&vshader_bc).get(),
GS: ShaderBytecode::from_vec(&gshader_bc).get(),
PS: ShaderBytecode::from_vec(&pshader_bc).get(),
RasterizerState: D3D12_RASTERIZER_DESC {
CullMode: D3D12_CULL_MODE_NONE,
DepthBias: 550,
SlopeScaledDepthBias: 1.5,
..rasterizer_desc_default()
},
InputLayout: D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: input_elts_desc.as_ptr(),
NumElements: input_elts_desc.len() as u32,
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 0, // Pixel shader writes depth buffer only
DSVFormat: DXGI_FORMAT_D32_FLOAT,
Flags: D3D12_PIPELINE_STATE_FLAG_NONE,
// Take other fields from default gpsd
..graphics_pipeline_state_desc_default()
};
//pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT;
trace!("Graphics pipeline state creation");
let pso = try!(dev.create_graphics_pipeline_state(&pso_desc));
Ok(PLShadow::<T> {
pso: pso,
root_sig: root_sig,
_luid: Luid(dev.get_adapter_luid()),
_phd: PhantomData,
})
}
} | ], D3DCOMPILE_OPTIMIZATION_LEVEL3) {
Err(err) => {
error!("Error compiling 'plshadow.hlsl': {}", err);
return Err(E_FAIL);
}, | random_line_split |
plshadow.rs | use winapi::*;
use create_device;
use dxsafe::*;
use dxsafe::structwrappers::*;
use dxsems::VertexFormat;
use std::marker::PhantomData;
// Point Light Shadow
// The name isn't quite correct. This module just fills depth cubemap.
pub struct PLShadow<T: VertexFormat> {
pub pso: D3D12PipelineState,
pub root_sig: D3D12RootSignature,
_luid: Luid,
_phd: PhantomData<T>,
}
impl<T: VertexFormat> PLShadow<T> {
pub fn | (dev: &D3D12Device) -> HResult<PLShadow<T>> {
let mut vshader_bc = vec![];
let mut gshader_bc = vec![];
let mut pshader_bc = vec![];
let mut rsig_bc = vec![];
trace!("Compiling 'plshadow.hlsl'...");
match create_device::compile_shaders("plshadow.hlsl",&mut[
("VSMain", "vs_5_0", &mut vshader_bc),
("GSMain", "gs_5_0", &mut gshader_bc),
("PSMain", "ps_5_0", &mut pshader_bc),
("RSD", "rootsig_1_0", &mut rsig_bc),
], D3DCOMPILE_OPTIMIZATION_LEVEL3) {
Err(err) => {
error!("Error compiling 'plshadow.hlsl': {}", err);
return Err(E_FAIL);
},
Ok(_) => {},
};
trace!("Done");
trace!("Root signature creation");
let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..]));
try!(root_sig.set_name("plshadow RSD"));
let input_elts_desc = T::generate(0);
// pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe.
let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: root_sig.iptr() as *mut _,
VS: ShaderBytecode::from_vec(&vshader_bc).get(),
GS: ShaderBytecode::from_vec(&gshader_bc).get(),
PS: ShaderBytecode::from_vec(&pshader_bc).get(),
RasterizerState: D3D12_RASTERIZER_DESC {
CullMode: D3D12_CULL_MODE_NONE,
DepthBias: 550,
SlopeScaledDepthBias: 1.5,
..rasterizer_desc_default()
},
InputLayout: D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: input_elts_desc.as_ptr(),
NumElements: input_elts_desc.len() as u32,
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 0, // Pixel shader writes depth buffer only
DSVFormat: DXGI_FORMAT_D32_FLOAT,
Flags: D3D12_PIPELINE_STATE_FLAG_NONE,
// Take other fields from default gpsd
..graphics_pipeline_state_desc_default()
};
//pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT;
trace!("Graphics pipeline state creation");
let pso = try!(dev.create_graphics_pipeline_state(&pso_desc));
Ok(PLShadow::<T> {
pso: pso,
root_sig: root_sig,
_luid: Luid(dev.get_adapter_luid()),
_phd: PhantomData,
})
}
}
| new | identifier_name |
plshadow.rs | use winapi::*;
use create_device;
use dxsafe::*;
use dxsafe::structwrappers::*;
use dxsems::VertexFormat;
use std::marker::PhantomData;
// Point Light Shadow
// The name isn't quite correct. This module just fills depth cubemap.
pub struct PLShadow<T: VertexFormat> {
pub pso: D3D12PipelineState,
pub root_sig: D3D12RootSignature,
_luid: Luid,
_phd: PhantomData<T>,
}
impl<T: VertexFormat> PLShadow<T> {
pub fn new(dev: &D3D12Device) -> HResult<PLShadow<T>> | trace!("Root signature creation");
let root_sig = try!(dev.create_root_signature(0, &rsig_bc[..]));
try!(root_sig.set_name("plshadow RSD"));
let input_elts_desc = T::generate(0);
// pso_desc contains pointers to local data, so I mustn't pass it around, but I can. Unsafe.
let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: root_sig.iptr() as *mut _,
VS: ShaderBytecode::from_vec(&vshader_bc).get(),
GS: ShaderBytecode::from_vec(&gshader_bc).get(),
PS: ShaderBytecode::from_vec(&pshader_bc).get(),
RasterizerState: D3D12_RASTERIZER_DESC {
CullMode: D3D12_CULL_MODE_NONE,
DepthBias: 550,
SlopeScaledDepthBias: 1.5,
..rasterizer_desc_default()
},
InputLayout: D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: input_elts_desc.as_ptr(),
NumElements: input_elts_desc.len() as u32,
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 0, // Pixel shader writes depth buffer only
DSVFormat: DXGI_FORMAT_D32_FLOAT,
Flags: D3D12_PIPELINE_STATE_FLAG_NONE,
// Take other fields from default gpsd
..graphics_pipeline_state_desc_default()
};
//pso_desc.RTVFormats[0] = DXGI_FORMAT_D32_FLOAT;
trace!("Graphics pipeline state creation");
let pso = try!(dev.create_graphics_pipeline_state(&pso_desc));
Ok(PLShadow::<T> {
pso: pso,
root_sig: root_sig,
_luid: Luid(dev.get_adapter_luid()),
_phd: PhantomData,
})
}
}
| {
let mut vshader_bc = vec![];
let mut gshader_bc = vec![];
let mut pshader_bc = vec![];
let mut rsig_bc = vec![];
trace!("Compiling 'plshadow.hlsl'...");
match create_device::compile_shaders("plshadow.hlsl",&mut[
("VSMain", "vs_5_0", &mut vshader_bc),
("GSMain", "gs_5_0", &mut gshader_bc),
("PSMain", "ps_5_0", &mut pshader_bc),
("RSD", "rootsig_1_0", &mut rsig_bc),
], D3DCOMPILE_OPTIMIZATION_LEVEL3) {
Err(err) => {
error!("Error compiling 'plshadow.hlsl': {}", err);
return Err(E_FAIL);
},
Ok(_) => {},
};
trace!("Done");
| identifier_body |
lib.rs | pub mod nodes;
pub mod parser;
pub mod tokenizer;
mod tests;
use tokenizer::*;
use parser::*;
use nodes::*;
pub struct Document {
root: Element,
}
impl Document {
pub fn new() -> Document {
Document {
root: Element::new("root"),
}
}
pub fn from_element(e: Element) -> Document {
Document {
root: e,
}
}
pub fn from_string(s: &str) -> Result<Document, String> {
let tokens = match tokenize(&s) {
Ok(tokens) => tokens,
Err(e) => return Err(e),
};
let element = match parse(tokens) {
Ok(element) => element,
Err(e) => return Err(e),
};
Ok(Document::from_element(element))
}
pub fn from_file(p: &str) -> Result<Document, String> {
let string = match string_from_file(p) {
Some(string) => string,
None => return Err("Couldn't make String from file".into()),
};
match Document::from_string(&string) {
Ok(document) => Ok(document),
Err(e) => Err(e),
}
}
pub fn | (&self) -> &Element {
match self.root.get_first_child() {
Some(c) => c,
None => panic!("Document has no root element!"),
}
}
pub fn print(&self) {
self.root.print(0);
}
}
| get_root | identifier_name |
lib.rs | pub mod nodes;
pub mod parser;
pub mod tokenizer;
| mod tests;
use tokenizer::*;
use parser::*;
use nodes::*;
pub struct Document {
root: Element,
}
impl Document {
pub fn new() -> Document {
Document {
root: Element::new("root"),
}
}
pub fn from_element(e: Element) -> Document {
Document {
root: e,
}
}
pub fn from_string(s: &str) -> Result<Document, String> {
let tokens = match tokenize(&s) {
Ok(tokens) => tokens,
Err(e) => return Err(e),
};
let element = match parse(tokens) {
Ok(element) => element,
Err(e) => return Err(e),
};
Ok(Document::from_element(element))
}
pub fn from_file(p: &str) -> Result<Document, String> {
let string = match string_from_file(p) {
Some(string) => string,
None => return Err("Couldn't make String from file".into()),
};
match Document::from_string(&string) {
Ok(document) => Ok(document),
Err(e) => Err(e),
}
}
pub fn get_root(&self) -> &Element {
match self.root.get_first_child() {
Some(c) => c,
None => panic!("Document has no root element!"),
}
}
pub fn print(&self) {
self.root.print(0);
}
} | random_line_split |
|
lib.rs | pub mod nodes;
pub mod parser;
pub mod tokenizer;
mod tests;
use tokenizer::*;
use parser::*;
use nodes::*;
pub struct Document {
root: Element,
}
impl Document {
pub fn new() -> Document {
Document {
root: Element::new("root"),
}
}
pub fn from_element(e: Element) -> Document |
pub fn from_string(s: &str) -> Result<Document, String> {
let tokens = match tokenize(&s) {
Ok(tokens) => tokens,
Err(e) => return Err(e),
};
let element = match parse(tokens) {
Ok(element) => element,
Err(e) => return Err(e),
};
Ok(Document::from_element(element))
}
pub fn from_file(p: &str) -> Result<Document, String> {
let string = match string_from_file(p) {
Some(string) => string,
None => return Err("Couldn't make String from file".into()),
};
match Document::from_string(&string) {
Ok(document) => Ok(document),
Err(e) => Err(e),
}
}
pub fn get_root(&self) -> &Element {
match self.root.get_first_child() {
Some(c) => c,
None => panic!("Document has no root element!"),
}
}
pub fn print(&self) {
self.root.print(0);
}
}
| {
Document {
root: e,
}
} | identifier_body |
file.rs | //! Provides File Management functions
use std::ffi;
use std::os::windows::ffi::{
OsStrExt,
OsStringExt
};
use std::default;
use std::ptr;
use std::mem;
use std::convert;
use std::io;
use crate::inner_raw as raw;
use self::raw::winapi::*;
use crate::utils;
const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32;
///Level of information to store about file during search.
pub enum FileInfoLevel {
///Corresponds to FindExInfoStandard. Default.
Standard,
///Corresponds to FindExInfoBasic.
Basic,
///Corresponds to FindExInfoMaxInfoLevel.
Max
}
impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel {
fn into(self) -> FINDEX_INFO_LEVELS {
match self {
FileInfoLevel::Standard => FindExInfoStandard,
FileInfoLevel::Basic => FindExInfoBasic,
FileInfoLevel::Max => FindExInfoMaxInfoLevel
}
}
}
impl default::Default for FileInfoLevel {
fn default() -> Self {
FileInfoLevel::Standard
}
}
///File search type
pub enum FileSearchType {
///Search file by name. Corresponds to FindExSearchNameMatch. Default.
NameMatch,
///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories.
///
///Note that this flag may be ignored by OS.
DirectoriesOnly
}
impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType {
fn into(self) -> FINDEX_SEARCH_OPS {
match self {
FileSearchType::NameMatch => FindExSearchNameMatch,
FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories
}
}
}
impl default::Default for FileSearchType {
fn default() -> Self {
FileSearchType::NameMatch
}
}
///File System Entry.
pub struct Entry(WIN32_FIND_DATAW);
impl Entry {
///Determines whether Entry is directory or not.
pub fn is_dir(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!= 0
}
///Determines whether Entry is file or not.
pub fn is_file(&self) -> bool {
!self.is_dir()
}
///Returns size of entry
pub fn size(&self) -> u64 |
///Returns whether Entry is read-only
pub fn is_read_only(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY)!= 0
}
///Returns name of Entry.
pub fn name(&self) -> ffi::OsString {
ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) {
Some(n) => &self.0.cFileName[..n],
None => &self.0.cFileName
})
}
}
///File System Search iterator.
pub struct Search(HANDLE);
impl Search {
///Creates new instance of Search.
///
///Due to the way how underlying WinAPI works first entry is also returned alongside it.
pub fn new<T:?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> {
let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect();
utf16_buff.push(0);
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
let result = unsafe {
FindFirstFileExW(utf16_buff.as_ptr(),
level.into(),
&mut file_data as *mut _ as *mut c_void,
typ.into(),
ptr::null_mut(),
flags)
};
if result == INVALID_HANDLE_VALUE {
Err(utils::get_last_error())
}
else {
Ok((Search(result), Entry(file_data)))
}
}
///Attempts to search again.
pub fn again(&self) -> io::Result<Entry> {
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
unsafe {
if FindNextFileW(self.0, &mut file_data)!= 0 {
Ok(Entry(file_data))
}
else {
Err(utils::get_last_error())
}
}
}
///Closes search.
pub fn close(self) {
drop(self.0);
}
}
impl Iterator for Search {
type Item = io::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
match self.again() {
Ok(data) => Some(Ok(data)),
Err(error) => {
match error.raw_os_error() {
Some(NO_MORE_FILES) => None,
_ => Some(Err(error))
}
}
}
}
}
impl Drop for Search {
fn drop(&mut self) {
unsafe {
debug_assert!(FindClose(self.0)!= 0);
}
}
}
| {
((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64)
} | identifier_body |
file.rs | //! Provides File Management functions
use std::ffi;
use std::os::windows::ffi::{
OsStrExt,
OsStringExt
};
use std::default;
use std::ptr;
use std::mem;
use std::convert;
use std::io;
use crate::inner_raw as raw;
use self::raw::winapi::*;
use crate::utils;
const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32;
///Level of information to store about file during search.
pub enum FileInfoLevel {
///Corresponds to FindExInfoStandard. Default.
Standard,
///Corresponds to FindExInfoBasic.
Basic,
///Corresponds to FindExInfoMaxInfoLevel.
Max
}
impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel {
fn into(self) -> FINDEX_INFO_LEVELS {
match self {
FileInfoLevel::Standard => FindExInfoStandard,
FileInfoLevel::Basic => FindExInfoBasic,
FileInfoLevel::Max => FindExInfoMaxInfoLevel
}
}
}
impl default::Default for FileInfoLevel {
fn default() -> Self {
FileInfoLevel::Standard
}
}
///File search type
pub enum FileSearchType {
///Search file by name. Corresponds to FindExSearchNameMatch. Default.
NameMatch,
///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories.
///
///Note that this flag may be ignored by OS.
DirectoriesOnly
}
impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType {
fn into(self) -> FINDEX_SEARCH_OPS {
match self {
FileSearchType::NameMatch => FindExSearchNameMatch,
FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories
}
}
}
impl default::Default for FileSearchType {
fn default() -> Self {
FileSearchType::NameMatch
}
}
///File System Entry.
pub struct Entry(WIN32_FIND_DATAW);
impl Entry {
///Determines whether Entry is directory or not.
pub fn is_dir(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!= 0
}
///Determines whether Entry is file or not.
pub fn is_file(&self) -> bool {
!self.is_dir()
}
///Returns size of entry
pub fn | (&self) -> u64 {
((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64)
}
///Returns whether Entry is read-only
pub fn is_read_only(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY)!= 0
}
///Returns name of Entry.
pub fn name(&self) -> ffi::OsString {
ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) {
Some(n) => &self.0.cFileName[..n],
None => &self.0.cFileName
})
}
}
///File System Search iterator.
pub struct Search(HANDLE);
impl Search {
///Creates new instance of Search.
///
///Due to the way how underlying WinAPI works first entry is also returned alongside it.
pub fn new<T:?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> {
let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect();
utf16_buff.push(0);
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
let result = unsafe {
FindFirstFileExW(utf16_buff.as_ptr(),
level.into(),
&mut file_data as *mut _ as *mut c_void,
typ.into(),
ptr::null_mut(),
flags)
};
if result == INVALID_HANDLE_VALUE {
Err(utils::get_last_error())
}
else {
Ok((Search(result), Entry(file_data)))
}
}
///Attempts to search again.
pub fn again(&self) -> io::Result<Entry> {
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
unsafe {
if FindNextFileW(self.0, &mut file_data)!= 0 {
Ok(Entry(file_data))
}
else {
Err(utils::get_last_error())
}
}
}
///Closes search.
pub fn close(self) {
drop(self.0);
}
}
impl Iterator for Search {
type Item = io::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
match self.again() {
Ok(data) => Some(Ok(data)),
Err(error) => {
match error.raw_os_error() {
Some(NO_MORE_FILES) => None,
_ => Some(Err(error))
}
}
}
}
}
impl Drop for Search {
fn drop(&mut self) {
unsafe {
debug_assert!(FindClose(self.0)!= 0);
}
}
}
| size | identifier_name |
file.rs | //! Provides File Management functions
use std::ffi;
use std::os::windows::ffi::{
OsStrExt,
OsStringExt
};
use std::default;
use std::ptr;
use std::mem;
use std::convert;
use std::io;
use crate::inner_raw as raw;
use self::raw::winapi::*;
use crate::utils;
const NO_MORE_FILES: i32 = ERROR_NO_MORE_FILES as i32;
///Level of information to store about file during search.
pub enum FileInfoLevel {
///Corresponds to FindExInfoStandard. Default.
Standard,
///Corresponds to FindExInfoBasic.
Basic,
///Corresponds to FindExInfoMaxInfoLevel.
Max
}
impl convert::Into<FINDEX_INFO_LEVELS> for FileInfoLevel {
fn into(self) -> FINDEX_INFO_LEVELS {
match self {
FileInfoLevel::Standard => FindExInfoStandard,
FileInfoLevel::Basic => FindExInfoBasic,
FileInfoLevel::Max => FindExInfoMaxInfoLevel
}
}
}
impl default::Default for FileInfoLevel {
fn default() -> Self {
FileInfoLevel::Standard
}
}
///File search type
pub enum FileSearchType {
///Search file by name. Corresponds to FindExSearchNameMatch. Default.
NameMatch,
///Ask to search directories only. Corresponds to FindExSearchLimitToDirectories.
///
///Note that this flag may be ignored by OS.
DirectoriesOnly
}
impl convert::Into<FINDEX_SEARCH_OPS> for FileSearchType {
fn into(self) -> FINDEX_SEARCH_OPS {
match self {
FileSearchType::NameMatch => FindExSearchNameMatch,
FileSearchType::DirectoriesOnly => FindExSearchLimitToDirectories
}
}
}
impl default::Default for FileSearchType {
fn default() -> Self {
FileSearchType::NameMatch
}
}
///File System Entry.
pub struct Entry(WIN32_FIND_DATAW);
impl Entry {
///Determines whether Entry is directory or not.
pub fn is_dir(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!= 0
}
///Determines whether Entry is file or not.
pub fn is_file(&self) -> bool { | !self.is_dir()
}
///Returns size of entry
pub fn size(&self) -> u64 {
((self.0.nFileSizeHigh as u64) << 32) | (self.0.nFileSizeLow as u64)
}
///Returns whether Entry is read-only
pub fn is_read_only(&self) -> bool {
(self.0.dwFileAttributes & FILE_ATTRIBUTE_READONLY)!= 0
}
///Returns name of Entry.
pub fn name(&self) -> ffi::OsString {
ffi::OsString::from_wide(match self.0.cFileName.iter().position(|c| *c == 0) {
Some(n) => &self.0.cFileName[..n],
None => &self.0.cFileName
})
}
}
///File System Search iterator.
pub struct Search(HANDLE);
impl Search {
///Creates new instance of Search.
///
///Due to the way how underlying WinAPI works first entry is also returned alongside it.
pub fn new<T:?Sized + AsRef<ffi::OsStr>>(name: &T, level: FileInfoLevel, typ: FileSearchType, flags: DWORD) -> io::Result<(Search, Entry)> {
let mut utf16_buff: Vec<u16> = name.as_ref().encode_wide().collect();
utf16_buff.push(0);
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
let result = unsafe {
FindFirstFileExW(utf16_buff.as_ptr(),
level.into(),
&mut file_data as *mut _ as *mut c_void,
typ.into(),
ptr::null_mut(),
flags)
};
if result == INVALID_HANDLE_VALUE {
Err(utils::get_last_error())
}
else {
Ok((Search(result), Entry(file_data)))
}
}
///Attempts to search again.
pub fn again(&self) -> io::Result<Entry> {
let mut file_data: WIN32_FIND_DATAW = unsafe { mem::zeroed() };
unsafe {
if FindNextFileW(self.0, &mut file_data)!= 0 {
Ok(Entry(file_data))
}
else {
Err(utils::get_last_error())
}
}
}
///Closes search.
pub fn close(self) {
drop(self.0);
}
}
impl Iterator for Search {
type Item = io::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
match self.again() {
Ok(data) => Some(Ok(data)),
Err(error) => {
match error.raw_os_error() {
Some(NO_MORE_FILES) => None,
_ => Some(Err(error))
}
}
}
}
}
impl Drop for Search {
fn drop(&mut self) {
unsafe {
debug_assert!(FindClose(self.0)!= 0);
}
}
} | random_line_split |
|
mut_dns_packet.rs | use buf::*;
#[derive(Debug)]
pub struct MutDnsPacket<'a> {
buf: &'a mut [u8],
pos: usize,
}
impl<'a> MutDnsPacket<'a> {
pub fn new(buf: &mut [u8]) -> MutDnsPacket {
MutDnsPacket::new_at(buf, 0)
}
pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket {
debug!("New MutDnsPacket. buf.len()= {:?}", buf.len());
MutDnsPacket {
buf: buf,
pos: pos,
}
}
}
impl<'a> BufWrite for MutDnsPacket<'a> {
fn buf(&mut self) -> &mut [u8] {
self.buf
}
}
impl<'a> BufRead for MutDnsPacket<'a> {
fn buf(&self) -> &[u8] {
self.buf
}
}
impl<'a> DirectAccessBuf for MutDnsPacket<'a> {
fn pos(&self) -> usize {
self.pos
}
fn set_pos(&mut self, pos: usize) {
self.pos = pos;
}
fn len(&self) -> usize {
self.buf().len()
}
}
///Iterate each 16bit word in the packet
impl<'a> Iterator for MutDnsPacket<'a> {
///2 octets of data and the position
type Item = (u16, usize);
///
///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left
///
fn next(&mut self) -> Option<Self::Item> {
self.next_u16().and_then(|n| Some((n, self.pos)))
}
}
#[cfg(test)]
mod tests {
use super::MutDnsPacket;
use buf::*;
fn test_buf() -> Vec<u8> {
//
// 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000
// 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111
// 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001
//
return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111,
109, 0, 0, 1, 0, 1];
}
#[test]
fn write_u8() {
let mut buf = test_buf();
let mut slice = buf.as_mut_slice();
let mut packet = MutDnsPacket::new(&mut slice);
packet.write_u8(7);
packet.write_u8(8);
packet.write_u8(9);
packet.seek(0);
assert_eq!(7, packet.next_u8().unwrap());
assert_eq!(8, packet.next_u8().unwrap());
assert_eq!(9, packet.next_u8().unwrap());
}
#[test]
fn write_u16() |
#[test]
fn write_u16_bounds() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u16(1));
assert_eq!(true, packet.write_u16(1));
assert_eq!(false, packet.write_u16(1)); //no room
println!("{:?}", packet);
}
#[test]
fn write_u32() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u32(123456789));
println!("{:?}", packet);
packet.seek(0);
assert_eq!(123456789, packet.next_u32().unwrap());
}
}
| {
let mut vec = test_buf();
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
packet.write_u16(2161);
packet.write_u16(1);
packet.seek(0);
println!("{:?}", packet);
assert_eq!(2161, packet.next_u16().unwrap());
assert_eq!(1, packet.next_u16().unwrap());
} | identifier_body |
mut_dns_packet.rs | use buf::*;
#[derive(Debug)]
pub struct MutDnsPacket<'a> {
buf: &'a mut [u8],
pos: usize,
}
impl<'a> MutDnsPacket<'a> {
pub fn new(buf: &mut [u8]) -> MutDnsPacket {
MutDnsPacket::new_at(buf, 0)
}
pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket {
debug!("New MutDnsPacket. buf.len()= {:?}", buf.len());
MutDnsPacket {
buf: buf,
pos: pos,
}
}
}
impl<'a> BufWrite for MutDnsPacket<'a> {
fn buf(&mut self) -> &mut [u8] {
self.buf
}
}
impl<'a> BufRead for MutDnsPacket<'a> {
fn buf(&self) -> &[u8] {
self.buf
}
}
impl<'a> DirectAccessBuf for MutDnsPacket<'a> {
fn pos(&self) -> usize {
self.pos
}
fn set_pos(&mut self, pos: usize) {
self.pos = pos;
}
fn len(&self) -> usize {
self.buf().len()
}
}
///Iterate each 16bit word in the packet
impl<'a> Iterator for MutDnsPacket<'a> {
///2 octets of data and the position
type Item = (u16, usize);
///
///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left
///
fn next(&mut self) -> Option<Self::Item> {
self.next_u16().and_then(|n| Some((n, self.pos)))
}
}
#[cfg(test)]
mod tests {
use super::MutDnsPacket;
use buf::*;
fn test_buf() -> Vec<u8> {
//
// 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000
// 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111
// 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001
//
return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111,
109, 0, 0, 1, 0, 1];
}
#[test]
fn write_u8() {
let mut buf = test_buf();
let mut slice = buf.as_mut_slice();
let mut packet = MutDnsPacket::new(&mut slice);
packet.write_u8(7);
packet.write_u8(8);
packet.write_u8(9);
packet.seek(0);
assert_eq!(7, packet.next_u8().unwrap()); |
#[test]
fn write_u16() {
let mut vec = test_buf();
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
packet.write_u16(2161);
packet.write_u16(1);
packet.seek(0);
println!("{:?}", packet);
assert_eq!(2161, packet.next_u16().unwrap());
assert_eq!(1, packet.next_u16().unwrap());
}
#[test]
fn write_u16_bounds() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u16(1));
assert_eq!(true, packet.write_u16(1));
assert_eq!(false, packet.write_u16(1)); //no room
println!("{:?}", packet);
}
#[test]
fn write_u32() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u32(123456789));
println!("{:?}", packet);
packet.seek(0);
assert_eq!(123456789, packet.next_u32().unwrap());
}
} | assert_eq!(8, packet.next_u8().unwrap());
assert_eq!(9, packet.next_u8().unwrap());
} | random_line_split |
mut_dns_packet.rs | use buf::*;
#[derive(Debug)]
pub struct MutDnsPacket<'a> {
buf: &'a mut [u8],
pos: usize,
}
impl<'a> MutDnsPacket<'a> {
pub fn new(buf: &mut [u8]) -> MutDnsPacket {
MutDnsPacket::new_at(buf, 0)
}
pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket {
debug!("New MutDnsPacket. buf.len()= {:?}", buf.len());
MutDnsPacket {
buf: buf,
pos: pos,
}
}
}
impl<'a> BufWrite for MutDnsPacket<'a> {
fn | (&mut self) -> &mut [u8] {
self.buf
}
}
impl<'a> BufRead for MutDnsPacket<'a> {
fn buf(&self) -> &[u8] {
self.buf
}
}
impl<'a> DirectAccessBuf for MutDnsPacket<'a> {
fn pos(&self) -> usize {
self.pos
}
fn set_pos(&mut self, pos: usize) {
self.pos = pos;
}
fn len(&self) -> usize {
self.buf().len()
}
}
///Iterate each 16bit word in the packet
impl<'a> Iterator for MutDnsPacket<'a> {
///2 octets of data and the position
type Item = (u16, usize);
///
///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left
///
fn next(&mut self) -> Option<Self::Item> {
self.next_u16().and_then(|n| Some((n, self.pos)))
}
}
#[cfg(test)]
mod tests {
use super::MutDnsPacket;
use buf::*;
fn test_buf() -> Vec<u8> {
//
// 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000
// 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111
// 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001
//
return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111,
109, 0, 0, 1, 0, 1];
}
#[test]
fn write_u8() {
let mut buf = test_buf();
let mut slice = buf.as_mut_slice();
let mut packet = MutDnsPacket::new(&mut slice);
packet.write_u8(7);
packet.write_u8(8);
packet.write_u8(9);
packet.seek(0);
assert_eq!(7, packet.next_u8().unwrap());
assert_eq!(8, packet.next_u8().unwrap());
assert_eq!(9, packet.next_u8().unwrap());
}
#[test]
fn write_u16() {
let mut vec = test_buf();
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
packet.write_u16(2161);
packet.write_u16(1);
packet.seek(0);
println!("{:?}", packet);
assert_eq!(2161, packet.next_u16().unwrap());
assert_eq!(1, packet.next_u16().unwrap());
}
#[test]
fn write_u16_bounds() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u16(1));
assert_eq!(true, packet.write_u16(1));
assert_eq!(false, packet.write_u16(1)); //no room
println!("{:?}", packet);
}
#[test]
fn write_u32() {
let mut vec = vec![0, 0, 0, 0];
let mut buf = vec.as_mut_slice();
let mut packet = MutDnsPacket::new(buf);
assert_eq!(true, packet.write_u32(123456789));
println!("{:?}", packet);
packet.seek(0);
assert_eq!(123456789, packet.next_u32().unwrap());
}
}
| buf | identifier_name |
crc32.rs | //! Helper module to compute a CRC32 checksum
use std::io;
use std::io::prelude::*;
static CRC32_TABLE : [u32; 256] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, | 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/// Update the checksum prev based upon the contents of buf.
pub fn update(prev: u32, buf: &[u8]) -> u32
{
let mut crc =!prev;
for &byte in buf.iter()
{
crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8);
}
!crc
}
/// Reader that validates the CRC32 when it reaches the EOF.
pub struct Crc32Reader<R>
{
inner: R,
crc: u32,
check: u32,
}
impl<R> Crc32Reader<R>
{
/// Get a new Crc32Reader which check the inner reader against checksum.
pub fn new(inner: R, checksum: u32) -> Crc32Reader<R>
{
Crc32Reader
{
inner: inner,
crc: 0,
check: checksum,
}
}
fn check_matches(&self) -> bool
{
self.check == self.crc
}
}
impl<R: Read> Read for Crc32Reader<R>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
let count = match self.inner.read(buf)
{
Ok(0) if!self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) },
Ok(n) => n,
Err(e) => return Err(e),
};
self.crc = update(self.crc, &buf[0..count]);
Ok(count)
}
}
#[cfg(test)]
mod test {
#[test]
fn samples() {
assert_eq!(super::update(0, b""), 0);
// test vectors from the iPXE project (input and output are bitwise negated)
assert_eq!(super::update(!0x12345678, b""),!0x12345678);
assert_eq!(super::update(!0xffffffff, b"hello world"),!0xf2b5ee7a);
assert_eq!(super::update(!0xffffffff, b"hello"),!0xc9ef5979);
assert_eq!(super::update(!0xc9ef5979, b" world"),!0xf2b5ee7a);
// Some vectors found on Rosetta code
assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD);
assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B);
assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A);
}
} | random_line_split |
|
crc32.rs | //! Helper module to compute a CRC32 checksum
use std::io;
use std::io::prelude::*;
static CRC32_TABLE : [u32; 256] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/// Update the checksum prev based upon the contents of buf.
pub fn update(prev: u32, buf: &[u8]) -> u32
|
/// Reader that validates the CRC32 when it reaches the EOF.
pub struct Crc32Reader<R>
{
inner: R,
crc: u32,
check: u32,
}
impl<R> Crc32Reader<R>
{
/// Get a new Crc32Reader which check the inner reader against checksum.
pub fn new(inner: R, checksum: u32) -> Crc32Reader<R>
{
Crc32Reader
{
inner: inner,
crc: 0,
check: checksum,
}
}
fn check_matches(&self) -> bool
{
self.check == self.crc
}
}
impl<R: Read> Read for Crc32Reader<R>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
let count = match self.inner.read(buf)
{
Ok(0) if!self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) },
Ok(n) => n,
Err(e) => return Err(e),
};
self.crc = update(self.crc, &buf[0..count]);
Ok(count)
}
}
#[cfg(test)]
mod test {
#[test]
fn samples() {
assert_eq!(super::update(0, b""), 0);
// test vectors from the iPXE project (input and output are bitwise negated)
assert_eq!(super::update(!0x12345678, b""),!0x12345678);
assert_eq!(super::update(!0xffffffff, b"hello world"),!0xf2b5ee7a);
assert_eq!(super::update(!0xffffffff, b"hello"),!0xc9ef5979);
assert_eq!(super::update(!0xc9ef5979, b" world"),!0xf2b5ee7a);
// Some vectors found on Rosetta code
assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD);
assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B);
assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A);
}
}
| {
let mut crc = !prev;
for &byte in buf.iter()
{
crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8);
}
!crc
} | identifier_body |
crc32.rs | //! Helper module to compute a CRC32 checksum
use std::io;
use std::io::prelude::*;
static CRC32_TABLE : [u32; 256] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/// Update the checksum prev based upon the contents of buf.
pub fn | (prev: u32, buf: &[u8]) -> u32
{
let mut crc =!prev;
for &byte in buf.iter()
{
crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8);
}
!crc
}
/// Reader that validates the CRC32 when it reaches the EOF.
pub struct Crc32Reader<R>
{
inner: R,
crc: u32,
check: u32,
}
impl<R> Crc32Reader<R>
{
/// Get a new Crc32Reader which check the inner reader against checksum.
pub fn new(inner: R, checksum: u32) -> Crc32Reader<R>
{
Crc32Reader
{
inner: inner,
crc: 0,
check: checksum,
}
}
fn check_matches(&self) -> bool
{
self.check == self.crc
}
}
impl<R: Read> Read for Crc32Reader<R>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
let count = match self.inner.read(buf)
{
Ok(0) if!self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) },
Ok(n) => n,
Err(e) => return Err(e),
};
self.crc = update(self.crc, &buf[0..count]);
Ok(count)
}
}
#[cfg(test)]
mod test {
#[test]
fn samples() {
assert_eq!(super::update(0, b""), 0);
// test vectors from the iPXE project (input and output are bitwise negated)
assert_eq!(super::update(!0x12345678, b""),!0x12345678);
assert_eq!(super::update(!0xffffffff, b"hello world"),!0xf2b5ee7a);
assert_eq!(super::update(!0xffffffff, b"hello"),!0xc9ef5979);
assert_eq!(super::update(!0xc9ef5979, b" world"),!0xf2b5ee7a);
// Some vectors found on Rosetta code
assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD);
assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B);
assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A);
}
}
| update | identifier_name |
crc32.rs | //! Helper module to compute a CRC32 checksum
use std::io;
use std::io::prelude::*;
static CRC32_TABLE : [u32; 256] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
/// Update the checksum prev based upon the contents of buf.
pub fn update(prev: u32, buf: &[u8]) -> u32
{
let mut crc =!prev;
for &byte in buf.iter()
{
crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8);
}
!crc
}
/// Reader that validates the CRC32 when it reaches the EOF.
pub struct Crc32Reader<R>
{
inner: R,
crc: u32,
check: u32,
}
impl<R> Crc32Reader<R>
{
/// Get a new Crc32Reader which check the inner reader against checksum.
pub fn new(inner: R, checksum: u32) -> Crc32Reader<R>
{
Crc32Reader
{
inner: inner,
crc: 0,
check: checksum,
}
}
fn check_matches(&self) -> bool
{
self.check == self.crc
}
}
impl<R: Read> Read for Crc32Reader<R>
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
{
let count = match self.inner.read(buf)
{
Ok(0) if!self.check_matches() => | ,
Ok(n) => n,
Err(e) => return Err(e),
};
self.crc = update(self.crc, &buf[0..count]);
Ok(count)
}
}
#[cfg(test)]
mod test {
#[test]
fn samples() {
assert_eq!(super::update(0, b""), 0);
// test vectors from the iPXE project (input and output are bitwise negated)
assert_eq!(super::update(!0x12345678, b""),!0x12345678);
assert_eq!(super::update(!0xffffffff, b"hello world"),!0xf2b5ee7a);
assert_eq!(super::update(!0xffffffff, b"hello"),!0xc9ef5979);
assert_eq!(super::update(!0xc9ef5979, b" world"),!0xf2b5ee7a);
// Some vectors found on Rosetta code
assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD);
assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B);
assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A);
}
}
| { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) } | conditional_block |
types.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// MethodCall denotes a specific request to be carried out by routing.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum MethodCall {
/// request to have `location` to handle put for the `content`
Put { | },
/// request to retreive data with specified type and location from network
Get {
location: ::routing::authority::Authority,
data_request: ::routing::data::DataRequest,
},
// /// request to post
// Post { destination: ::routing::NameType, content: Data },
// /// Request delete
// Delete { name: ::routing::NameType, data : Data },
/// request to refresh
Refresh {
type_tag: u64,
our_authority: ::routing::Authority,
payload: Vec<u8>,
},
/// reply
Reply {
data: ::routing::data::Data,
},
/// response error indicating failed in putting data
FailedPut {
location: ::routing::authority::Authority,
data: ::routing::data::Data,
},
/// response error indicating clearing sarificial data
ClearSacrificial {
location: ::routing::authority::Authority,
name: ::routing::NameType,
size: u32,
},
/// response error indicating not enough allowance
LowBalance{ location: ::routing::authority::Authority,
data: ::routing::data::Data, balance: u32},
/// response error indicating invalid request
InvalidRequest {
data: ::routing::data::Data,
},
}
/// This trait is required for any type (normally an account) which is refreshed on a churn event.
pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable {
/// The serialised contents
fn serialised_contents(&self) -> Vec<u8> {
::routing::utils::encode(&self).unwrap_or(vec![])
}
/// Merge multiple refreshable objects into one
fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>;
} | location: ::routing::authority::Authority,
content: ::routing::data::Data, | random_line_split |
types.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// MethodCall denotes a specific request to be carried out by routing.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum MethodCall {
/// request to have `location` to handle put for the `content`
Put {
location: ::routing::authority::Authority,
content: ::routing::data::Data,
},
/// request to retreive data with specified type and location from network
Get {
location: ::routing::authority::Authority,
data_request: ::routing::data::DataRequest,
},
// /// request to post
// Post { destination: ::routing::NameType, content: Data },
// /// Request delete
// Delete { name: ::routing::NameType, data : Data },
/// request to refresh
Refresh {
type_tag: u64,
our_authority: ::routing::Authority,
payload: Vec<u8>,
},
/// reply
Reply {
data: ::routing::data::Data,
},
/// response error indicating failed in putting data
FailedPut {
location: ::routing::authority::Authority,
data: ::routing::data::Data,
},
/// response error indicating clearing sarificial data
ClearSacrificial {
location: ::routing::authority::Authority,
name: ::routing::NameType,
size: u32,
},
/// response error indicating not enough allowance
LowBalance{ location: ::routing::authority::Authority,
data: ::routing::data::Data, balance: u32},
/// response error indicating invalid request
InvalidRequest {
data: ::routing::data::Data,
},
}
/// This trait is required for any type (normally an account) which is refreshed on a churn event.
pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable {
/// The serialised contents
fn serialised_contents(&self) -> Vec<u8> |
/// Merge multiple refreshable objects into one
fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>;
}
| {
::routing::utils::encode(&self).unwrap_or(vec![])
} | identifier_body |
types.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// MethodCall denotes a specific request to be carried out by routing.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum MethodCall {
/// request to have `location` to handle put for the `content`
Put {
location: ::routing::authority::Authority,
content: ::routing::data::Data,
},
/// request to retreive data with specified type and location from network
Get {
location: ::routing::authority::Authority,
data_request: ::routing::data::DataRequest,
},
// /// request to post
// Post { destination: ::routing::NameType, content: Data },
// /// Request delete
// Delete { name: ::routing::NameType, data : Data },
/// request to refresh
Refresh {
type_tag: u64,
our_authority: ::routing::Authority,
payload: Vec<u8>,
},
/// reply
Reply {
data: ::routing::data::Data,
},
/// response error indicating failed in putting data
FailedPut {
location: ::routing::authority::Authority,
data: ::routing::data::Data,
},
/// response error indicating clearing sarificial data
ClearSacrificial {
location: ::routing::authority::Authority,
name: ::routing::NameType,
size: u32,
},
/// response error indicating not enough allowance
LowBalance{ location: ::routing::authority::Authority,
data: ::routing::data::Data, balance: u32},
/// response error indicating invalid request
InvalidRequest {
data: ::routing::data::Data,
},
}
/// This trait is required for any type (normally an account) which is refreshed on a churn event.
pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable {
/// The serialised contents
fn | (&self) -> Vec<u8> {
::routing::utils::encode(&self).unwrap_or(vec![])
}
/// Merge multiple refreshable objects into one
fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>;
}
| serialised_contents | identifier_name |
uds.rs | use std::io::{Read, Write};
use std::mem;
use std::net::Shutdown;
use std::os::unix::prelude::*;
use std::path::Path;
use libc;
use {io, Ready, Poll, PollOpt, Token};
use event::Evented;
use sys::unix::{cvt, Io};
use sys::unix::io::{set_nonblock, set_cloexec};
trait MyInto<T> {
fn my_into(self) -> T;
}
impl MyInto<u32> for usize {
fn my_into(self) -> u32 { self as u32 }
}
impl MyInto<usize> for usize {
fn my_into(self) -> usize { self }
}
unsafe fn sockaddr_un(path: &Path)
-> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
let mut addr: libc::sockaddr_un = mem::zeroed();
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_os_str().as_bytes();
if bytes.len() >= addr.sun_path.len() {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN"))
}
for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
*dst = *src as libc::c_char;
}
// null byte for pathname addresses is already there because we zeroed the
// struct
let mut len = sun_path_offset() + bytes.len();
match bytes.get(0) {
Some(&0) | None => |
Some(_) => len += 1,
}
Ok((addr, len as libc::socklen_t))
}
fn sun_path_offset() -> usize {
unsafe {
// Work with an actual instance of the type since using a null pointer is UB
let addr: libc::sockaddr_un = mem::uninitialized();
let base = &addr as *const _ as usize;
let path = &addr.sun_path as *const _ as usize;
path - base
}
}
#[derive(Debug)]
pub struct UnixSocket {
io: Io,
}
impl UnixSocket {
/// Returns a new, unbound, non-blocking Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
#[cfg(target_os = "linux")]
use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
#[cfg(not(target_os = "linux"))]
const SOCK_CLOEXEC: libc::c_int = 0;
#[cfg(not(target_os = "linux"))]
const SOCK_NONBLOCK: libc::c_int = 0;
unsafe {
if cfg!(target_os = "linux") {
let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
match cvt(libc::socket(libc::AF_UNIX, flags, 0)) {
Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)),
Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
Err(e) => return Err(e),
}
}
let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?;
let fd = UnixSocket::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(fd)
}
}
/// Connect the socket to the specified address
pub fn connect<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::connect(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
/// Listen for incoming requests
pub fn listen(&self, backlog: usize) -> io::Result<()> {
unsafe {
cvt(libc::listen(self.as_raw_fd(), backlog as i32))?;
Ok(())
}
}
pub fn accept(&self) -> io::Result<UnixSocket> {
unsafe {
let fd = cvt(libc::accept(self.as_raw_fd(),
0 as *mut _,
0 as *mut _))?;
let fd = Io::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(UnixSocket { io: fd })
}
}
/// Bind the socket to the specified address
#[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
#[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
let len_i32 = len as i32;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len_i32))?;
Ok(())
}
}
pub fn try_clone(&self) -> io::Result<UnixSocket> {
Ok(UnixSocket { io: self.io.try_clone()? })
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Read => libc::SHUT_RD,
Shutdown::Write => libc::SHUT_WR,
Shutdown::Both => libc::SHUT_RDWR,
};
unsafe {
cvt(libc::shutdown(self.as_raw_fd(), how))?;
Ok(())
}
}
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_mut_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?;
const SCM_RIGHTS: libc::c_int = 1;
let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET &&
cmsg.hdr.cmsg_type == SCM_RIGHTS {
Some(cmsg.data[0])
} else {
None
};
Ok((bytes as usize, fd))
}
}
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into();
cmsg.hdr.cmsg_level = libc::SOL_SOCKET;
cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS
cmsg.data[0] = fd;
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?;
Ok(bytes as usize)
}
}
}
impl Read for UnixSocket {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.io.read(buf)
}
}
impl Write for UnixSocket {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.io.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.io.flush()
}
}
impl Evented for UnixSocket {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.io.deregister(poll)
}
}
impl From<Io> for UnixSocket {
fn from(io: Io) -> UnixSocket {
UnixSocket { io: io }
}
}
impl FromRawFd for UnixSocket {
unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket {
UnixSocket { io: Io::from_raw_fd(fd) }
}
}
impl IntoRawFd for UnixSocket {
fn into_raw_fd(self) -> RawFd {
self.io.into_raw_fd()
}
}
impl AsRawFd for UnixSocket {
fn as_raw_fd(&self) -> RawFd {
self.io.as_raw_fd()
}
}
| {} | conditional_block |
uds.rs | use std::io::{Read, Write};
use std::mem;
use std::net::Shutdown;
use std::os::unix::prelude::*;
use std::path::Path;
use libc;
use {io, Ready, Poll, PollOpt, Token};
use event::Evented;
use sys::unix::{cvt, Io};
use sys::unix::io::{set_nonblock, set_cloexec};
trait MyInto<T> {
fn my_into(self) -> T;
}
impl MyInto<u32> for usize {
fn my_into(self) -> u32 { self as u32 }
}
impl MyInto<usize> for usize {
fn my_into(self) -> usize { self }
}
unsafe fn sockaddr_un(path: &Path)
-> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
let mut addr: libc::sockaddr_un = mem::zeroed();
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_os_str().as_bytes();
if bytes.len() >= addr.sun_path.len() {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN"))
}
for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
*dst = *src as libc::c_char;
}
// null byte for pathname addresses is already there because we zeroed the
// struct
let mut len = sun_path_offset() + bytes.len();
match bytes.get(0) {
Some(&0) | None => {}
Some(_) => len += 1,
}
Ok((addr, len as libc::socklen_t))
}
fn sun_path_offset() -> usize {
unsafe {
// Work with an actual instance of the type since using a null pointer is UB
let addr: libc::sockaddr_un = mem::uninitialized();
let base = &addr as *const _ as usize;
let path = &addr.sun_path as *const _ as usize;
path - base
}
}
#[derive(Debug)]
pub struct UnixSocket {
io: Io,
}
impl UnixSocket {
/// Returns a new, unbound, non-blocking Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
#[cfg(target_os = "linux")]
use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
#[cfg(not(target_os = "linux"))]
const SOCK_CLOEXEC: libc::c_int = 0;
#[cfg(not(target_os = "linux"))]
const SOCK_NONBLOCK: libc::c_int = 0;
unsafe {
if cfg!(target_os = "linux") {
let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
match cvt(libc::socket(libc::AF_UNIX, flags, 0)) {
Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)),
Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
Err(e) => return Err(e),
}
}
let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?;
let fd = UnixSocket::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(fd)
}
}
/// Connect the socket to the specified address
pub fn connect<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::connect(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
/// Listen for incoming requests
pub fn | (&self, backlog: usize) -> io::Result<()> {
unsafe {
cvt(libc::listen(self.as_raw_fd(), backlog as i32))?;
Ok(())
}
}
pub fn accept(&self) -> io::Result<UnixSocket> {
unsafe {
let fd = cvt(libc::accept(self.as_raw_fd(),
0 as *mut _,
0 as *mut _))?;
let fd = Io::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(UnixSocket { io: fd })
}
}
/// Bind the socket to the specified address
#[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
#[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
let len_i32 = len as i32;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len_i32))?;
Ok(())
}
}
pub fn try_clone(&self) -> io::Result<UnixSocket> {
Ok(UnixSocket { io: self.io.try_clone()? })
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Read => libc::SHUT_RD,
Shutdown::Write => libc::SHUT_WR,
Shutdown::Both => libc::SHUT_RDWR,
};
unsafe {
cvt(libc::shutdown(self.as_raw_fd(), how))?;
Ok(())
}
}
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_mut_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?;
const SCM_RIGHTS: libc::c_int = 1;
let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET &&
cmsg.hdr.cmsg_type == SCM_RIGHTS {
Some(cmsg.data[0])
} else {
None
};
Ok((bytes as usize, fd))
}
}
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into();
cmsg.hdr.cmsg_level = libc::SOL_SOCKET;
cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS
cmsg.data[0] = fd;
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?;
Ok(bytes as usize)
}
}
}
impl Read for UnixSocket {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.io.read(buf)
}
}
impl Write for UnixSocket {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.io.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.io.flush()
}
}
impl Evented for UnixSocket {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.io.deregister(poll)
}
}
impl From<Io> for UnixSocket {
fn from(io: Io) -> UnixSocket {
UnixSocket { io: io }
}
}
impl FromRawFd for UnixSocket {
unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket {
UnixSocket { io: Io::from_raw_fd(fd) }
}
}
impl IntoRawFd for UnixSocket {
fn into_raw_fd(self) -> RawFd {
self.io.into_raw_fd()
}
}
impl AsRawFd for UnixSocket {
fn as_raw_fd(&self) -> RawFd {
self.io.as_raw_fd()
}
}
| listen | identifier_name |
uds.rs | use std::io::{Read, Write};
use std::mem;
use std::net::Shutdown;
use std::os::unix::prelude::*;
use std::path::Path;
use libc;
use {io, Ready, Poll, PollOpt, Token};
use event::Evented;
use sys::unix::{cvt, Io};
use sys::unix::io::{set_nonblock, set_cloexec};
trait MyInto<T> {
fn my_into(self) -> T;
}
impl MyInto<u32> for usize {
fn my_into(self) -> u32 { self as u32 }
}
impl MyInto<usize> for usize {
fn my_into(self) -> usize { self }
}
unsafe fn sockaddr_un(path: &Path)
-> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
let mut addr: libc::sockaddr_un = mem::zeroed();
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_os_str().as_bytes();
if bytes.len() >= addr.sun_path.len() {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN"))
}
for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
*dst = *src as libc::c_char;
}
// null byte for pathname addresses is already there because we zeroed the
// struct
let mut len = sun_path_offset() + bytes.len();
match bytes.get(0) {
Some(&0) | None => {}
Some(_) => len += 1,
}
Ok((addr, len as libc::socklen_t))
}
fn sun_path_offset() -> usize {
unsafe {
// Work with an actual instance of the type since using a null pointer is UB
let addr: libc::sockaddr_un = mem::uninitialized();
let base = &addr as *const _ as usize;
let path = &addr.sun_path as *const _ as usize;
path - base
}
}
#[derive(Debug)]
pub struct UnixSocket {
io: Io,
}
impl UnixSocket {
/// Returns a new, unbound, non-blocking Unix domain socket
pub fn stream() -> io::Result<UnixSocket> {
#[cfg(target_os = "linux")]
use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
#[cfg(not(target_os = "linux"))]
const SOCK_CLOEXEC: libc::c_int = 0;
#[cfg(not(target_os = "linux"))]
const SOCK_NONBLOCK: libc::c_int = 0;
unsafe {
if cfg!(target_os = "linux") {
let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
match cvt(libc::socket(libc::AF_UNIX, flags, 0)) {
Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)),
Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
Err(e) => return Err(e),
}
}
let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?;
let fd = UnixSocket::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(fd)
}
}
/// Connect the socket to the specified address
pub fn connect<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::connect(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
/// Listen for incoming requests
pub fn listen(&self, backlog: usize) -> io::Result<()> {
unsafe {
cvt(libc::listen(self.as_raw_fd(), backlog as i32))?;
Ok(()) | }
}
pub fn accept(&self) -> io::Result<UnixSocket> {
unsafe {
let fd = cvt(libc::accept(self.as_raw_fd(),
0 as *mut _,
0 as *mut _))?;
let fd = Io::from_raw_fd(fd);
set_cloexec(fd.as_raw_fd())?;
set_nonblock(fd.as_raw_fd())?;
Ok(UnixSocket { io: fd })
}
}
/// Bind the socket to the specified address
#[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len))?;
Ok(())
}
}
#[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))]
pub fn bind<P: AsRef<Path> +?Sized>(&self, addr: &P) -> io::Result<()> {
unsafe {
let (addr, len) = sockaddr_un(addr.as_ref())?;
let len_i32 = len as i32;
cvt(libc::bind(self.as_raw_fd(),
&addr as *const _ as *const _,
len_i32))?;
Ok(())
}
}
pub fn try_clone(&self) -> io::Result<UnixSocket> {
Ok(UnixSocket { io: self.io.try_clone()? })
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Read => libc::SHUT_RD,
Shutdown::Write => libc::SHUT_WR,
Shutdown::Both => libc::SHUT_RDWR,
};
unsafe {
cvt(libc::shutdown(self.as_raw_fd(), how))?;
Ok(())
}
}
pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_mut_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?;
const SCM_RIGHTS: libc::c_int = 1;
let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET &&
cmsg.hdr.cmsg_type == SCM_RIGHTS {
Some(cmsg.data[0])
} else {
None
};
Ok((bytes as usize, fd))
}
}
pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
unsafe {
let mut iov = libc::iovec {
iov_base: buf.as_ptr() as *mut _,
iov_len: buf.len(),
};
struct Cmsg {
hdr: libc::cmsghdr,
data: [libc::c_int; 1],
}
let mut cmsg: Cmsg = mem::zeroed();
cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into();
cmsg.hdr.cmsg_level = libc::SOL_SOCKET;
cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS
cmsg.data[0] = fd;
let mut msg: libc::msghdr = mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = &mut cmsg as *mut _ as *mut _;
msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?;
Ok(bytes as usize)
}
}
}
impl Read for UnixSocket {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.io.read(buf)
}
}
impl Write for UnixSocket {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.io.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.io.flush()
}
}
impl Evented for UnixSocket {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.io.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.io.deregister(poll)
}
}
impl From<Io> for UnixSocket {
fn from(io: Io) -> UnixSocket {
UnixSocket { io: io }
}
}
impl FromRawFd for UnixSocket {
unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket {
UnixSocket { io: Io::from_raw_fd(fd) }
}
}
impl IntoRawFd for UnixSocket {
fn into_raw_fd(self) -> RawFd {
self.io.into_raw_fd()
}
}
impl AsRawFd for UnixSocket {
fn as_raw_fd(&self) -> RawFd {
self.io.as_raw_fd()
}
} | random_line_split |
|
p_2_1_2_02.rs | // P_2_1_2_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* changing module color and positions in a grid
*
* MOUSE
* position x : offset x
* position y : offset y
* left click : random position
*
* KEYS
* 1-3 : different sets of colors
* 0 : default
* arrow up/down : background module size
* arrow left/right : foreground module size
* s : save png
*/
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};
fn main() {
nannou::app(model).run();
}
struct Model {
tile_count: u32,
act_random_seed: u64,
module_color_background: Hsva,
module_color_foreground: Hsva,
module_alpha_background: f32,
module_alpha_foreground: f32,
module_radius_background: f32,
module_radius_foreground: f32,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(600, 600)
.view(view)
.mouse_pressed(mouse_pressed)
.key_pressed(key_pressed)
.key_released(key_released)
.build()
.unwrap();
let module_alpha_background = 1.0;
let module_alpha_foreground = 1.0;
Model {
tile_count: 20,
act_random_seed: 0,
module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background),
module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground),
module_alpha_background,
module_alpha_foreground,
module_radius_background: 15.0,
module_radius_foreground: 7.5,
}
}
fn vie | p: &App, model: &Model, frame: Frame) {
let draw = app.draw();
let win = app.window_rect();
draw.background().color(WHITE);
let mut rng = StdRng::seed_from_u64(model.act_random_seed);
let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());
let my = clamp(win.top() - app.mouse.y, 0.0, win.h());
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0;
let shift_y = rng.gen_range(-my, my + 1.0) / 20.0;
draw.ellipse()
.x_y(pos_x + shift_x, pos_y + shift_y)
.radius(model.module_radius_background)
.color(model.module_color_background);
}
}
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
draw.ellipse()
.x_y(pos_x, pos_y)
.radius(model.module_radius_foreground)
.color(model.module_color_foreground);
}
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.act_random_seed = (random_f32() * 100000.0) as u64;
}
fn key_pressed(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
fn key_released(_app: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
if model
.module_color_background
.eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background))
{
model.module_color_background =
hsva(0.758, 0.73, 0.51, model.module_alpha_background);
} else {
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
}
}
Key::Key2 => {
if model
.module_color_foreground
.eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground))
{
model.module_color_foreground =
hsva(0.89, 1.0, 0.77, model.module_alpha_foreground);
} else {
model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground);
}
}
Key::Key3 => {
if model.module_alpha_background == 1.0 {
model.module_alpha_background = 0.5;
model.module_alpha_foreground = 0.5;
} else {
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
}
model.module_color_background.alpha = model.module_alpha_background;
model.module_color_foreground.alpha = model.module_alpha_foreground;
}
Key::Key0 => {
model.module_radius_background = 15.0;
model.module_radius_foreground = 7.5;
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground);
}
Key::Up => {
model.module_radius_background += 2.0;
}
Key::Down => {
model.module_radius_background = 5.0.max(model.module_radius_background - 2.0);
}
Key::Left => {
model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0);
}
Key::Right => {
model.module_radius_foreground += 2.0;
}
_other_key => {}
}
}
| w(ap | identifier_name |
p_2_1_2_02.rs | // P_2_1_2_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* changing module color and positions in a grid
*
* MOUSE
* position x : offset x
* position y : offset y
* left click : random position
*
* KEYS
* 1-3 : different sets of colors
* 0 : default
* arrow up/down : background module size
* arrow left/right : foreground module size
* s : save png
*/
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};
fn main() {
nannou::app(model).run();
}
struct Model {
tile_count: u32,
act_random_seed: u64,
module_color_background: Hsva,
module_color_foreground: Hsva,
module_alpha_background: f32,
module_alpha_foreground: f32,
module_radius_background: f32,
module_radius_foreground: f32,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(600, 600)
.view(view)
.mouse_pressed(mouse_pressed)
.key_pressed(key_pressed)
.key_released(key_released)
.build()
.unwrap();
let module_alpha_background = 1.0;
let module_alpha_foreground = 1.0;
Model {
tile_count: 20,
act_random_seed: 0,
module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background),
module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground),
module_alpha_background,
module_alpha_foreground,
module_radius_background: 15.0,
module_radius_foreground: 7.5,
}
}
fn view(app: &App, model: &Model, frame: Frame) {
let draw = app.draw();
let win = app.window_rect();
draw.background().color(WHITE);
let mut rng = StdRng::seed_from_u64(model.act_random_seed);
let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());
let my = clamp(win.top() - app.mouse.y, 0.0, win.h());
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0;
let shift_y = rng.gen_range(-my, my + 1.0) / 20.0;
draw.ellipse()
.x_y(pos_x + shift_x, pos_y + shift_y)
.radius(model.module_radius_background)
.color(model.module_color_background);
}
}
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
draw.ellipse()
.x_y(pos_x, pos_y)
.radius(model.module_radius_foreground)
.color(model.module_color_foreground);
}
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.act_random_seed = (random_f32() * 100000.0) as u64;
}
fn key_pressed(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
fn key_released(_app: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
if model
.module_color_background
.eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background))
{
model.module_color_background =
hsva(0.758, 0.73, 0.51, model.module_alpha_background);
} else {
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
}
}
Key::Key2 => {
if model
.module_color_foreground
.eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground))
{
model.module_color_foreground =
hsva(0.89, 1.0, 0.77, model.module_alpha_foreground);
} else {
| }
Key::Key3 => {
if model.module_alpha_background == 1.0 {
model.module_alpha_background = 0.5;
model.module_alpha_foreground = 0.5;
} else {
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
}
model.module_color_background.alpha = model.module_alpha_background;
model.module_color_foreground.alpha = model.module_alpha_foreground;
}
Key::Key0 => {
model.module_radius_background = 15.0;
model.module_radius_foreground = 7.5;
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground);
}
Key::Up => {
model.module_radius_background += 2.0;
}
Key::Down => {
model.module_radius_background = 5.0.max(model.module_radius_background - 2.0);
}
Key::Left => {
model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0);
}
Key::Right => {
model.module_radius_foreground += 2.0;
}
_other_key => {}
}
}
| model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground);
}
| conditional_block |
p_2_1_2_02.rs | // P_2_1_2_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* changing module color and positions in a grid
*
* MOUSE
* position x : offset x
* position y : offset y
* left click : random position
*
* KEYS
* 1-3 : different sets of colors
* 0 : default
* arrow up/down : background module size
* arrow left/right : foreground module size
* s : save png
*/
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};
fn main() {
nannou::app(model).run();
}
struct Model {
tile_count: u32,
act_random_seed: u64,
module_color_background: Hsva,
module_color_foreground: Hsva,
module_alpha_background: f32,
module_alpha_foreground: f32,
module_radius_background: f32,
module_radius_foreground: f32,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(600, 600)
.view(view)
.mouse_pressed(mouse_pressed)
.key_pressed(key_pressed)
.key_released(key_released)
.build()
.unwrap();
let module_alpha_background = 1.0;
let module_alpha_foreground = 1.0;
Model {
tile_count: 20,
act_random_seed: 0,
module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background),
module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground),
module_alpha_background,
module_alpha_foreground,
module_radius_background: 15.0,
module_radius_foreground: 7.5,
}
}
fn view(app: &App, model: &Model, frame: Frame) {
let draw = app.draw();
let win = app.window_rect();
draw.background().color(WHITE);
let mut rng = StdRng::seed_from_u64(model.act_random_seed);
let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());
let my = clamp(win.top() - app.mouse.y, 0.0, win.h());
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0;
let shift_y = rng.gen_range(-my, my + 1.0) / 20.0;
draw.ellipse()
.x_y(pos_x + shift_x, pos_y + shift_y)
.radius(model.module_radius_background)
.color(model.module_color_background);
}
}
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
draw.ellipse()
.x_y(pos_x, pos_y)
.radius(model.module_radius_foreground)
.color(model.module_color_foreground);
}
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.act_random_seed = (random_f32() * 100000.0) as u64;
}
fn key_pressed(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
fn key_released(_app: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
if model
.module_color_background
.eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background))
{
model.module_color_background =
hsva(0.758, 0.73, 0.51, model.module_alpha_background);
} else {
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
}
}
Key::Key2 => {
if model
.module_color_foreground
.eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground))
{
model.module_color_foreground =
hsva(0.89, 1.0, 0.77, model.module_alpha_foreground);
} else {
model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground);
}
}
Key::Key3 => {
if model.module_alpha_background == 1.0 {
model.module_alpha_background = 0.5;
model.module_alpha_foreground = 0.5;
} else {
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
}
model.module_color_background.alpha = model.module_alpha_background; | }
Key::Key0 => {
model.module_radius_background = 15.0;
model.module_radius_foreground = 7.5;
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground);
}
Key::Up => {
model.module_radius_background += 2.0;
}
Key::Down => {
model.module_radius_background = 5.0.max(model.module_radius_background - 2.0);
}
Key::Left => {
model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0);
}
Key::Right => {
model.module_radius_foreground += 2.0;
}
_other_key => {}
}
} | model.module_color_foreground.alpha = model.module_alpha_foreground; | random_line_split |
p_2_1_2_02.rs | // P_2_1_2_02
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* changing module color and positions in a grid
*
* MOUSE
* position x : offset x
* position y : offset y
* left click : random position
*
* KEYS
* 1-3 : different sets of colors
* 0 : default
* arrow up/down : background module size
* arrow left/right : foreground module size
* s : save png
*/
use nannou::prelude::*;
use nannou::rand::rngs::StdRng;
use nannou::rand::{Rng, SeedableRng};
fn main() {
nannou::app(model).run();
}
struct Model {
tile_count: u32,
act_random_seed: u64,
module_color_background: Hsva,
module_color_foreground: Hsva,
module_alpha_background: f32,
module_alpha_foreground: f32,
module_radius_background: f32,
module_radius_foreground: f32,
}
fn model(app: &App) -> Model {
| module_radius_background: 15.0,
module_radius_foreground: 7.5,
}
}
f
n view(app: &App, model: &Model, frame: Frame) {
let draw = app.draw();
let win = app.window_rect();
draw.background().color(WHITE);
let mut rng = StdRng::seed_from_u64(model.act_random_seed);
let mx = clamp(win.right() + app.mouse.x, 0.0, win.w());
let my = clamp(win.top() - app.mouse.y, 0.0, win.h());
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0;
let shift_y = rng.gen_range(-my, my + 1.0) / 20.0;
draw.ellipse()
.x_y(pos_x + shift_x, pos_y + shift_y)
.radius(model.module_radius_background)
.color(model.module_color_background);
}
}
for grid_y in 0..model.tile_count {
for grid_x in 0..model.tile_count {
let tile_w = win.w() / model.tile_count as f32;
let tile_h = win.h() / model.tile_count as f32;
let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32;
let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32;
draw.ellipse()
.x_y(pos_x, pos_y)
.radius(model.module_radius_foreground)
.color(model.module_color_foreground);
}
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.act_random_seed = (random_f32() * 100000.0) as u64;
}
fn key_pressed(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
fn key_released(_app: &App, model: &mut Model, key: Key) {
match key {
Key::Key1 => {
if model
.module_color_background
.eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background))
{
model.module_color_background =
hsva(0.758, 0.73, 0.51, model.module_alpha_background);
} else {
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
}
}
Key::Key2 => {
if model
.module_color_foreground
.eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground))
{
model.module_color_foreground =
hsva(0.89, 1.0, 0.77, model.module_alpha_foreground);
} else {
model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground);
}
}
Key::Key3 => {
if model.module_alpha_background == 1.0 {
model.module_alpha_background = 0.5;
model.module_alpha_foreground = 0.5;
} else {
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
}
model.module_color_background.alpha = model.module_alpha_background;
model.module_color_foreground.alpha = model.module_alpha_foreground;
}
Key::Key0 => {
model.module_radius_background = 15.0;
model.module_radius_foreground = 7.5;
model.module_alpha_background = 1.0;
model.module_alpha_foreground = 1.0;
model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background);
model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground);
}
Key::Up => {
model.module_radius_background += 2.0;
}
Key::Down => {
model.module_radius_background = 5.0.max(model.module_radius_background - 2.0);
}
Key::Left => {
model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0);
}
Key::Right => {
model.module_radius_foreground += 2.0;
}
_other_key => {}
}
}
| let _window = app
.new_window()
.size(600, 600)
.view(view)
.mouse_pressed(mouse_pressed)
.key_pressed(key_pressed)
.key_released(key_released)
.build()
.unwrap();
let module_alpha_background = 1.0;
let module_alpha_foreground = 1.0;
Model {
tile_count: 20,
act_random_seed: 0,
module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background),
module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground),
module_alpha_background,
module_alpha_foreground, | identifier_body |
stat.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.
use std::io::{File, TempDir};
pub fn main() {
let dir = TempDir::new_in(&Path::new("."), "").unwrap();
let path = dir.path().join("file");
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write([0]);
}
}
}
}
assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000); | } | random_line_split |
|
stat.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.
use std::io::{File, TempDir};
pub fn | () {
let dir = TempDir::new_in(&Path::new("."), "").unwrap();
let path = dir.path().join("file");
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write([0]);
}
}
}
}
assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000);
}
| main | identifier_name |
stat.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.
use std::io::{File, TempDir};
pub fn main() | {
let dir = TempDir::new_in(&Path::new("."), "").unwrap();
let path = dir.path().join("file");
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write([0]);
}
}
}
}
assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000);
} | identifier_body |
|
keymap.rs | ) -> i32 {
(c as i32) & 0x1f
}
// Hash table used to cache a reverse-map to speed up calls to where-is.
declare_GC_protected_static!(where_is_cache, Qnil);
/// Allows the C code to get the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn get_where_is_cache() -> LispObject {
unsafe { where_is_cache }
}
/// Allows the C code to set the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn set_where_is_cache(val: LispObject) {
unsafe {
where_is_cache = val;
}
}
// Which keymaps are reverse-stored in the cache.
declare_GC_protected_static!(where_is_cache_keymaps, Qt);
/// Allows the C code to get the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn get_where_is_cache_keymaps() -> LispObject {
unsafe { where_is_cache_keymaps }
}
/// Allows the C code to set the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn set_where_is_cache_keymaps(val: LispObject) {
unsafe {
where_is_cache_keymaps = val;
}
}
/// Check that OBJECT is a keymap (after dereferencing through any
/// symbols). If it is, return it.
///
/// If AUTOLOAD and if OBJECT is a symbol whose function value
/// is an autoload form, do the autoload and try again.
/// If AUTOLOAD, callers must assume GC is possible.
///
/// `ERROR_IF_NOT_KEYMAP` controls how we respond if OBJECT isn't a keymap.
/// If `ERROR_IF_NOT_KEYMAP`, signal an error; otherwise,
/// just return Qnil.
///
/// Note that most of the time, we don't want to pursue autoloads.
/// Functions like `Faccessible_keymaps` which scan entire keymap trees
/// shouldn't load every autoloaded keymap. I'm not sure about this,
/// but it seems to me that only `read_key_sequence`, `Flookup_key`, and
/// `Fdefine_key` should cause keymaps to be autoloaded.
///
/// This function can GC when AUTOLOAD is true, because it calls
/// `Fautoload_do_load` which can GC.
#[no_mangle]
pub extern "C" fn get_keymap(
object: LispObject,
error_if_not_keymap: bool,
autoload: bool,
) -> LispObject {
let object = object;
let mut autoload_retry = true;
while autoload_retry {
autoload_retry = false;
if object.is_nil() {
break;
}
if let Some((car, _)) = object.into() {
if car.eq(Qkeymap) {
return object;
}
}
let tem = indirect_function(object);
if let Some((car, _)) = tem.into() {
if car.eq(Qkeymap) {
return tem;
}
// Should we do an autoload? Autoload forms for keymaps have
// Qkeymap as their fifth element.
if (autoload ||!error_if_not_keymap) && car.eq(Qautoload) && object.is_symbol() {
let tail = nth(4, tem);
if tail.eq(Qkeymap) {
if autoload {
autoload_do_load(tem, object, Qnil);
autoload_retry = true;
} else {
return object;
}
}
}
}
}
if error_if_not_keymap {
wrong_type!(Qkeymapp, object);
}
Qnil
}
/// Construct and return a new keymap, of the form (keymap CHARTABLE. ALIST).
/// CHARTABLE is a char-table that holds the bindings for all characters
/// without modifiers. All entries in it are initially nil, meaning
/// "command undefined". ALIST is an assoc-list which holds bindings for
/// function keys, mouse events, and any other things that appear in the
/// input stream. Initially, ALIST is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_keymap(string: LispObject) -> (LispObject, (LispObject, LispObject)) {
let tail: LispObject = if string.is_not_nil() {
list!(string)
} else {
Qnil
};
let char_table = unsafe { Fmake_char_table(Qkeymap, Qnil) };
(Qkeymap, (char_table, tail))
}
/// Return t if OBJECT is a keymap.
///
/// A keymap is a list (keymap. ALIST),
/// or a symbol whose function definition is itself a keymap.
/// ALIST elements look like (CHAR. DEFN) or (SYMBOL. DEFN);
/// a vector of densely packed bindings for small character codes
/// is also allowed as an element.
#[lisp_fn]
pub fn keymapp(object: LispObject) -> bool {
let map = get_keymap(object, false, false);
map.is_not_nil()
}
/// Return the parent map of KEYMAP, or nil if it has none.
/// We assume that KEYMAP is a valid keymap.
#[no_mangle]
pub extern "C" fn keymap_parent(keymap: LispObject, autoload: bool) -> LispObject |
/// Return the parent keymap of KEYMAP.
/// If KEYMAP has no parent, return nil.
#[lisp_fn(name = "keymap-parent", c_name = "keymap_parent")]
pub fn keymap_parent_lisp(keymap: LispObject) -> LispObject {
keymap_parent(keymap, true)
}
/// Check whether MAP is one of MAPS parents.
#[no_mangle]
pub extern "C" fn keymap_memberp(map: LispObject, maps: LispObject) -> bool {
let map = map;
let mut maps = maps;
if map.is_nil() {
return false;
}
while keymapp(maps) &&!map.eq(maps) {
maps = keymap_parent(maps, false);
}
map.eq(maps)
}
/// Modify KEYMAP to set its parent map to PARENT.
/// Return PARENT. PARENT should be nil or another keymap.
#[lisp_fn]
pub fn set_keymap_parent(keymap: LispObject, parent: LispObject) -> LispObject {
// Flush any reverse-map cache
unsafe {
where_is_cache = Qnil;
where_is_cache_keymaps = Qt;
}
let mut parent = parent;
let keymap = get_keymap(keymap, true, true);
if parent.is_not_nil() {
parent = get_keymap(parent, true, false);
// Check for cycles
if keymap_memberp(keymap, parent) {
error!("Cyclic keymap inheritance");
}
}
// Skip past the initial element 'keymap'.
let mut prev = LispCons::from(keymap);
let mut list;
loop {
list = prev.cdr();
// If there is a parent keymap here, replace it.
// If we came to the end, add the parent in PREV.
match list.as_cons() {
None => break,
Some(cons) => {
if keymapp(list) {
break;
} else {
prev = cons;
}
}
}
}
prev.check_impure();
prev.set_cdr(parent);
parent
}
/// Return the prompt-string of a keymap MAP.
/// If non-nil, the prompt is shown in the echo-area
/// when reading a key-sequence to be looked-up in this keymap.
#[lisp_fn]
pub fn keymap_prompt(map: LispObject) -> LispObject {
let map = get_keymap(map, false, false);
for elt in map.iter_cars(LispConsEndChecks::off, LispConsCircularChecks::off) {
let mut tem = elt;
if tem.is_string() {
return tem;
} else if keymapp(tem) {
tem = keymap_prompt(tem);
if tem.is_not_nil() {
return tem;
}
}
}
Qnil
}
/// Same as `map_keymap_internal`, but traverses parent keymaps as well.
/// AUTOLOAD indicates that autoloaded keymaps should be loaded.
#[no_mangle]
pub unsafe extern "C" fn map_keymap(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
autoload: bool,
) {
let mut map = get_keymap(map, true, autoload);
while map.is_cons() {
if let Some((car, cdr)) = map.into() {
if keymapp(car) {
map_keymap(car, fun, args, data, autoload);
map = cdr;
} else {
map = map_keymap_internal(map, fun, args, data);
}
}
if!map.is_cons() {
map = get_keymap(map, false, autoload);
}
}
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
///
/// If KEYMAP has a parent, the parent's bindings are included as well.
/// This works recursively: if the parent has itself a parent, then the
/// grandparent's bindings are also included and so on.
/// usage: (map-keymap FUNCTION KEYMAP)
#[lisp_fn(name = "map-keymap", c_name = "map_keymap", min = "2")]
pub fn map_keymap_lisp(function: LispObject, keymap: LispObject, sort_first: bool) -> LispObject {
if sort_first {
return call!(intern("map-keymap-sorted").into(), function, keymap);
}
unsafe {
map_keymap(
keymap,
Some(map_keymap_call),
function,
ptr::null_mut(),
true,
)
};
Qnil
}
/// Call FUN for every binding in MAP and stop at (and return) the parent.
/// FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA).
#[no_mangle]
pub unsafe extern "C" fn map_keymap_internal(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
) -> LispObject {
let map = map;
let tail = match map.into() {
None => Qnil,
Some((car, cdr)) => {
if car.eq(Qkeymap) {
cdr
} else {
map
}
}
};
let mut parent = tail;
for tail_cons in tail.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
let binding = tail_cons.car();
if binding.eq(Qkeymap) {
break;
} else {
// An embedded parent.
if keymapp(binding) {
break;
}
if let Some((car, cdr)) = binding.into() {
map_keymap_item(fun, args, car, cdr, data);
} else if binding.is_vector() {
if let Some(binding_vec) = binding.as_vectorlike() {
for c in 0..binding_vec.pseudovector_size() {
map_keymap_item(fun, args, c.into(), aref(binding, c), data);
}
}
} else if binding.is_char_table() {
let saved = match fun {
Some(f) => make_save_funcptr_ptr_obj(Some(std::mem::transmute(f)), data, args),
None => make_save_funcptr_ptr_obj(None, data, args),
};
map_char_table(Some(map_keymap_char_table_item), Qnil, binding, saved);
}
}
parent = tail_cons.cdr();
}
parent
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
/// If KEYMAP has a parent, this function returns it without processing it.
#[lisp_fn(name = "map-keymap-internal", c_name = "map_keymap_internal")]
pub fn map_keymap_internal_lisp(function: LispObject, mut keymap: LispObject) -> LispObject {
keymap = get_keymap(keymap, true, true);
unsafe { map_keymap_internal(keymap, Some(map_keymap_call), function, ptr::null_mut()) }
}
/// Return the binding for command KEYS in current local keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn local_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_local_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return current buffer's local keymap, or nil if it has none.
/// Normally the local keymap is set by the major mode with `use-local-map'.
#[lisp_fn]
pub fn current_local_map() -> LispObject {
ThreadState::current_buffer_unchecked().keymap_
}
/// Select KEYMAP as the local keymap.
/// If KEYMAP is nil, that means no local keymap.
#[lisp_fn]
pub fn use_local_map(mut keymap: LispObject) {
if!keymap.is_nil() {
let map = get_keymap(keymap, true, true);
keymap = map;
}
ThreadState::current_buffer_unchecked().keymap_ = keymap;
}
/// Return the binding for command KEYS in current global keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// This function's return values are the same as those of `lookup-key'
/// (which see).
///
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn global_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_global_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return the current global keymap.
#[lisp_fn]
pub fn current_global_map() -> LispObject {
unsafe { _current_global_map }
}
/// Select KEYMAP as the global keymap.
#[lisp_fn]
pub fn use_global_map(keymap: LispObject) {
unsafe { _current_global_map = get_keymap(keymap, true, true) };
}
// Value is number if KEY is too long; nil if valid but has no definition.
// GC is possible in this function.
/// In keymap KEYMAP, look up key sequence KEY. Return the definition.
/// A value of nil means undefined. See doc of `define-key'
/// for kinds of definitions.
///
/// A number as value means KEY is "too long";
/// that is, characters or symbols in it except for the last one
/// fail to be a valid sequence of prefix characters in KEYMAP.
/// The number is how many characters at the front of KEY
/// it takes to reach a non-prefix key.
///
/// Normally, `lookup-key' ignores bindings for t, which act as default
/// bindings, used when nothing else in the keymap applies; this makes it
/// usable as a general function for probing keymaps. However, if the
/// third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will
/// recognize the default bindings, just as `read-key-sequence' does.
#[lisp_fn(min = "2")]
pub fn lookup_key(keymap: LispObject, key: LispObject, accept_default: LispObject) -> LispObject {
let ok = accept_default.is_not_nil();
let mut keymap = get_keymap(keymap, true, true);
let length = key.as_vector_or_string_length() as EmacsInt;
if length == 0 {
return keymap;
}
let mut idx = 0;
loop {
let mut c = aref(key, idx);
idx += 1;
if c.is_cons() && lucid_event_type_list_p(c.into()) {
c = unsafe { Fevent_convert_list(c) };
}
// Turn the 8th bit of string chars into a meta modifier.
if let Some(k) = key.as_string() {
if let Some(x) = c.as_fixnum() {
let x = x as u32;
if x & 0x80!= 0 &&!k.is_multibyte() {
c = ((x | char_bits::CHAR_META) &!0x80).into();
}
}
}
// Allow string since binding for `menu-bar-select-buffer'
// includes the buffer name in the key sequence.
if!(c.is_fixnum() || c.is_symbol() || c.is_cons() || c.is_string()) {
message_with_string!("Key sequence contains invalid event %s", c, true);
}
let cmd = unsafe { access_keymap(keymap, c, ok, false, true) };
if idx == length {
return cmd;
}
keymap = get_keymap(cmd, false, true);
if!keymap.is_cons() {
return idx.into();
}
unsafe {
maybe_quit();
};
}
}
/// Define COMMAND as a prefix command. COMMAND should be a symbol.
/// A new sparse keymap is stored as COMMAND's function definition and its
/// value.
/// This prepares COMMAND for use as a prefix key's binding.
/// If a second optional argument MAPVAR is given, it should be a symbol.
/// The map is then stored as MAPVAR's value instead of as COMMAND's
/// value; but COMMAND is still defined as a function.
/// The third optional argument NAME, if given, supplies a menu name
/// string for the map. This is required to use the keymap as a menu.
/// This function returns COMMAND.
#[lisp_fn(min = "1")]
pub fn define_prefix_command(
command: LispSymbolRef,
mapvar: LispObject,
name: LispObject,
) -> LispSymbolRef {
let map = make_sparse_keymap(name);
fset(command, map);
if mapvar.is_not_nil() {
set(mapvar.into(), map);
} else {
set(command, map);
}
command
}
/// Construct and return a new sparse keymap.
/// Its car is `keymap' and its cdr is an alist of (CHAR. DEFINITION),
/// which binds the character CHAR to DEFINITION, or (SYMBOL. DEFINITION),
/// which binds the function key or mouse event SYMBOL to DEFINITION.
/// Initially the alist is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_sparse_keymap(string: LispObject) -> LispObject {
if string.is_not_nil() {
let s = if unsafe { globals.Vpurify_flag }.is_not_nil() {
unsafe { Fpurecopy(string) }
} else {
string
};
list!(Qkeymap, s)
} else {
list!(Qkeymap)
}
}
#[no_mangle]
pub extern "C" fn describe_vector_princ(elt: LispObject, fun: LispObject) {
indent_to(16, 1.into());
call!(fun, elt);
unsafe { Fterpri(Qnil, Qnil) };
}
/// Insert a description of contents of VECTOR.
/// This is text showing the elements of vector matched against indices.
/// DESCRIBER is the output function used; nil means use `princ'.
#[lisp_fn(min = "1", name = "describe-vector", c_name = "describe_vector")]
pub fn describe_vector_lisp(vector: LispObject, mut describer: LispObject) {
if describer.is_nil() {
describer = intern("princ").into();
}
unsafe { specbind(Qstandard_output, current_buffer()) };
if!(vector.is_vector() || vector.is_char_table()) {
wrong_type!(Qvector_or_char_table_p, vector);
}
let count = c_specpdl_index();
unsafe {
describe_vector(
vector,
Qnil,
describer,
Some(describe_vector_princ),
false,
Qnil,
Qnil,
false,
false,
)
};
unbind_to(count, Qnil);
}
#[no_mangle]
pub extern "C" fn copy_keymap_1(chartable: LispObject, idx: LispObject, elt: LispObject) {
unsafe { Fset_char_table_range(chartable, idx, copy_keymap_item(elt)) };
}
/// Return a copy of the keymap KEYMAP.
///
/// Note that this is almost never needed. If you want a keymap that's like
/// another yet with a few changes, you should use map inheritance rather
/// than copying. I.e. something like:
///
/// (let ((map (make-sparse-keymap)))
/// (set-keymap-parent map <theirmap>)
/// (define-key map...)
///...)
///
/// After performing `copy-keymap', the copy starts out with the same definitions
/// of KEYMAP, but changing either the copy or KEYMAP does not affect the other.
/// Any key definitions that are subkeymaps are recursively copied.
/// However, a key definition which is a symbol whose definition is a keymap
/// is not copied.
#[lisp_fn]
pub fn copy_keymap(keymap: LispObject) -> LispObject {
let keymap = get_keymap(keymap, true, false);
let mut tail = list!(Qkeymap);
let copy = tail;
let (_, mut keymap) = keymap.into(); // Skip the `keymap' symbol.
while let Some((mut elt, kmd)) = keymap.into() {
if elt.eq(Qkeymap) {
break;
}
if elt.is_char_table() {
elt = unsafe { Fcopy_sequence(elt) };
unsafe { map_char_table(Some(copy_keymap_1), Qnil, elt, elt) };
} else if let Some(v) = elt.as_vector() {
elt = unsafe { Fcopy_sequence(elt) };
let mut v2 = elt.as_vector().unwrap();
for (i, obj) in v.iter().enumerate() {
v2.set(i, unsafe { copy_keymap_item(obj) });
}
} else if let Some((front, back)) = elt.into() {
if front.eq(Qkeymap) {
// This is a sub keymap
elt = copy_keymap(elt);
| {
let map = get_keymap(keymap, true, autoload);
let mut current = Qnil;
for elt in map.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
current = elt.cdr();
if keymapp(current) {
return current;
}
}
get_keymap(current, false, autoload)
} | identifier_body |
keymap.rs | ) -> i32 {
(c as i32) & 0x1f
}
// Hash table used to cache a reverse-map to speed up calls to where-is.
declare_GC_protected_static!(where_is_cache, Qnil);
/// Allows the C code to get the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn get_where_is_cache() -> LispObject {
unsafe { where_is_cache }
}
/// Allows the C code to set the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn set_where_is_cache(val: LispObject) {
unsafe {
where_is_cache = val;
}
}
// Which keymaps are reverse-stored in the cache.
declare_GC_protected_static!(where_is_cache_keymaps, Qt);
/// Allows the C code to get the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn get_where_is_cache_keymaps() -> LispObject {
unsafe { where_is_cache_keymaps }
}
/// Allows the C code to set the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn set_where_is_cache_keymaps(val: LispObject) {
unsafe {
where_is_cache_keymaps = val;
}
}
/// Check that OBJECT is a keymap (after dereferencing through any
/// symbols). If it is, return it.
///
/// If AUTOLOAD and if OBJECT is a symbol whose function value
/// is an autoload form, do the autoload and try again.
/// If AUTOLOAD, callers must assume GC is possible.
///
/// `ERROR_IF_NOT_KEYMAP` controls how we respond if OBJECT isn't a keymap.
/// If `ERROR_IF_NOT_KEYMAP`, signal an error; otherwise,
/// just return Qnil.
///
/// Note that most of the time, we don't want to pursue autoloads.
/// Functions like `Faccessible_keymaps` which scan entire keymap trees
/// shouldn't load every autoloaded keymap. I'm not sure about this,
/// but it seems to me that only `read_key_sequence`, `Flookup_key`, and
/// `Fdefine_key` should cause keymaps to be autoloaded.
///
/// This function can GC when AUTOLOAD is true, because it calls
/// `Fautoload_do_load` which can GC.
#[no_mangle]
pub extern "C" fn get_keymap(
object: LispObject,
error_if_not_keymap: bool,
autoload: bool,
) -> LispObject {
let object = object;
let mut autoload_retry = true;
while autoload_retry {
autoload_retry = false;
if object.is_nil() {
break;
}
if let Some((car, _)) = object.into() {
if car.eq(Qkeymap) {
return object;
}
}
let tem = indirect_function(object);
if let Some((car, _)) = tem.into() {
if car.eq(Qkeymap) {
return tem;
}
// Should we do an autoload? Autoload forms for keymaps have
// Qkeymap as their fifth element.
if (autoload ||!error_if_not_keymap) && car.eq(Qautoload) && object.is_symbol() {
let tail = nth(4, tem);
if tail.eq(Qkeymap) {
if autoload {
autoload_do_load(tem, object, Qnil);
autoload_retry = true;
} else {
return object;
}
}
}
}
}
if error_if_not_keymap {
wrong_type!(Qkeymapp, object);
}
Qnil
}
/// Construct and return a new keymap, of the form (keymap CHARTABLE. ALIST).
/// CHARTABLE is a char-table that holds the bindings for all characters
/// without modifiers. All entries in it are initially nil, meaning
/// "command undefined". ALIST is an assoc-list which holds bindings for
/// function keys, mouse events, and any other things that appear in the
/// input stream. Initially, ALIST is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_keymap(string: LispObject) -> (LispObject, (LispObject, LispObject)) {
let tail: LispObject = if string.is_not_nil() {
list!(string)
} else {
Qnil
};
let char_table = unsafe { Fmake_char_table(Qkeymap, Qnil) };
(Qkeymap, (char_table, tail))
}
/// Return t if OBJECT is a keymap.
///
/// A keymap is a list (keymap. ALIST),
/// or a symbol whose function definition is itself a keymap.
/// ALIST elements look like (CHAR. DEFN) or (SYMBOL. DEFN);
/// a vector of densely packed bindings for small character codes
/// is also allowed as an element.
#[lisp_fn]
pub fn keymapp(object: LispObject) -> bool {
let map = get_keymap(object, false, false);
map.is_not_nil()
}
/// Return the parent map of KEYMAP, or nil if it has none.
/// We assume that KEYMAP is a valid keymap.
#[no_mangle]
pub extern "C" fn keymap_parent(keymap: LispObject, autoload: bool) -> LispObject {
let map = get_keymap(keymap, true, autoload);
let mut current = Qnil;
for elt in map.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
current = elt.cdr();
if keymapp(current) {
return current;
}
}
get_keymap(current, false, autoload)
}
/// Return the parent keymap of KEYMAP.
/// If KEYMAP has no parent, return nil.
#[lisp_fn(name = "keymap-parent", c_name = "keymap_parent")]
pub fn keymap_parent_lisp(keymap: LispObject) -> LispObject {
keymap_parent(keymap, true)
}
/// Check whether MAP is one of MAPS parents.
#[no_mangle]
pub extern "C" fn keymap_memberp(map: LispObject, maps: LispObject) -> bool {
let map = map;
let mut maps = maps;
if map.is_nil() {
return false;
}
while keymapp(maps) &&!map.eq(maps) {
maps = keymap_parent(maps, false);
}
map.eq(maps)
}
/// Modify KEYMAP to set its parent map to PARENT.
/// Return PARENT. PARENT should be nil or another keymap.
#[lisp_fn]
pub fn set_keymap_parent(keymap: LispObject, parent: LispObject) -> LispObject {
// Flush any reverse-map cache
unsafe {
where_is_cache = Qnil;
where_is_cache_keymaps = Qt;
}
let mut parent = parent;
let keymap = get_keymap(keymap, true, true);
if parent.is_not_nil() {
parent = get_keymap(parent, true, false);
// Check for cycles
if keymap_memberp(keymap, parent) {
error!("Cyclic keymap inheritance");
}
}
// Skip past the initial element 'keymap'.
let mut prev = LispCons::from(keymap);
let mut list;
loop {
list = prev.cdr();
// If there is a parent keymap here, replace it.
// If we came to the end, add the parent in PREV.
match list.as_cons() {
None => break,
Some(cons) => {
if keymapp(list) {
break;
} else {
prev = cons;
}
}
}
}
prev.check_impure();
prev.set_cdr(parent);
parent
}
/// Return the prompt-string of a keymap MAP.
/// If non-nil, the prompt is shown in the echo-area
/// when reading a key-sequence to be looked-up in this keymap.
#[lisp_fn]
pub fn keymap_prompt(map: LispObject) -> LispObject {
let map = get_keymap(map, false, false);
for elt in map.iter_cars(LispConsEndChecks::off, LispConsCircularChecks::off) {
let mut tem = elt;
if tem.is_string() {
return tem;
} else if keymapp(tem) {
tem = keymap_prompt(tem);
if tem.is_not_nil() {
return tem;
}
}
}
Qnil
}
/// Same as `map_keymap_internal`, but traverses parent keymaps as well.
/// AUTOLOAD indicates that autoloaded keymaps should be loaded.
#[no_mangle]
pub unsafe extern "C" fn map_keymap(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
autoload: bool,
) {
let mut map = get_keymap(map, true, autoload);
while map.is_cons() {
if let Some((car, cdr)) = map.into() {
if keymapp(car) {
map_keymap(car, fun, args, data, autoload);
map = cdr;
} else {
map = map_keymap_internal(map, fun, args, data);
}
}
if!map.is_cons() {
map = get_keymap(map, false, autoload);
}
}
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
///
/// If KEYMAP has a parent, the parent's bindings are included as well.
/// This works recursively: if the parent has itself a parent, then the
/// grandparent's bindings are also included and so on.
/// usage: (map-keymap FUNCTION KEYMAP)
#[lisp_fn(name = "map-keymap", c_name = "map_keymap", min = "2")]
pub fn map_keymap_lisp(function: LispObject, keymap: LispObject, sort_first: bool) -> LispObject {
if sort_first {
return call!(intern("map-keymap-sorted").into(), function, keymap);
}
unsafe {
map_keymap(
keymap,
Some(map_keymap_call),
function,
ptr::null_mut(),
true,
)
};
Qnil
}
/// Call FUN for every binding in MAP and stop at (and return) the parent.
/// FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA).
#[no_mangle]
pub unsafe extern "C" fn map_keymap_internal(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
) -> LispObject {
let map = map;
let tail = match map.into() {
None => Qnil,
Some((car, cdr)) => {
if car.eq(Qkeymap) {
cdr
} else {
map
}
}
};
let mut parent = tail;
for tail_cons in tail.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
let binding = tail_cons.car();
if binding.eq(Qkeymap) {
break;
} else {
// An embedded parent.
if keymapp(binding) {
break;
}
if let Some((car, cdr)) = binding.into() | else if binding.is_vector() {
if let Some(binding_vec) = binding.as_vectorlike() {
for c in 0..binding_vec.pseudovector_size() {
map_keymap_item(fun, args, c.into(), aref(binding, c), data);
}
}
} else if binding.is_char_table() {
let saved = match fun {
Some(f) => make_save_funcptr_ptr_obj(Some(std::mem::transmute(f)), data, args),
None => make_save_funcptr_ptr_obj(None, data, args),
};
map_char_table(Some(map_keymap_char_table_item), Qnil, binding, saved);
}
}
parent = tail_cons.cdr();
}
parent
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
/// If KEYMAP has a parent, this function returns it without processing it.
#[lisp_fn(name = "map-keymap-internal", c_name = "map_keymap_internal")]
pub fn map_keymap_internal_lisp(function: LispObject, mut keymap: LispObject) -> LispObject {
keymap = get_keymap(keymap, true, true);
unsafe { map_keymap_internal(keymap, Some(map_keymap_call), function, ptr::null_mut()) }
}
/// Return the binding for command KEYS in current local keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn local_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_local_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return current buffer's local keymap, or nil if it has none.
/// Normally the local keymap is set by the major mode with `use-local-map'.
#[lisp_fn]
pub fn current_local_map() -> LispObject {
ThreadState::current_buffer_unchecked().keymap_
}
/// Select KEYMAP as the local keymap.
/// If KEYMAP is nil, that means no local keymap.
#[lisp_fn]
pub fn use_local_map(mut keymap: LispObject) {
if!keymap.is_nil() {
let map = get_keymap(keymap, true, true);
keymap = map;
}
ThreadState::current_buffer_unchecked().keymap_ = keymap;
}
/// Return the binding for command KEYS in current global keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// This function's return values are the same as those of `lookup-key'
/// (which see).
///
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn global_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_global_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return the current global keymap.
#[lisp_fn]
pub fn current_global_map() -> LispObject {
unsafe { _current_global_map }
}
/// Select KEYMAP as the global keymap.
#[lisp_fn]
pub fn use_global_map(keymap: LispObject) {
unsafe { _current_global_map = get_keymap(keymap, true, true) };
}
// Value is number if KEY is too long; nil if valid but has no definition.
// GC is possible in this function.
/// In keymap KEYMAP, look up key sequence KEY. Return the definition.
/// A value of nil means undefined. See doc of `define-key'
/// for kinds of definitions.
///
/// A number as value means KEY is "too long";
/// that is, characters or symbols in it except for the last one
/// fail to be a valid sequence of prefix characters in KEYMAP.
/// The number is how many characters at the front of KEY
/// it takes to reach a non-prefix key.
///
/// Normally, `lookup-key' ignores bindings for t, which act as default
/// bindings, used when nothing else in the keymap applies; this makes it
/// usable as a general function for probing keymaps. However, if the
/// third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will
/// recognize the default bindings, just as `read-key-sequence' does.
#[lisp_fn(min = "2")]
pub fn lookup_key(keymap: LispObject, key: LispObject, accept_default: LispObject) -> LispObject {
let ok = accept_default.is_not_nil();
let mut keymap = get_keymap(keymap, true, true);
let length = key.as_vector_or_string_length() as EmacsInt;
if length == 0 {
return keymap;
}
let mut idx = 0;
loop {
let mut c = aref(key, idx);
idx += 1;
if c.is_cons() && lucid_event_type_list_p(c.into()) {
c = unsafe { Fevent_convert_list(c) };
}
// Turn the 8th bit of string chars into a meta modifier.
if let Some(k) = key.as_string() {
if let Some(x) = c.as_fixnum() {
let x = x as u32;
if x & 0x80!= 0 &&!k.is_multibyte() {
c = ((x | char_bits::CHAR_META) &!0x80).into();
}
}
}
// Allow string since binding for `menu-bar-select-buffer'
// includes the buffer name in the key sequence.
if!(c.is_fixnum() || c.is_symbol() || c.is_cons() || c.is_string()) {
message_with_string!("Key sequence contains invalid event %s", c, true);
}
let cmd = unsafe { access_keymap(keymap, c, ok, false, true) };
if idx == length {
return cmd;
}
keymap = get_keymap(cmd, false, true);
if!keymap.is_cons() {
return idx.into();
}
unsafe {
maybe_quit();
};
}
}
/// Define COMMAND as a prefix command. COMMAND should be a symbol.
/// A new sparse keymap is stored as COMMAND's function definition and its
/// value.
/// This prepares COMMAND for use as a prefix key's binding.
/// If a second optional argument MAPVAR is given, it should be a symbol.
/// The map is then stored as MAPVAR's value instead of as COMMAND's
/// value; but COMMAND is still defined as a function.
/// The third optional argument NAME, if given, supplies a menu name
/// string for the map. This is required to use the keymap as a menu.
/// This function returns COMMAND.
#[lisp_fn(min = "1")]
pub fn define_prefix_command(
command: LispSymbolRef,
mapvar: LispObject,
name: LispObject,
) -> LispSymbolRef {
let map = make_sparse_keymap(name);
fset(command, map);
if mapvar.is_not_nil() {
set(mapvar.into(), map);
} else {
set(command, map);
}
command
}
/// Construct and return a new sparse keymap.
/// Its car is `keymap' and its cdr is an alist of (CHAR. DEFINITION),
/// which binds the character CHAR to DEFINITION, or (SYMBOL. DEFINITION),
/// which binds the function key or mouse event SYMBOL to DEFINITION.
/// Initially the alist is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_sparse_keymap(string: LispObject) -> LispObject {
if string.is_not_nil() {
let s = if unsafe { globals.Vpurify_flag }.is_not_nil() {
unsafe { Fpurecopy(string) }
} else {
string
};
list!(Qkeymap, s)
} else {
list!(Qkeymap)
}
}
#[no_mangle]
pub extern "C" fn describe_vector_princ(elt: LispObject, fun: LispObject) {
indent_to(16, 1.into());
call!(fun, elt);
unsafe { Fterpri(Qnil, Qnil) };
}
/// Insert a description of contents of VECTOR.
/// This is text showing the elements of vector matched against indices.
/// DESCRIBER is the output function used; nil means use `princ'.
#[lisp_fn(min = "1", name = "describe-vector", c_name = "describe_vector")]
pub fn describe_vector_lisp(vector: LispObject, mut describer: LispObject) {
if describer.is_nil() {
describer = intern("princ").into();
}
unsafe { specbind(Qstandard_output, current_buffer()) };
if!(vector.is_vector() || vector.is_char_table()) {
wrong_type!(Qvector_or_char_table_p, vector);
}
let count = c_specpdl_index();
unsafe {
describe_vector(
vector,
Qnil,
describer,
Some(describe_vector_princ),
false,
Qnil,
Qnil,
false,
false,
)
};
unbind_to(count, Qnil);
}
#[no_mangle]
pub extern "C" fn copy_keymap_1(chartable: LispObject, idx: LispObject, elt: LispObject) {
unsafe { Fset_char_table_range(chartable, idx, copy_keymap_item(elt)) };
}
/// Return a copy of the keymap KEYMAP.
///
/// Note that this is almost never needed. If you want a keymap that's like
/// another yet with a few changes, you should use map inheritance rather
/// than copying. I.e. something like:
///
/// (let ((map (make-sparse-keymap)))
/// (set-keymap-parent map <theirmap>)
/// (define-key map...)
///...)
///
/// After performing `copy-keymap', the copy starts out with the same definitions
/// of KEYMAP, but changing either the copy or KEYMAP does not affect the other.
/// Any key definitions that are subkeymaps are recursively copied.
/// However, a key definition which is a symbol whose definition is a keymap
/// is not copied.
#[lisp_fn]
pub fn copy_keymap(keymap: LispObject) -> LispObject {
let keymap = get_keymap(keymap, true, false);
let mut tail = list!(Qkeymap);
let copy = tail;
let (_, mut keymap) = keymap.into(); // Skip the `keymap' symbol.
while let Some((mut elt, kmd)) = keymap.into() {
if elt.eq(Qkeymap) {
break;
}
if elt.is_char_table() {
elt = unsafe { Fcopy_sequence(elt) };
unsafe { map_char_table(Some(copy_keymap_1), Qnil, elt, elt) };
} else if let Some(v) = elt.as_vector() {
elt = unsafe { Fcopy_sequence(elt) };
let mut v2 = elt.as_vector().unwrap();
for (i, obj) in v.iter().enumerate() {
v2.set(i, unsafe { copy_keymap_item(obj) });
}
} else if let Some((front, back)) = elt.into() {
if front.eq(Qkeymap) {
// This is a sub keymap
elt = copy_keymap(elt);
| {
map_keymap_item(fun, args, car, cdr, data);
} | conditional_block |
keymap.rs | char) -> i32 {
(c as i32) & 0x1f
}
// Hash table used to cache a reverse-map to speed up calls to where-is.
declare_GC_protected_static!(where_is_cache, Qnil);
/// Allows the C code to get the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn get_where_is_cache() -> LispObject {
unsafe { where_is_cache }
}
/// Allows the C code to set the value of `where_is_cache`
#[no_mangle]
pub extern "C" fn set_where_is_cache(val: LispObject) {
unsafe {
where_is_cache = val;
}
}
// Which keymaps are reverse-stored in the cache.
declare_GC_protected_static!(where_is_cache_keymaps, Qt);
/// Allows the C code to get the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn get_where_is_cache_keymaps() -> LispObject {
unsafe { where_is_cache_keymaps }
}
/// Allows the C code to set the value of `where_is_cache_keymaps`
#[no_mangle]
pub extern "C" fn set_where_is_cache_keymaps(val: LispObject) {
unsafe {
where_is_cache_keymaps = val;
}
}
/// Check that OBJECT is a keymap (after dereferencing through any
/// symbols). If it is, return it.
///
/// If AUTOLOAD and if OBJECT is a symbol whose function value
/// is an autoload form, do the autoload and try again.
/// If AUTOLOAD, callers must assume GC is possible.
///
/// `ERROR_IF_NOT_KEYMAP` controls how we respond if OBJECT isn't a keymap.
/// If `ERROR_IF_NOT_KEYMAP`, signal an error; otherwise,
/// just return Qnil.
///
/// Note that most of the time, we don't want to pursue autoloads.
/// Functions like `Faccessible_keymaps` which scan entire keymap trees
/// shouldn't load every autoloaded keymap. I'm not sure about this,
/// but it seems to me that only `read_key_sequence`, `Flookup_key`, and
/// `Fdefine_key` should cause keymaps to be autoloaded.
///
/// This function can GC when AUTOLOAD is true, because it calls
/// `Fautoload_do_load` which can GC.
#[no_mangle]
pub extern "C" fn get_keymap(
object: LispObject,
error_if_not_keymap: bool,
autoload: bool,
) -> LispObject {
let object = object;
let mut autoload_retry = true;
while autoload_retry {
autoload_retry = false;
if object.is_nil() {
break;
}
if let Some((car, _)) = object.into() {
if car.eq(Qkeymap) {
return object;
}
}
let tem = indirect_function(object);
if let Some((car, _)) = tem.into() {
if car.eq(Qkeymap) {
return tem;
}
// Should we do an autoload? Autoload forms for keymaps have
// Qkeymap as their fifth element.
if (autoload ||!error_if_not_keymap) && car.eq(Qautoload) && object.is_symbol() {
let tail = nth(4, tem);
if tail.eq(Qkeymap) {
if autoload {
autoload_do_load(tem, object, Qnil);
autoload_retry = true;
} else {
return object;
}
}
}
}
}
if error_if_not_keymap {
wrong_type!(Qkeymapp, object);
}
Qnil |
/// Construct and return a new keymap, of the form (keymap CHARTABLE. ALIST).
/// CHARTABLE is a char-table that holds the bindings for all characters
/// without modifiers. All entries in it are initially nil, meaning
/// "command undefined". ALIST is an assoc-list which holds bindings for
/// function keys, mouse events, and any other things that appear in the
/// input stream. Initially, ALIST is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_keymap(string: LispObject) -> (LispObject, (LispObject, LispObject)) {
let tail: LispObject = if string.is_not_nil() {
list!(string)
} else {
Qnil
};
let char_table = unsafe { Fmake_char_table(Qkeymap, Qnil) };
(Qkeymap, (char_table, tail))
}
/// Return t if OBJECT is a keymap.
///
/// A keymap is a list (keymap. ALIST),
/// or a symbol whose function definition is itself a keymap.
/// ALIST elements look like (CHAR. DEFN) or (SYMBOL. DEFN);
/// a vector of densely packed bindings for small character codes
/// is also allowed as an element.
#[lisp_fn]
pub fn keymapp(object: LispObject) -> bool {
let map = get_keymap(object, false, false);
map.is_not_nil()
}
/// Return the parent map of KEYMAP, or nil if it has none.
/// We assume that KEYMAP is a valid keymap.
#[no_mangle]
pub extern "C" fn keymap_parent(keymap: LispObject, autoload: bool) -> LispObject {
let map = get_keymap(keymap, true, autoload);
let mut current = Qnil;
for elt in map.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
current = elt.cdr();
if keymapp(current) {
return current;
}
}
get_keymap(current, false, autoload)
}
/// Return the parent keymap of KEYMAP.
/// If KEYMAP has no parent, return nil.
#[lisp_fn(name = "keymap-parent", c_name = "keymap_parent")]
pub fn keymap_parent_lisp(keymap: LispObject) -> LispObject {
keymap_parent(keymap, true)
}
/// Check whether MAP is one of MAPS parents.
#[no_mangle]
pub extern "C" fn keymap_memberp(map: LispObject, maps: LispObject) -> bool {
let map = map;
let mut maps = maps;
if map.is_nil() {
return false;
}
while keymapp(maps) &&!map.eq(maps) {
maps = keymap_parent(maps, false);
}
map.eq(maps)
}
/// Modify KEYMAP to set its parent map to PARENT.
/// Return PARENT. PARENT should be nil or another keymap.
#[lisp_fn]
pub fn set_keymap_parent(keymap: LispObject, parent: LispObject) -> LispObject {
// Flush any reverse-map cache
unsafe {
where_is_cache = Qnil;
where_is_cache_keymaps = Qt;
}
let mut parent = parent;
let keymap = get_keymap(keymap, true, true);
if parent.is_not_nil() {
parent = get_keymap(parent, true, false);
// Check for cycles
if keymap_memberp(keymap, parent) {
error!("Cyclic keymap inheritance");
}
}
// Skip past the initial element 'keymap'.
let mut prev = LispCons::from(keymap);
let mut list;
loop {
list = prev.cdr();
// If there is a parent keymap here, replace it.
// If we came to the end, add the parent in PREV.
match list.as_cons() {
None => break,
Some(cons) => {
if keymapp(list) {
break;
} else {
prev = cons;
}
}
}
}
prev.check_impure();
prev.set_cdr(parent);
parent
}
/// Return the prompt-string of a keymap MAP.
/// If non-nil, the prompt is shown in the echo-area
/// when reading a key-sequence to be looked-up in this keymap.
#[lisp_fn]
pub fn keymap_prompt(map: LispObject) -> LispObject {
let map = get_keymap(map, false, false);
for elt in map.iter_cars(LispConsEndChecks::off, LispConsCircularChecks::off) {
let mut tem = elt;
if tem.is_string() {
return tem;
} else if keymapp(tem) {
tem = keymap_prompt(tem);
if tem.is_not_nil() {
return tem;
}
}
}
Qnil
}
/// Same as `map_keymap_internal`, but traverses parent keymaps as well.
/// AUTOLOAD indicates that autoloaded keymaps should be loaded.
#[no_mangle]
pub unsafe extern "C" fn map_keymap(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
autoload: bool,
) {
let mut map = get_keymap(map, true, autoload);
while map.is_cons() {
if let Some((car, cdr)) = map.into() {
if keymapp(car) {
map_keymap(car, fun, args, data, autoload);
map = cdr;
} else {
map = map_keymap_internal(map, fun, args, data);
}
}
if!map.is_cons() {
map = get_keymap(map, false, autoload);
}
}
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
///
/// If KEYMAP has a parent, the parent's bindings are included as well.
/// This works recursively: if the parent has itself a parent, then the
/// grandparent's bindings are also included and so on.
/// usage: (map-keymap FUNCTION KEYMAP)
#[lisp_fn(name = "map-keymap", c_name = "map_keymap", min = "2")]
pub fn map_keymap_lisp(function: LispObject, keymap: LispObject, sort_first: bool) -> LispObject {
if sort_first {
return call!(intern("map-keymap-sorted").into(), function, keymap);
}
unsafe {
map_keymap(
keymap,
Some(map_keymap_call),
function,
ptr::null_mut(),
true,
)
};
Qnil
}
/// Call FUN for every binding in MAP and stop at (and return) the parent.
/// FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA).
#[no_mangle]
pub unsafe extern "C" fn map_keymap_internal(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
) -> LispObject {
let map = map;
let tail = match map.into() {
None => Qnil,
Some((car, cdr)) => {
if car.eq(Qkeymap) {
cdr
} else {
map
}
}
};
let mut parent = tail;
for tail_cons in tail.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
let binding = tail_cons.car();
if binding.eq(Qkeymap) {
break;
} else {
// An embedded parent.
if keymapp(binding) {
break;
}
if let Some((car, cdr)) = binding.into() {
map_keymap_item(fun, args, car, cdr, data);
} else if binding.is_vector() {
if let Some(binding_vec) = binding.as_vectorlike() {
for c in 0..binding_vec.pseudovector_size() {
map_keymap_item(fun, args, c.into(), aref(binding, c), data);
}
}
} else if binding.is_char_table() {
let saved = match fun {
Some(f) => make_save_funcptr_ptr_obj(Some(std::mem::transmute(f)), data, args),
None => make_save_funcptr_ptr_obj(None, data, args),
};
map_char_table(Some(map_keymap_char_table_item), Qnil, binding, saved);
}
}
parent = tail_cons.cdr();
}
parent
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
/// If KEYMAP has a parent, this function returns it without processing it.
#[lisp_fn(name = "map-keymap-internal", c_name = "map_keymap_internal")]
pub fn map_keymap_internal_lisp(function: LispObject, mut keymap: LispObject) -> LispObject {
keymap = get_keymap(keymap, true, true);
unsafe { map_keymap_internal(keymap, Some(map_keymap_call), function, ptr::null_mut()) }
}
/// Return the binding for command KEYS in current local keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn local_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_local_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return current buffer's local keymap, or nil if it has none.
/// Normally the local keymap is set by the major mode with `use-local-map'.
#[lisp_fn]
pub fn current_local_map() -> LispObject {
ThreadState::current_buffer_unchecked().keymap_
}
/// Select KEYMAP as the local keymap.
/// If KEYMAP is nil, that means no local keymap.
#[lisp_fn]
pub fn use_local_map(mut keymap: LispObject) {
if!keymap.is_nil() {
let map = get_keymap(keymap, true, true);
keymap = map;
}
ThreadState::current_buffer_unchecked().keymap_ = keymap;
}
/// Return the binding for command KEYS in current global keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// This function's return values are the same as those of `lookup-key'
/// (which see).
///
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn global_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_global_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return the current global keymap.
#[lisp_fn]
pub fn current_global_map() -> LispObject {
unsafe { _current_global_map }
}
/// Select KEYMAP as the global keymap.
#[lisp_fn]
pub fn use_global_map(keymap: LispObject) {
unsafe { _current_global_map = get_keymap(keymap, true, true) };
}
// Value is number if KEY is too long; nil if valid but has no definition.
// GC is possible in this function.
/// In keymap KEYMAP, look up key sequence KEY. Return the definition.
/// A value of nil means undefined. See doc of `define-key'
/// for kinds of definitions.
///
/// A number as value means KEY is "too long";
/// that is, characters or symbols in it except for the last one
/// fail to be a valid sequence of prefix characters in KEYMAP.
/// The number is how many characters at the front of KEY
/// it takes to reach a non-prefix key.
///
/// Normally, `lookup-key' ignores bindings for t, which act as default
/// bindings, used when nothing else in the keymap applies; this makes it
/// usable as a general function for probing keymaps. However, if the
/// third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will
/// recognize the default bindings, just as `read-key-sequence' does.
#[lisp_fn(min = "2")]
pub fn lookup_key(keymap: LispObject, key: LispObject, accept_default: LispObject) -> LispObject {
let ok = accept_default.is_not_nil();
let mut keymap = get_keymap(keymap, true, true);
let length = key.as_vector_or_string_length() as EmacsInt;
if length == 0 {
return keymap;
}
let mut idx = 0;
loop {
let mut c = aref(key, idx);
idx += 1;
if c.is_cons() && lucid_event_type_list_p(c.into()) {
c = unsafe { Fevent_convert_list(c) };
}
// Turn the 8th bit of string chars into a meta modifier.
if let Some(k) = key.as_string() {
if let Some(x) = c.as_fixnum() {
let x = x as u32;
if x & 0x80!= 0 &&!k.is_multibyte() {
c = ((x | char_bits::CHAR_META) &!0x80).into();
}
}
}
// Allow string since binding for `menu-bar-select-buffer'
// includes the buffer name in the key sequence.
if!(c.is_fixnum() || c.is_symbol() || c.is_cons() || c.is_string()) {
message_with_string!("Key sequence contains invalid event %s", c, true);
}
let cmd = unsafe { access_keymap(keymap, c, ok, false, true) };
if idx == length {
return cmd;
}
keymap = get_keymap(cmd, false, true);
if!keymap.is_cons() {
return idx.into();
}
unsafe {
maybe_quit();
};
}
}
/// Define COMMAND as a prefix command. COMMAND should be a symbol.
/// A new sparse keymap is stored as COMMAND's function definition and its
/// value.
/// This prepares COMMAND for use as a prefix key's binding.
/// If a second optional argument MAPVAR is given, it should be a symbol.
/// The map is then stored as MAPVAR's value instead of as COMMAND's
/// value; but COMMAND is still defined as a function.
/// The third optional argument NAME, if given, supplies a menu name
/// string for the map. This is required to use the keymap as a menu.
/// This function returns COMMAND.
#[lisp_fn(min = "1")]
pub fn define_prefix_command(
command: LispSymbolRef,
mapvar: LispObject,
name: LispObject,
) -> LispSymbolRef {
let map = make_sparse_keymap(name);
fset(command, map);
if mapvar.is_not_nil() {
set(mapvar.into(), map);
} else {
set(command, map);
}
command
}
/// Construct and return a new sparse keymap.
/// Its car is `keymap' and its cdr is an alist of (CHAR. DEFINITION),
/// which binds the character CHAR to DEFINITION, or (SYMBOL. DEFINITION),
/// which binds the function key or mouse event SYMBOL to DEFINITION.
/// Initially the alist is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_sparse_keymap(string: LispObject) -> LispObject {
if string.is_not_nil() {
let s = if unsafe { globals.Vpurify_flag }.is_not_nil() {
unsafe { Fpurecopy(string) }
} else {
string
};
list!(Qkeymap, s)
} else {
list!(Qkeymap)
}
}
#[no_mangle]
pub extern "C" fn describe_vector_princ(elt: LispObject, fun: LispObject) {
indent_to(16, 1.into());
call!(fun, elt);
unsafe { Fterpri(Qnil, Qnil) };
}
/// Insert a description of contents of VECTOR.
/// This is text showing the elements of vector matched against indices.
/// DESCRIBER is the output function used; nil means use `princ'.
#[lisp_fn(min = "1", name = "describe-vector", c_name = "describe_vector")]
pub fn describe_vector_lisp(vector: LispObject, mut describer: LispObject) {
if describer.is_nil() {
describer = intern("princ").into();
}
unsafe { specbind(Qstandard_output, current_buffer()) };
if!(vector.is_vector() || vector.is_char_table()) {
wrong_type!(Qvector_or_char_table_p, vector);
}
let count = c_specpdl_index();
unsafe {
describe_vector(
vector,
Qnil,
describer,
Some(describe_vector_princ),
false,
Qnil,
Qnil,
false,
false,
)
};
unbind_to(count, Qnil);
}
#[no_mangle]
pub extern "C" fn copy_keymap_1(chartable: LispObject, idx: LispObject, elt: LispObject) {
unsafe { Fset_char_table_range(chartable, idx, copy_keymap_item(elt)) };
}
/// Return a copy of the keymap KEYMAP.
///
/// Note that this is almost never needed. If you want a keymap that's like
/// another yet with a few changes, you should use map inheritance rather
/// than copying. I.e. something like:
///
/// (let ((map (make-sparse-keymap)))
/// (set-keymap-parent map <theirmap>)
/// (define-key map...)
///...)
///
/// After performing `copy-keymap', the copy starts out with the same definitions
/// of KEYMAP, but changing either the copy or KEYMAP does not affect the other.
/// Any key definitions that are subkeymaps are recursively copied.
/// However, a key definition which is a symbol whose definition is a keymap
/// is not copied.
#[lisp_fn]
pub fn copy_keymap(keymap: LispObject) -> LispObject {
let keymap = get_keymap(keymap, true, false);
let mut tail = list!(Qkeymap);
let copy = tail;
let (_, mut keymap) = keymap.into(); // Skip the `keymap' symbol.
while let Some((mut elt, kmd)) = keymap.into() {
if elt.eq(Qkeymap) {
break;
}
if elt.is_char_table() {
elt = unsafe { Fcopy_sequence(elt) };
unsafe { map_char_table(Some(copy_keymap_1), Qnil, elt, elt) };
} else if let Some(v) = elt.as_vector() {
elt = unsafe { Fcopy_sequence(elt) };
let mut v2 = elt.as_vector().unwrap();
for (i, obj) in v.iter().enumerate() {
v2.set(i, unsafe { copy_keymap_item(obj) });
}
} else if let Some((front, back)) = elt.into() {
if front.eq(Qkeymap) {
// This is a sub keymap
elt = copy_keymap(elt);
| } | random_line_split |
keymap.rs | we don't want to pursue autoloads.
/// Functions like `Faccessible_keymaps` which scan entire keymap trees
/// shouldn't load every autoloaded keymap. I'm not sure about this,
/// but it seems to me that only `read_key_sequence`, `Flookup_key`, and
/// `Fdefine_key` should cause keymaps to be autoloaded.
///
/// This function can GC when AUTOLOAD is true, because it calls
/// `Fautoload_do_load` which can GC.
#[no_mangle]
pub extern "C" fn get_keymap(
object: LispObject,
error_if_not_keymap: bool,
autoload: bool,
) -> LispObject {
let object = object;
let mut autoload_retry = true;
while autoload_retry {
autoload_retry = false;
if object.is_nil() {
break;
}
if let Some((car, _)) = object.into() {
if car.eq(Qkeymap) {
return object;
}
}
let tem = indirect_function(object);
if let Some((car, _)) = tem.into() {
if car.eq(Qkeymap) {
return tem;
}
// Should we do an autoload? Autoload forms for keymaps have
// Qkeymap as their fifth element.
if (autoload ||!error_if_not_keymap) && car.eq(Qautoload) && object.is_symbol() {
let tail = nth(4, tem);
if tail.eq(Qkeymap) {
if autoload {
autoload_do_load(tem, object, Qnil);
autoload_retry = true;
} else {
return object;
}
}
}
}
}
if error_if_not_keymap {
wrong_type!(Qkeymapp, object);
}
Qnil
}
/// Construct and return a new keymap, of the form (keymap CHARTABLE. ALIST).
/// CHARTABLE is a char-table that holds the bindings for all characters
/// without modifiers. All entries in it are initially nil, meaning
/// "command undefined". ALIST is an assoc-list which holds bindings for
/// function keys, mouse events, and any other things that appear in the
/// input stream. Initially, ALIST is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_keymap(string: LispObject) -> (LispObject, (LispObject, LispObject)) {
let tail: LispObject = if string.is_not_nil() {
list!(string)
} else {
Qnil
};
let char_table = unsafe { Fmake_char_table(Qkeymap, Qnil) };
(Qkeymap, (char_table, tail))
}
/// Return t if OBJECT is a keymap.
///
/// A keymap is a list (keymap. ALIST),
/// or a symbol whose function definition is itself a keymap.
/// ALIST elements look like (CHAR. DEFN) or (SYMBOL. DEFN);
/// a vector of densely packed bindings for small character codes
/// is also allowed as an element.
#[lisp_fn]
pub fn keymapp(object: LispObject) -> bool {
let map = get_keymap(object, false, false);
map.is_not_nil()
}
/// Return the parent map of KEYMAP, or nil if it has none.
/// We assume that KEYMAP is a valid keymap.
#[no_mangle]
pub extern "C" fn keymap_parent(keymap: LispObject, autoload: bool) -> LispObject {
let map = get_keymap(keymap, true, autoload);
let mut current = Qnil;
for elt in map.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
current = elt.cdr();
if keymapp(current) {
return current;
}
}
get_keymap(current, false, autoload)
}
/// Return the parent keymap of KEYMAP.
/// If KEYMAP has no parent, return nil.
#[lisp_fn(name = "keymap-parent", c_name = "keymap_parent")]
pub fn keymap_parent_lisp(keymap: LispObject) -> LispObject {
keymap_parent(keymap, true)
}
/// Check whether MAP is one of MAPS parents.
#[no_mangle]
pub extern "C" fn keymap_memberp(map: LispObject, maps: LispObject) -> bool {
let map = map;
let mut maps = maps;
if map.is_nil() {
return false;
}
while keymapp(maps) &&!map.eq(maps) {
maps = keymap_parent(maps, false);
}
map.eq(maps)
}
/// Modify KEYMAP to set its parent map to PARENT.
/// Return PARENT. PARENT should be nil or another keymap.
#[lisp_fn]
pub fn set_keymap_parent(keymap: LispObject, parent: LispObject) -> LispObject {
// Flush any reverse-map cache
unsafe {
where_is_cache = Qnil;
where_is_cache_keymaps = Qt;
}
let mut parent = parent;
let keymap = get_keymap(keymap, true, true);
if parent.is_not_nil() {
parent = get_keymap(parent, true, false);
// Check for cycles
if keymap_memberp(keymap, parent) {
error!("Cyclic keymap inheritance");
}
}
// Skip past the initial element 'keymap'.
let mut prev = LispCons::from(keymap);
let mut list;
loop {
list = prev.cdr();
// If there is a parent keymap here, replace it.
// If we came to the end, add the parent in PREV.
match list.as_cons() {
None => break,
Some(cons) => {
if keymapp(list) {
break;
} else {
prev = cons;
}
}
}
}
prev.check_impure();
prev.set_cdr(parent);
parent
}
/// Return the prompt-string of a keymap MAP.
/// If non-nil, the prompt is shown in the echo-area
/// when reading a key-sequence to be looked-up in this keymap.
#[lisp_fn]
pub fn keymap_prompt(map: LispObject) -> LispObject {
let map = get_keymap(map, false, false);
for elt in map.iter_cars(LispConsEndChecks::off, LispConsCircularChecks::off) {
let mut tem = elt;
if tem.is_string() {
return tem;
} else if keymapp(tem) {
tem = keymap_prompt(tem);
if tem.is_not_nil() {
return tem;
}
}
}
Qnil
}
/// Same as `map_keymap_internal`, but traverses parent keymaps as well.
/// AUTOLOAD indicates that autoloaded keymaps should be loaded.
#[no_mangle]
pub unsafe extern "C" fn map_keymap(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
autoload: bool,
) {
let mut map = get_keymap(map, true, autoload);
while map.is_cons() {
if let Some((car, cdr)) = map.into() {
if keymapp(car) {
map_keymap(car, fun, args, data, autoload);
map = cdr;
} else {
map = map_keymap_internal(map, fun, args, data);
}
}
if!map.is_cons() {
map = get_keymap(map, false, autoload);
}
}
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
///
/// If KEYMAP has a parent, the parent's bindings are included as well.
/// This works recursively: if the parent has itself a parent, then the
/// grandparent's bindings are also included and so on.
/// usage: (map-keymap FUNCTION KEYMAP)
#[lisp_fn(name = "map-keymap", c_name = "map_keymap", min = "2")]
pub fn map_keymap_lisp(function: LispObject, keymap: LispObject, sort_first: bool) -> LispObject {
if sort_first {
return call!(intern("map-keymap-sorted").into(), function, keymap);
}
unsafe {
map_keymap(
keymap,
Some(map_keymap_call),
function,
ptr::null_mut(),
true,
)
};
Qnil
}
/// Call FUN for every binding in MAP and stop at (and return) the parent.
/// FUN is called with 4 arguments: FUN (KEY, BINDING, ARGS, DATA).
#[no_mangle]
pub unsafe extern "C" fn map_keymap_internal(
map: LispObject,
fun: map_keymap_function_t,
args: LispObject,
data: *mut c_void,
) -> LispObject {
let map = map;
let tail = match map.into() {
None => Qnil,
Some((car, cdr)) => {
if car.eq(Qkeymap) {
cdr
} else {
map
}
}
};
let mut parent = tail;
for tail_cons in tail.iter_tails(LispConsEndChecks::off, LispConsCircularChecks::off) {
let binding = tail_cons.car();
if binding.eq(Qkeymap) {
break;
} else {
// An embedded parent.
if keymapp(binding) {
break;
}
if let Some((car, cdr)) = binding.into() {
map_keymap_item(fun, args, car, cdr, data);
} else if binding.is_vector() {
if let Some(binding_vec) = binding.as_vectorlike() {
for c in 0..binding_vec.pseudovector_size() {
map_keymap_item(fun, args, c.into(), aref(binding, c), data);
}
}
} else if binding.is_char_table() {
let saved = match fun {
Some(f) => make_save_funcptr_ptr_obj(Some(std::mem::transmute(f)), data, args),
None => make_save_funcptr_ptr_obj(None, data, args),
};
map_char_table(Some(map_keymap_char_table_item), Qnil, binding, saved);
}
}
parent = tail_cons.cdr();
}
parent
}
/// Call FUNCTION once for each event binding in KEYMAP.
/// FUNCTION is called with two arguments: the event that is bound, and
/// the definition it is bound to. The event may be a character range.
/// If KEYMAP has a parent, this function returns it without processing it.
#[lisp_fn(name = "map-keymap-internal", c_name = "map_keymap_internal")]
pub fn map_keymap_internal_lisp(function: LispObject, mut keymap: LispObject) -> LispObject {
keymap = get_keymap(keymap, true, true);
unsafe { map_keymap_internal(keymap, Some(map_keymap_call), function, ptr::null_mut()) }
}
/// Return the binding for command KEYS in current local keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn local_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_local_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return current buffer's local keymap, or nil if it has none.
/// Normally the local keymap is set by the major mode with `use-local-map'.
#[lisp_fn]
pub fn current_local_map() -> LispObject {
ThreadState::current_buffer_unchecked().keymap_
}
/// Select KEYMAP as the local keymap.
/// If KEYMAP is nil, that means no local keymap.
#[lisp_fn]
pub fn use_local_map(mut keymap: LispObject) {
if!keymap.is_nil() {
let map = get_keymap(keymap, true, true);
keymap = map;
}
ThreadState::current_buffer_unchecked().keymap_ = keymap;
}
/// Return the binding for command KEYS in current global keymap only.
/// KEYS is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
/// This function's return values are the same as those of `lookup-key'
/// (which see).
///
/// If optional argument ACCEPT-DEFAULT is non-nil, recognize default
/// bindings; see the description of `lookup-key' for more details about this.
#[lisp_fn(min = "1")]
pub fn global_key_binding(keys: LispObject, accept_default: LispObject) -> LispObject {
let map = current_global_map();
if map.is_nil() {
Qnil
} else {
lookup_key(map, keys, accept_default)
}
}
/// Return the current global keymap.
#[lisp_fn]
pub fn current_global_map() -> LispObject {
unsafe { _current_global_map }
}
/// Select KEYMAP as the global keymap.
#[lisp_fn]
pub fn use_global_map(keymap: LispObject) {
unsafe { _current_global_map = get_keymap(keymap, true, true) };
}
// Value is number if KEY is too long; nil if valid but has no definition.
// GC is possible in this function.
/// In keymap KEYMAP, look up key sequence KEY. Return the definition.
/// A value of nil means undefined. See doc of `define-key'
/// for kinds of definitions.
///
/// A number as value means KEY is "too long";
/// that is, characters or symbols in it except for the last one
/// fail to be a valid sequence of prefix characters in KEYMAP.
/// The number is how many characters at the front of KEY
/// it takes to reach a non-prefix key.
///
/// Normally, `lookup-key' ignores bindings for t, which act as default
/// bindings, used when nothing else in the keymap applies; this makes it
/// usable as a general function for probing keymaps. However, if the
/// third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will
/// recognize the default bindings, just as `read-key-sequence' does.
#[lisp_fn(min = "2")]
pub fn lookup_key(keymap: LispObject, key: LispObject, accept_default: LispObject) -> LispObject {
let ok = accept_default.is_not_nil();
let mut keymap = get_keymap(keymap, true, true);
let length = key.as_vector_or_string_length() as EmacsInt;
if length == 0 {
return keymap;
}
let mut idx = 0;
loop {
let mut c = aref(key, idx);
idx += 1;
if c.is_cons() && lucid_event_type_list_p(c.into()) {
c = unsafe { Fevent_convert_list(c) };
}
// Turn the 8th bit of string chars into a meta modifier.
if let Some(k) = key.as_string() {
if let Some(x) = c.as_fixnum() {
let x = x as u32;
if x & 0x80!= 0 &&!k.is_multibyte() {
c = ((x | char_bits::CHAR_META) &!0x80).into();
}
}
}
// Allow string since binding for `menu-bar-select-buffer'
// includes the buffer name in the key sequence.
if!(c.is_fixnum() || c.is_symbol() || c.is_cons() || c.is_string()) {
message_with_string!("Key sequence contains invalid event %s", c, true);
}
let cmd = unsafe { access_keymap(keymap, c, ok, false, true) };
if idx == length {
return cmd;
}
keymap = get_keymap(cmd, false, true);
if!keymap.is_cons() {
return idx.into();
}
unsafe {
maybe_quit();
};
}
}
/// Define COMMAND as a prefix command. COMMAND should be a symbol.
/// A new sparse keymap is stored as COMMAND's function definition and its
/// value.
/// This prepares COMMAND for use as a prefix key's binding.
/// If a second optional argument MAPVAR is given, it should be a symbol.
/// The map is then stored as MAPVAR's value instead of as COMMAND's
/// value; but COMMAND is still defined as a function.
/// The third optional argument NAME, if given, supplies a menu name
/// string for the map. This is required to use the keymap as a menu.
/// This function returns COMMAND.
#[lisp_fn(min = "1")]
pub fn define_prefix_command(
command: LispSymbolRef,
mapvar: LispObject,
name: LispObject,
) -> LispSymbolRef {
let map = make_sparse_keymap(name);
fset(command, map);
if mapvar.is_not_nil() {
set(mapvar.into(), map);
} else {
set(command, map);
}
command
}
/// Construct and return a new sparse keymap.
/// Its car is `keymap' and its cdr is an alist of (CHAR. DEFINITION),
/// which binds the character CHAR to DEFINITION, or (SYMBOL. DEFINITION),
/// which binds the function key or mouse event SYMBOL to DEFINITION.
/// Initially the alist is nil.
///
/// The optional arg STRING supplies a menu name for the keymap
/// in case you use it as a menu with `x-popup-menu'.
#[lisp_fn(min = "0")]
pub fn make_sparse_keymap(string: LispObject) -> LispObject {
if string.is_not_nil() {
let s = if unsafe { globals.Vpurify_flag }.is_not_nil() {
unsafe { Fpurecopy(string) }
} else {
string
};
list!(Qkeymap, s)
} else {
list!(Qkeymap)
}
}
#[no_mangle]
pub extern "C" fn describe_vector_princ(elt: LispObject, fun: LispObject) {
indent_to(16, 1.into());
call!(fun, elt);
unsafe { Fterpri(Qnil, Qnil) };
}
/// Insert a description of contents of VECTOR.
/// This is text showing the elements of vector matched against indices.
/// DESCRIBER is the output function used; nil means use `princ'.
#[lisp_fn(min = "1", name = "describe-vector", c_name = "describe_vector")]
pub fn describe_vector_lisp(vector: LispObject, mut describer: LispObject) {
if describer.is_nil() {
describer = intern("princ").into();
}
unsafe { specbind(Qstandard_output, current_buffer()) };
if!(vector.is_vector() || vector.is_char_table()) {
wrong_type!(Qvector_or_char_table_p, vector);
}
let count = c_specpdl_index();
unsafe {
describe_vector(
vector,
Qnil,
describer,
Some(describe_vector_princ),
false,
Qnil,
Qnil,
false,
false,
)
};
unbind_to(count, Qnil);
}
#[no_mangle]
pub extern "C" fn copy_keymap_1(chartable: LispObject, idx: LispObject, elt: LispObject) {
unsafe { Fset_char_table_range(chartable, idx, copy_keymap_item(elt)) };
}
/// Return a copy of the keymap KEYMAP.
///
/// Note that this is almost never needed. If you want a keymap that's like
/// another yet with a few changes, you should use map inheritance rather
/// than copying. I.e. something like:
///
/// (let ((map (make-sparse-keymap)))
/// (set-keymap-parent map <theirmap>)
/// (define-key map...)
///...)
///
/// After performing `copy-keymap', the copy starts out with the same definitions
/// of KEYMAP, but changing either the copy or KEYMAP does not affect the other.
/// Any key definitions that are subkeymaps are recursively copied.
/// However, a key definition which is a symbol whose definition is a keymap
/// is not copied.
#[lisp_fn]
pub fn copy_keymap(keymap: LispObject) -> LispObject {
let keymap = get_keymap(keymap, true, false);
let mut tail = list!(Qkeymap);
let copy = tail;
let (_, mut keymap) = keymap.into(); // Skip the `keymap' symbol.
while let Some((mut elt, kmd)) = keymap.into() {
if elt.eq(Qkeymap) {
break;
}
if elt.is_char_table() {
elt = unsafe { Fcopy_sequence(elt) };
unsafe { map_char_table(Some(copy_keymap_1), Qnil, elt, elt) };
} else if let Some(v) = elt.as_vector() {
elt = unsafe { Fcopy_sequence(elt) };
let mut v2 = elt.as_vector().unwrap();
for (i, obj) in v.iter().enumerate() {
v2.set(i, unsafe { copy_keymap_item(obj) });
}
} else if let Some((front, back)) = elt.into() {
if front.eq(Qkeymap) {
// This is a sub keymap
elt = copy_keymap(elt);
} else {
elt = (front, unsafe { copy_keymap_item(back) }).into();
}
}
setcdr(tail.into(), list!(elt));
tail = LispCons::from(tail).cdr();
keymap = kmd;
}
setcdr(tail.into(), keymap);
copy
}
// GC is possible in this funtion if it autoloads a keymap.
/// Return the binding for command KEY in current keymaps.
/// KEY is a string or vector, a sequence of keystrokes.
/// The binding is probably a symbol with a function definition.
///
/// Normally, `key-binding' ignores bindings for t, which act as default
/// bindings, used when nothing else in the keymap applies; this makes it
/// usable as a general function for probing keymaps. However, if the
/// optional second argument ACCEPT-DEFAULT is non-nil, `key-binding' does
/// recognize the default bindings, just as `read-key-sequence' does.
///
/// Like the normal command loop, `key-binding' will remap the command
/// resulting from looking up KEY by looking up the command in the
/// current keymaps. However, if the optional third argument NO-REMAP
/// is non-nil, `key-binding' returns the unmapped command.
///
/// If KEY is a key sequence initiated with the mouse, the used keymaps
/// will depend on the clicked mouse position with regard to the buffer
/// and possible local keymaps on strings.
///
/// If the optional argument POSITION is non-nil, it specifies a mouse
/// position as returned by `event-start' and `event-end', and the lookup
/// occurs in the keymaps associated with it instead of KEY. It can also
/// be a number or marker, in which case the keymap properties at the
/// specified buffer position instead of point are used.
#[lisp_fn(min = "1")]
pub fn | key_binding | identifier_name |
|
mod.rs | use std::cmp::Ordering;
| ///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::orderings::ordering_from_str;
/// use std::cmp::Ordering;
///
/// assert_eq!(ordering_from_str("Equal"), Some(Ordering::Equal));
/// assert_eq!(ordering_from_str("Less"), Some(Ordering::Less));
/// assert_eq!(ordering_from_str("Greater"), Some(Ordering::Greater));
/// assert_eq!(ordering_from_str("abc"), None);
/// ```
#[inline]
pub fn ordering_from_str(src: &str) -> Option<Ordering> {
match src {
"Equal" => Some(Ordering::Equal),
"Less" => Some(Ordering::Less),
"Greater" => Some(Ordering::Greater),
_ => None,
}
}
/// This module contains iterators that generate `Ordering`s without repetition.
pub mod exhaustive;
/// This module contains iterators that generate `Ordering`s randomly.
pub mod random; | pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned. | random_line_split |
mod.rs | use std::cmp::Ordering;
pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::orderings::ordering_from_str;
/// use std::cmp::Ordering;
///
/// assert_eq!(ordering_from_str("Equal"), Some(Ordering::Equal));
/// assert_eq!(ordering_from_str("Less"), Some(Ordering::Less));
/// assert_eq!(ordering_from_str("Greater"), Some(Ordering::Greater));
/// assert_eq!(ordering_from_str("abc"), None);
/// ```
#[inline]
pub fn | (src: &str) -> Option<Ordering> {
match src {
"Equal" => Some(Ordering::Equal),
"Less" => Some(Ordering::Less),
"Greater" => Some(Ordering::Greater),
_ => None,
}
}
/// This module contains iterators that generate `Ordering`s without repetition.
pub mod exhaustive;
/// This module contains iterators that generate `Ordering`s randomly.
pub mod random;
| ordering_from_str | identifier_name |
mod.rs | use std::cmp::Ordering;
pub(crate) const ORDERINGS: [Ordering; 3] = [Ordering::Equal, Ordering::Less, Ordering::Greater];
/// Converts a `&str` to a `Ordering`.
///
/// If the `&str` does not represent a valid `Ordering`, `None` is returned.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::orderings::ordering_from_str;
/// use std::cmp::Ordering;
///
/// assert_eq!(ordering_from_str("Equal"), Some(Ordering::Equal));
/// assert_eq!(ordering_from_str("Less"), Some(Ordering::Less));
/// assert_eq!(ordering_from_str("Greater"), Some(Ordering::Greater));
/// assert_eq!(ordering_from_str("abc"), None);
/// ```
#[inline]
pub fn ordering_from_str(src: &str) -> Option<Ordering> |
/// This module contains iterators that generate `Ordering`s without repetition.
pub mod exhaustive;
/// This module contains iterators that generate `Ordering`s randomly.
pub mod random;
| {
match src {
"Equal" => Some(Ordering::Equal),
"Less" => Some(Ordering::Less),
"Greater" => Some(Ordering::Greater),
_ => None,
}
} | identifier_body |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
Stripe(RequestError),
/// A networking error communicating with the Stripe server.
Http(hyper::Error),
/// An error reading the response body.
Io(io::Error),
/// An error converting between wire format and Rust types.
Conversion(Box<error::Error + Send>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
Error::Stripe(ref err) => write!(f, ": {}", err),
Error::Http(ref err) => write!(f, ": {}", err),
Error::Io(ref err) => write!(f, ": {}", err),
Error::Conversion(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Stripe(_) => "error reported by stripe",
Error::Http(_) => "error communicating with stripe",
Error::Io(_) => "error reading response from stripe",
Error::Conversion(_) => "error converting between wire format and Rust types",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Stripe(ref err) => Some(err),
Error::Http(ref err) => Some(err),
Error::Io(ref err) => Some(err),
Error::Conversion(ref err) => Some(&**err),
}
}
}
impl From<RequestError> for Error {
fn from(err: RequestError) -> Error {
Error::Stripe(err)
}
}
impl From<hyper::Error> for Error {
fn from(err: hyper::Error) -> Error {
Error::Http(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<qs::Error> for Error {
fn from(err: qs::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
impl From<json::Error> for Error {
fn from(err: json::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
/// The list of possible values for a RequestError's type.
#[derive(Debug, PartialEq, Deserialize)]
pub enum ErrorType {
#[serde(skip_deserializing)]
Unknown,
#[serde(rename = "api_error")]
Api,
#[serde(rename = "api_connection_error")]
Connection,
#[serde(rename = "authentication_error")]
Authentication,
#[serde(rename = "card_error")]
Card,
#[serde(rename = "invalid_request_error")]
InvalidRequest,
#[serde(rename = "rate_limit_error")]
RateLimit,
#[serde(rename = "validation_error")]
Validation,
}
impl Default for ErrorType {
fn default() -> Self {
ErrorType::Unknown
}
}
impl fmt::Display for ErrorType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}Error", self)))
}
}
/// The list of possible values for a RequestError's code.
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
AccountAlreadyExists,
AccountCountryInvalidAddress,
AccountInvalid,
AccountNumberInvalid,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
BalanceInsufficient,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BitcoinUpgradeRequired,
CardDeclined,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExpiredForCapture,
CountryUnsupported,
CouponExpired,
CustomerMaxSubscriptions,
EmailInvalid,
ExpiredCard,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsUnsupported,
InvalidCardType,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceUpcomingNone,
LivemodeMismatch,
Missing,
OrderCreationFailed,
OrderRequiredSettings,
OrderStatusInvalid,
OrderUpstreamTimeout,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParameterMissing,
ParameterUnknown,
PaymentMethodUnactivated,
PayoutsNotAllowed,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ResourceAlreadyExists,
ResourceMissing,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
TaxIdInvalid,
TaxesCalculationFailed,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenAlreadyUsed,
TokenInUse,
TransfersNotAllowed,
UpstreamOrderCreationFailed,
UrlInvalid,
#[doc(hidden)] __NonExhaustive,
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}", self)))
}
}
/// An error reported by stripe in a request's response.
///
/// For more details see https://stripe.com/docs/api#errors.
#[derive(Debug, Default, Deserialize)]
pub struct RequestError {
/// The HTTP status in the response.
#[serde(skip_deserializing)]
pub http_status: u16,
/// The type of error returned.
#[serde(rename = "type")]
pub error_type: ErrorType,
/// A human-readable message providing more details about the error.
/// For card errors, these messages can be shown to end users.
#[serde(default)]
pub message: Option<String>,
/// For card errors, a value describing the kind of card error that occured.
pub code: Option<ErrorCode>,
/// For card errors resulting from a bank decline, a string indicating the
/// bank's reason for the decline if they provide one.
pub decline_code: Option<String>,
/// The ID of the failed charge, if applicable.
pub charge: Option<String>,
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl error::Error for RequestError {
fn description(&self) -> &str {
self.message.as_ref().map(|s| s.as_str()).unwrap_or(
"request error",
)
}
}
#[doc(hidden)]
#[derive(Deserialize)]
pub struct ErrorObject {
pub error: RequestError,
}
/// An error encountered when communicating with the Stripe API webhooks.
#[derive(Debug)]
pub enum WebhookError {
BadHeader(ParseIntError),
BadSignature,
BadTimestamp(i64),
BadParse(json::Error),
}
impl fmt::Display for WebhookError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
WebhookError::BadHeader(ref err) => write!(f, ": {}", err),
WebhookError::BadSignature => write!(f, "Signatures do not match"),
WebhookError::BadTimestamp(ref err) => write!(f, ": {}", err),
WebhookError::BadParse(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for WebhookError {
fn description(&self) -> &str {
match *self {
WebhookError::BadHeader(_) => "error parsing timestamp",
WebhookError::BadSignature => "error comparing signatures",
WebhookError::BadTimestamp(_) => "error comparing timestamps - over tolerance",
WebhookError::BadParse(_) => "error parsing event object",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
WebhookError::BadHeader(ref err) => Some(err),
WebhookError::BadSignature => None,
WebhookError::BadTimestamp(_) => None,
WebhookError::BadParse(ref err) => Some(err),
}
}
}
| {
write!(f, "{}({})", self.error_type, self.http_status)?;
if let Some(ref message) = self.message {
write!(f, ": {}", message)?;
}
Ok(())
} | identifier_body |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
Stripe(RequestError),
/// A networking error communicating with the Stripe server.
Http(hyper::Error),
/// An error reading the response body.
Io(io::Error),
/// An error converting between wire format and Rust types.
Conversion(Box<error::Error + Send>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
Error::Stripe(ref err) => write!(f, ": {}", err),
Error::Http(ref err) => write!(f, ": {}", err),
Error::Io(ref err) => write!(f, ": {}", err),
Error::Conversion(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Stripe(_) => "error reported by stripe",
Error::Http(_) => "error communicating with stripe",
Error::Io(_) => "error reading response from stripe",
Error::Conversion(_) => "error converting between wire format and Rust types",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Stripe(ref err) => Some(err),
Error::Http(ref err) => Some(err),
Error::Io(ref err) => Some(err),
Error::Conversion(ref err) => Some(&**err),
}
}
}
impl From<RequestError> for Error {
fn from(err: RequestError) -> Error {
Error::Stripe(err)
}
}
impl From<hyper::Error> for Error {
fn from(err: hyper::Error) -> Error {
Error::Http(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<qs::Error> for Error {
fn from(err: qs::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
impl From<json::Error> for Error {
fn from(err: json::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
/// The list of possible values for a RequestError's type.
#[derive(Debug, PartialEq, Deserialize)]
pub enum ErrorType {
#[serde(skip_deserializing)]
Unknown,
#[serde(rename = "api_error")]
Api,
#[serde(rename = "api_connection_error")]
Connection,
#[serde(rename = "authentication_error")]
Authentication,
#[serde(rename = "card_error")]
Card,
#[serde(rename = "invalid_request_error")]
InvalidRequest,
#[serde(rename = "rate_limit_error")]
RateLimit,
#[serde(rename = "validation_error")]
Validation,
}
impl Default for ErrorType {
fn default() -> Self {
ErrorType::Unknown
}
}
impl fmt::Display for ErrorType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}Error", self)))
}
}
/// The list of possible values for a RequestError's code.
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
AccountAlreadyExists,
AccountCountryInvalidAddress,
AccountInvalid,
AccountNumberInvalid,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
BalanceInsufficient,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BitcoinUpgradeRequired,
CardDeclined,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExpiredForCapture,
CountryUnsupported,
CouponExpired,
CustomerMaxSubscriptions,
EmailInvalid,
ExpiredCard,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsUnsupported,
InvalidCardType,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceUpcomingNone,
LivemodeMismatch,
Missing,
OrderCreationFailed,
OrderRequiredSettings,
OrderStatusInvalid,
OrderUpstreamTimeout,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParameterMissing,
ParameterUnknown,
PaymentMethodUnactivated,
PayoutsNotAllowed,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ResourceAlreadyExists,
ResourceMissing,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
TaxIdInvalid,
TaxesCalculationFailed,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenAlreadyUsed,
TokenInUse,
TransfersNotAllowed,
UpstreamOrderCreationFailed,
UrlInvalid,
#[doc(hidden)] __NonExhaustive,
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}", self)))
}
}
/// An error reported by stripe in a request's response.
///
/// For more details see https://stripe.com/docs/api#errors.
#[derive(Debug, Default, Deserialize)]
pub struct RequestError {
/// The HTTP status in the response. |
/// The type of error returned.
#[serde(rename = "type")]
pub error_type: ErrorType,
/// A human-readable message providing more details about the error.
/// For card errors, these messages can be shown to end users.
#[serde(default)]
pub message: Option<String>,
/// For card errors, a value describing the kind of card error that occured.
pub code: Option<ErrorCode>,
/// For card errors resulting from a bank decline, a string indicating the
/// bank's reason for the decline if they provide one.
pub decline_code: Option<String>,
/// The ID of the failed charge, if applicable.
pub charge: Option<String>,
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self.error_type, self.http_status)?;
if let Some(ref message) = self.message {
write!(f, ": {}", message)?;
}
Ok(())
}
}
impl error::Error for RequestError {
fn description(&self) -> &str {
self.message.as_ref().map(|s| s.as_str()).unwrap_or(
"request error",
)
}
}
#[doc(hidden)]
#[derive(Deserialize)]
pub struct ErrorObject {
pub error: RequestError,
}
/// An error encountered when communicating with the Stripe API webhooks.
#[derive(Debug)]
pub enum WebhookError {
BadHeader(ParseIntError),
BadSignature,
BadTimestamp(i64),
BadParse(json::Error),
}
impl fmt::Display for WebhookError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
WebhookError::BadHeader(ref err) => write!(f, ": {}", err),
WebhookError::BadSignature => write!(f, "Signatures do not match"),
WebhookError::BadTimestamp(ref err) => write!(f, ": {}", err),
WebhookError::BadParse(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for WebhookError {
fn description(&self) -> &str {
match *self {
WebhookError::BadHeader(_) => "error parsing timestamp",
WebhookError::BadSignature => "error comparing signatures",
WebhookError::BadTimestamp(_) => "error comparing timestamps - over tolerance",
WebhookError::BadParse(_) => "error parsing event object",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
WebhookError::BadHeader(ref err) => Some(err),
WebhookError::BadSignature => None,
WebhookError::BadTimestamp(_) => None,
WebhookError::BadParse(ref err) => Some(err),
}
}
} | #[serde(skip_deserializing)]
pub http_status: u16, | random_line_split |
error.rs | extern crate hyper;
extern crate serde_json as json;
extern crate serde_qs as qs;
use params::to_snakecase;
use std::error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
/// An error encountered when communicating with the Stripe API.
#[derive(Debug)]
pub enum Error {
/// An error reported by Stripe.
Stripe(RequestError),
/// A networking error communicating with the Stripe server.
Http(hyper::Error),
/// An error reading the response body.
Io(io::Error),
/// An error converting between wire format and Rust types.
Conversion(Box<error::Error + Send>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
Error::Stripe(ref err) => write!(f, ": {}", err),
Error::Http(ref err) => write!(f, ": {}", err),
Error::Io(ref err) => write!(f, ": {}", err),
Error::Conversion(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Stripe(_) => "error reported by stripe",
Error::Http(_) => "error communicating with stripe",
Error::Io(_) => "error reading response from stripe",
Error::Conversion(_) => "error converting between wire format and Rust types",
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Stripe(ref err) => Some(err),
Error::Http(ref err) => Some(err),
Error::Io(ref err) => Some(err),
Error::Conversion(ref err) => Some(&**err),
}
}
}
impl From<RequestError> for Error {
fn from(err: RequestError) -> Error {
Error::Stripe(err)
}
}
impl From<hyper::Error> for Error {
fn from(err: hyper::Error) -> Error {
Error::Http(err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<qs::Error> for Error {
fn from(err: qs::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
impl From<json::Error> for Error {
fn from(err: json::Error) -> Error {
Error::Conversion(Box::new(err))
}
}
/// The list of possible values for a RequestError's type.
#[derive(Debug, PartialEq, Deserialize)]
pub enum ErrorType {
#[serde(skip_deserializing)]
Unknown,
#[serde(rename = "api_error")]
Api,
#[serde(rename = "api_connection_error")]
Connection,
#[serde(rename = "authentication_error")]
Authentication,
#[serde(rename = "card_error")]
Card,
#[serde(rename = "invalid_request_error")]
InvalidRequest,
#[serde(rename = "rate_limit_error")]
RateLimit,
#[serde(rename = "validation_error")]
Validation,
}
impl Default for ErrorType {
fn default() -> Self {
ErrorType::Unknown
}
}
impl fmt::Display for ErrorType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}Error", self)))
}
}
/// The list of possible values for a RequestError's code.
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
AccountAlreadyExists,
AccountCountryInvalidAddress,
AccountInvalid,
AccountNumberInvalid,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
BalanceInsufficient,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BitcoinUpgradeRequired,
CardDeclined,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExpiredForCapture,
CountryUnsupported,
CouponExpired,
CustomerMaxSubscriptions,
EmailInvalid,
ExpiredCard,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsUnsupported,
InvalidCardType,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceUpcomingNone,
LivemodeMismatch,
Missing,
OrderCreationFailed,
OrderRequiredSettings,
OrderStatusInvalid,
OrderUpstreamTimeout,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParameterMissing,
ParameterUnknown,
PaymentMethodUnactivated,
PayoutsNotAllowed,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ResourceAlreadyExists,
ResourceMissing,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
TaxIdInvalid,
TaxesCalculationFailed,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenAlreadyUsed,
TokenInUse,
TransfersNotAllowed,
UpstreamOrderCreationFailed,
UrlInvalid,
#[doc(hidden)] __NonExhaustive,
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", to_snakecase(&format!("{:?}", self)))
}
}
/// An error reported by stripe in a request's response.
///
/// For more details see https://stripe.com/docs/api#errors.
#[derive(Debug, Default, Deserialize)]
pub struct RequestError {
/// The HTTP status in the response.
#[serde(skip_deserializing)]
pub http_status: u16,
/// The type of error returned.
#[serde(rename = "type")]
pub error_type: ErrorType,
/// A human-readable message providing more details about the error.
/// For card errors, these messages can be shown to end users.
#[serde(default)]
pub message: Option<String>,
/// For card errors, a value describing the kind of card error that occured.
pub code: Option<ErrorCode>,
/// For card errors resulting from a bank decline, a string indicating the
/// bank's reason for the decline if they provide one.
pub decline_code: Option<String>,
/// The ID of the failed charge, if applicable.
pub charge: Option<String>,
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self.error_type, self.http_status)?;
if let Some(ref message) = self.message {
write!(f, ": {}", message)?;
}
Ok(())
}
}
impl error::Error for RequestError {
fn description(&self) -> &str {
self.message.as_ref().map(|s| s.as_str()).unwrap_or(
"request error",
)
}
}
#[doc(hidden)]
#[derive(Deserialize)]
pub struct ErrorObject {
pub error: RequestError,
}
/// An error encountered when communicating with the Stripe API webhooks.
#[derive(Debug)]
pub enum WebhookError {
BadHeader(ParseIntError),
BadSignature,
BadTimestamp(i64),
BadParse(json::Error),
}
impl fmt::Display for WebhookError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))?;
match *self {
WebhookError::BadHeader(ref err) => write!(f, ": {}", err),
WebhookError::BadSignature => write!(f, "Signatures do not match"),
WebhookError::BadTimestamp(ref err) => write!(f, ": {}", err),
WebhookError::BadParse(ref err) => write!(f, ": {}", err),
}
}
}
impl error::Error for WebhookError {
fn description(&self) -> &str {
match *self {
WebhookError::BadHeader(_) => "error parsing timestamp",
WebhookError::BadSignature => "error comparing signatures",
WebhookError::BadTimestamp(_) => "error comparing timestamps - over tolerance",
WebhookError::BadParse(_) => "error parsing event object",
}
}
fn | (&self) -> Option<&error::Error> {
match *self {
WebhookError::BadHeader(ref err) => Some(err),
WebhookError::BadSignature => None,
WebhookError::BadTimestamp(_) => None,
WebhookError::BadParse(ref err) => Some(err),
}
}
}
| cause | identifier_name |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub fn list_dir(path: &Path) -> Vec<String> |
pub fn contents(path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut contents))
.expect("Error reading file");
bytes::Bytes::from(contents)
}
pub fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.expect("Getting file metadata")
.permissions()
.mode()
& 0o100
== 0o100
}
| {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err))
.map(|entry| {
entry
.expect("Error reading entry")
.file_name()
.to_string_lossy()
.to_string()
})
.collect();
v.sort();
v
} | identifier_body |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub fn list_dir(path: &Path) -> Vec<String> {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err))
.map(|entry| {
entry
.expect("Error reading entry")
.file_name()
.to_string_lossy()
.to_string()
})
.collect();
v.sort();
v
}
pub fn | (path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut contents))
.expect("Error reading file");
bytes::Bytes::from(contents)
}
pub fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.expect("Getting file metadata")
.permissions()
.mode()
& 0o100
== 0o100
}
| contents | identifier_name |
file.rs | use bytes;
use std;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
| .map(|entry| {
entry
.expect("Error reading entry")
.file_name()
.to_string_lossy()
.to_string()
})
.collect();
v.sort();
v
}
pub fn contents(path: &Path) -> bytes::Bytes {
let mut contents = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut contents))
.expect("Error reading file");
bytes::Bytes::from(contents)
}
pub fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.expect("Getting file metadata")
.permissions()
.mode()
& 0o100
== 0o100
} | pub fn list_dir(path: &Path) -> Vec<String> {
let mut v: Vec<_> = std::fs::read_dir(path)
.unwrap_or_else(|err| panic!("Listing dir {:?}: {:?}", path, err)) | random_line_split |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::core::*;
use crate::helper::*;
use flate2::write::{ZlibDecoder, ZlibEncoder};
use flate2::Compression;
use serde::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::mem;
#[derive(Default)]
pub struct Save {}
impl Save {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Save {
fn run(&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let data = match serde_cbor::to_vec(&core) {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to serialize project", &e.to_string()),
};
let mut file = match File::create(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressor = ZlibEncoder::new(Vec::new(), Compression::default());
compressor.write_all(&data).unwrap();
let compressed_data = compressor.finish().unwrap();
if let Err(e) = file.write_all(&compressed_data) {
return error_msg(core, "Failed to save project", &e.to_string());
}
}
fn help(&self, core: &mut Core) {
help(core, &"save", &"", vec![("[file_path]", "Save project into given path.")]);
}
}
#[derive(Default)]
pub struct Load {}
impl Load {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Load {
fn run(&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let mut file = match File::open(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressed_data: Vec<u8> = Vec::new();
if let Err(e) = file.read_to_end(&mut compressed_data) {
return error_msg(core, "Failed to load project", &e.to_string());
}
let mut data = Vec::new();
let mut decompressor = ZlibDecoder::new(data);
if let Err(e) = decompressor.write_all(&compressed_data) {
return error_msg(core, "Failed to decompress project", &e.to_string());
}
data = match decompressor.finish() {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to decompress project", &e.to_string()),
};
let mut deserializer = serde_cbor::Deserializer::from_slice(&data);
let mut core2: Core = match Core::deserialize(&mut deserializer) {
Ok(core) => core,
Err(e) => return error_msg(core, "Failed to load project", &e.to_string()),
};
mem::swap(&mut core.stdout, &mut core2.stdout);
mem::swap(&mut core.stderr, &mut core2.stderr);
mem::swap(&mut core.env, &mut core2.env);
core2.set_commands(core.commands());
*core = core2;
}
fn help(&self, core: &mut Core) {
help(core, &"load", &"", vec![("[file_path]", "load project from given path.")]);
}
}
#[cfg(test)]
mod test_project {
use super::*;
use crate::writer::*;
use rair_io::*;
use std::fs;
#[test]
fn test_project_help() {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let load = Load::new();
let save = Save::new();
load.help(&mut core);
save.help(&mut core);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Command: [load]\n\n\
Usage:\n\
load [file_path]\tload project from given path.\n\
Command: [save]\n\n\
Usage:\n\
save [file_path]\tSave project into given path.\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
}
#[test]
fn test_project() | 0xfff31000 0x31000 0x337\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
fs::remove_file("rair_project").unwrap();
}
}
| {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let mut load = Load::new();
let mut save = Save::new();
core.io.open("malloc://0x500", IoMode::READ | IoMode::WRITE).unwrap();
core.io.open_at("malloc://0x1337", IoMode::READ | IoMode::WRITE, 0x31000).unwrap();
core.io.map(0x31000, 0xfff31000, 0x337).unwrap();
save.run(&mut core, &["rair_project".to_string()]);
core.io.close_all();
load.run(&mut core, &["rair_project".to_string()]);
core.run("files", &[]);
core.run("maps", &[]);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Handle\tStart address\tsize\t\tPermissions\tURI\n\
0\t0x00000000\t0x00000500\tWRITE | READ\tmalloc://0x500\n\
1\t0x00031000\t0x00001337\tWRITE | READ\tmalloc://0x1337\n\
Virtual Address Physical Address Size\n\ | identifier_body |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::core::*;
use crate::helper::*;
use flate2::write::{ZlibDecoder, ZlibEncoder};
use flate2::Compression;
use serde::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::mem;
#[derive(Default)]
pub struct Save {}
impl Save {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Save {
fn run(&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let data = match serde_cbor::to_vec(&core) {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to serialize project", &e.to_string()),
};
let mut file = match File::create(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressor = ZlibEncoder::new(Vec::new(), Compression::default());
compressor.write_all(&data).unwrap();
let compressed_data = compressor.finish().unwrap();
if let Err(e) = file.write_all(&compressed_data) {
return error_msg(core, "Failed to save project", &e.to_string());
}
}
fn help(&self, core: &mut Core) {
help(core, &"save", &"", vec![("[file_path]", "Save project into given path.")]);
}
}
#[derive(Default)]
pub struct Load {}
impl Load {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Load {
fn | (&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let mut file = match File::open(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressed_data: Vec<u8> = Vec::new();
if let Err(e) = file.read_to_end(&mut compressed_data) {
return error_msg(core, "Failed to load project", &e.to_string());
}
let mut data = Vec::new();
let mut decompressor = ZlibDecoder::new(data);
if let Err(e) = decompressor.write_all(&compressed_data) {
return error_msg(core, "Failed to decompress project", &e.to_string());
}
data = match decompressor.finish() {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to decompress project", &e.to_string()),
};
let mut deserializer = serde_cbor::Deserializer::from_slice(&data);
let mut core2: Core = match Core::deserialize(&mut deserializer) {
Ok(core) => core,
Err(e) => return error_msg(core, "Failed to load project", &e.to_string()),
};
mem::swap(&mut core.stdout, &mut core2.stdout);
mem::swap(&mut core.stderr, &mut core2.stderr);
mem::swap(&mut core.env, &mut core2.env);
core2.set_commands(core.commands());
*core = core2;
}
fn help(&self, core: &mut Core) {
help(core, &"load", &"", vec![("[file_path]", "load project from given path.")]);
}
}
#[cfg(test)]
mod test_project {
use super::*;
use crate::writer::*;
use rair_io::*;
use std::fs;
#[test]
fn test_project_help() {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let load = Load::new();
let save = Save::new();
load.help(&mut core);
save.help(&mut core);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Command: [load]\n\n\
Usage:\n\
load [file_path]\tload project from given path.\n\
Command: [save]\n\n\
Usage:\n\
save [file_path]\tSave project into given path.\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
}
#[test]
fn test_project() {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let mut load = Load::new();
let mut save = Save::new();
core.io.open("malloc://0x500", IoMode::READ | IoMode::WRITE).unwrap();
core.io.open_at("malloc://0x1337", IoMode::READ | IoMode::WRITE, 0x31000).unwrap();
core.io.map(0x31000, 0xfff31000, 0x337).unwrap();
save.run(&mut core, &["rair_project".to_string()]);
core.io.close_all();
load.run(&mut core, &["rair_project".to_string()]);
core.run("files", &[]);
core.run("maps", &[]);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Handle\tStart address\tsize\t\tPermissions\tURI\n\
0\t0x00000000\t0x00000500\tWRITE | READ\tmalloc://0x500\n\
1\t0x00031000\t0x00001337\tWRITE | READ\tmalloc://0x1337\n\
Virtual Address Physical Address Size\n\
0xfff31000 0x31000 0x337\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
fs::remove_file("rair_project").unwrap();
}
}
| run | identifier_name |
project.rs | /*
* project.rs: Commands to save/load projects.
* Copyright (C) 2019 Oddcoder
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::core::*;
use crate::helper::*;
use flate2::write::{ZlibDecoder, ZlibEncoder};
use flate2::Compression;
use serde::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::mem;
#[derive(Default)]
pub struct Save {}
impl Save {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Save {
fn run(&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let data = match serde_cbor::to_vec(&core) {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to serialize project", &e.to_string()),
};
let mut file = match File::create(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressor = ZlibEncoder::new(Vec::new(), Compression::default());
compressor.write_all(&data).unwrap();
let compressed_data = compressor.finish().unwrap();
if let Err(e) = file.write_all(&compressed_data) {
return error_msg(core, "Failed to save project", &e.to_string());
}
}
fn help(&self, core: &mut Core) {
help(core, &"save", &"", vec![("[file_path]", "Save project into given path.")]);
}
}
#[derive(Default)]
pub struct Load {}
impl Load {
pub fn new() -> Self {
Default::default()
}
}
impl Cmd for Load {
fn run(&mut self, core: &mut Core, args: &[String]) {
if args.len()!= 1 {
expect(core, args.len() as u64, 1);
return;
}
let mut file = match File::open(&args[0]) {
Ok(file) => file,
Err(e) => return error_msg(core, "Failed to open file", &e.to_string()),
};
let mut compressed_data: Vec<u8> = Vec::new();
if let Err(e) = file.read_to_end(&mut compressed_data) {
return error_msg(core, "Failed to load project", &e.to_string());
}
let mut data = Vec::new();
let mut decompressor = ZlibDecoder::new(data);
if let Err(e) = decompressor.write_all(&compressed_data) {
return error_msg(core, "Failed to decompress project", &e.to_string());
}
data = match decompressor.finish() {
Ok(data) => data,
Err(e) => return error_msg(core, "Failed to decompress project", &e.to_string()),
};
let mut deserializer = serde_cbor::Deserializer::from_slice(&data);
let mut core2: Core = match Core::deserialize(&mut deserializer) {
Ok(core) => core,
Err(e) => return error_msg(core, "Failed to load project", &e.to_string()),
};
mem::swap(&mut core.stdout, &mut core2.stdout);
mem::swap(&mut core.stderr, &mut core2.stderr);
mem::swap(&mut core.env, &mut core2.env);
core2.set_commands(core.commands());
*core = core2;
}
fn help(&self, core: &mut Core) {
help(core, &"load", &"", vec![("[file_path]", "load project from given path.")]);
}
}
#[cfg(test)]
mod test_project {
use super::*;
use crate::writer::*;
use rair_io::*;
use std::fs;
#[test]
fn test_project_help() {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf();
core.stdout = Writer::new_buf();
let load = Load::new();
let save = Save::new();
load.help(&mut core);
save.help(&mut core);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Command: [load]\n\n\
Usage:\n\
load [file_path]\tload project from given path.\n\
Command: [save]\n\n\
Usage:\n\
save [file_path]\tSave project into given path.\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
}
#[test]
fn test_project() {
let mut core = Core::new_no_colors();
core.stderr = Writer::new_buf(); | core.stdout = Writer::new_buf();
let mut load = Load::new();
let mut save = Save::new();
core.io.open("malloc://0x500", IoMode::READ | IoMode::WRITE).unwrap();
core.io.open_at("malloc://0x1337", IoMode::READ | IoMode::WRITE, 0x31000).unwrap();
core.io.map(0x31000, 0xfff31000, 0x337).unwrap();
save.run(&mut core, &["rair_project".to_string()]);
core.io.close_all();
load.run(&mut core, &["rair_project".to_string()]);
core.run("files", &[]);
core.run("maps", &[]);
assert_eq!(
core.stdout.utf8_string().unwrap(),
"Handle\tStart address\tsize\t\tPermissions\tURI\n\
0\t0x00000000\t0x00000500\tWRITE | READ\tmalloc://0x500\n\
1\t0x00031000\t0x00001337\tWRITE | READ\tmalloc://0x1337\n\
Virtual Address Physical Address Size\n\
0xfff31000 0x31000 0x337\n"
);
assert_eq!(core.stderr.utf8_string().unwrap(), "");
fs::remove_file("rair_project").unwrap();
}
} | random_line_split |
|
persistable.rs | use std::marker::PhantomData;
use expression::Expression;
use query_builder::{QueryBuilder, BuildQueryResult};
use query_source::{Table, Column};
use types::NativeSqlType;
/// Represents that a structure can be used to to insert a new row into the database.
/// Implementations can be automatically generated by
/// [`#[insertable_into]`](https://github.com/sgrif/diesel/tree/master/diesel_codegen#insertable_intotable_name).
/// This is automatically implemented for `&[T]`, `Vec<T>` and `&Vec<T>` for inserting more than
/// one record.
pub trait Insertable<T: Table> {
type Columns: InsertableColumns<T>;
type Values: Expression<SqlType=<Self::Columns as InsertableColumns<T>>::SqlType>;
fn columns() -> Self::Columns;
fn values(self) -> Self::Values;
}
pub trait InsertableColumns<T: Table> {
type SqlType: NativeSqlType;
fn names(&self) -> String;
}
impl<'a, T, U> Insertable<T> for &'a [U] where
T: Table,
&'a U: Insertable<T>,
{
type Columns = <&'a U as Insertable<T>>::Columns;
type Values = InsertValues<'a, T, U>;
fn columns() -> Self::Columns {
<&'a U>::columns()
}
fn values(self) -> Self::Values {
InsertValues {
values: self,
_marker: PhantomData,
}
}
}
impl<'a, T, U> Insertable<T> for &'a Vec<U> where
T: Table,
&'a U: Insertable<T>,
{
type Columns = <&'a U as Insertable<T>>::Columns;
type Values = InsertValues<'a, T, U>;
fn | () -> Self::Columns {
<&'a U>::columns()
}
fn values(self) -> Self::Values {
InsertValues {
values: &*self,
_marker: PhantomData,
}
}
}
pub struct InsertValues<'a, T, U: 'a> {
values: &'a [U],
_marker: PhantomData<T>,
}
impl<'a, T, U> Expression for InsertValues<'a, T, U> where
T: Table,
&'a U: Insertable<T>,
{
type SqlType = <<&'a U as Insertable<T>>::Columns as InsertableColumns<T>>::SqlType;
fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {
self.to_insert_sql(out)
}
fn to_insert_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {
for (i, record) in self.values.into_iter().enumerate() {
if i!= 0 {
out.push_sql(", ");
}
try!(record.values().to_insert_sql(out));
}
Ok(())
}
}
impl<C: Column<Table=T>, T: Table> InsertableColumns<T> for C {
type SqlType = <Self as Expression>::SqlType;
fn names(&self) -> String {
Self::name().to_string()
}
}
| columns | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.