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 |
---|---|---|---|---|
builder.rs
|
use super::{op::*, Script};
use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*};
type FnRef = (u8, u32); // ID, pointer
#[derive(Clone, Debug, Default)]
pub struct Builder {
lookup_table: Vec<FnRef>,
body: Vec<u8>,
}
impl Builder {
pub fn new() -> Self {
Self {
lookup_table: Vec::new(),
body: Vec::new(),
}
}
/// Returns the script on success, otherwise an error with the total script size that has exceeded the max script
/// byte size.
pub fn build(self) -> Result<Script, usize> {
// 1 byte for fn len, 5 bytes for 1 byte id + 4 bytes pointer per fn
let header_len = 1 + (self.lookup_table.len() * 5);
let total_len = header_len + self.body.len();
if total_len > MAX_SCRIPT_BYTE_SIZE {
return Err(total_len);
}
let mut script = Vec::<u8>::with_capacity(total_len);
debug_assert!(self.lookup_table.len() <= u8::max_value() as usize);
script.push(self.lookup_table.len() as u8);
for fn_ref in self.lookup_table {
script.push(fn_ref.0);
// Offset the byte pointer by the length of the header
script.push_u32(header_len as u32 + fn_ref.1);
}
script.extend(self.body);
debug_assert_eq!(
script.len(),
total_len,
"buffer capacity under utilized, total length is incorrect"
);
debug_assert_eq!(
script.capacity(),
total_len,
"additional allocation was performed, total length is incorrect"
);
Ok(Script::new(script))
}
pub fn push(mut self, function: FnBuilder) -> Self {
if self.lookup_table.len() + 1 > usize::from(u8::max_value()) {
panic!("cannot push more than {} functions", u8::max_value());
}
let byte_pos = self.body.len() as u32;
self.lookup_table.push((function.id, byte_pos));
self.body.extend(&function.byte_code);
self
}
}
#[derive(Clone, Debug)]
pub struct FnBuilder {
id: u8,
byte_code: Vec<u8>,
}
impl FnBuilder {
/// Creates a function builder with the specified `id` and function definition `fn_def`. The function definition
/// frame must represent an OpDefine operation.
pub fn new(id: u8, fn_def: OpFrame) -> Self {
let mut byte_code = vec![];
match fn_def {
OpFrame::OpDefine(args) => {
assert!(
args.len() <= usize::from(u8::max_value()),
"too many arguments provided"
);
byte_code.push(Operand::OpDefine.into());
byte_code.push(args.len() as u8);
for arg in args {
byte_code.push(arg.into());
}
}
_ => panic!("expected a function definition"),
}
|
pub fn push(mut self, frame: OpFrame) -> Self {
match frame {
// Function definition
OpFrame::OpDefine(_) => panic!("OpDefine cannot be pushed in a function"),
// Events
OpFrame::OpTransfer => self.byte_code.push(Operand::OpTransfer.into()),
// Push value
OpFrame::False => self.byte_code.push(Operand::PushFalse.into()),
OpFrame::True => self.byte_code.push(Operand::PushTrue.into()),
OpFrame::PubKey(key) => {
self.byte_code.push(Operand::PushPubKey.into());
self.byte_code.extend(key.as_ref());
}
OpFrame::ScriptHash(hash) => {
self.byte_code.push(Operand::PushScriptHash.into());
self.byte_code.extend(hash.as_ref());
}
OpFrame::Asset(asset) => {
self.byte_code.push(Operand::PushAsset.into());
self.byte_code.extend(&asset.amount.to_be_bytes());
}
// Arithmetic
OpFrame::OpLoadAmt => self.byte_code.push(Operand::OpLoadAmt.into()),
OpFrame::OpLoadRemAmt => self.byte_code.push(Operand::OpLoadRemAmt.into()),
OpFrame::OpAdd => self.byte_code.push(Operand::OpAdd.into()),
OpFrame::OpSub => self.byte_code.push(Operand::OpSub.into()),
OpFrame::OpMul => self.byte_code.push(Operand::OpMul.into()),
OpFrame::OpDiv => self.byte_code.push(Operand::OpDiv.into()),
// Logic
OpFrame::OpNot => self.byte_code.push(Operand::OpNot.into()),
OpFrame::OpIf => self.byte_code.push(Operand::OpIf.into()),
OpFrame::OpElse => self.byte_code.push(Operand::OpElse.into()),
OpFrame::OpEndIf => self.byte_code.push(Operand::OpEndIf.into()),
OpFrame::OpReturn => self.byte_code.push(Operand::OpReturn.into()),
// Crypto
OpFrame::OpCheckSig => self.byte_code.push(Operand::OpCheckSig.into()),
OpFrame::OpCheckSigFastFail => {
self.byte_code.push(Operand::OpCheckSigFastFail.into());
}
OpFrame::OpCheckMultiSig(threshold, key_count) => {
self.byte_code
.extend(&[Operand::OpCheckMultiSig.into(), threshold, key_count]);
}
OpFrame::OpCheckMultiSigFastFail(threshold, key_count) => self.byte_code.extend(&[
Operand::OpCheckMultiSigFastFail.into(),
threshold,
key_count,
]),
}
self
}
}
|
Self { id, byte_code }
}
|
random_line_split
|
builder.rs
|
use super::{op::*, Script};
use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*};
type FnRef = (u8, u32); // ID, pointer
#[derive(Clone, Debug, Default)]
pub struct Builder {
lookup_table: Vec<FnRef>,
body: Vec<u8>,
}
impl Builder {
pub fn
|
() -> Self {
Self {
lookup_table: Vec::new(),
body: Vec::new(),
}
}
/// Returns the script on success, otherwise an error with the total script size that has exceeded the max script
/// byte size.
pub fn build(self) -> Result<Script, usize> {
// 1 byte for fn len, 5 bytes for 1 byte id + 4 bytes pointer per fn
let header_len = 1 + (self.lookup_table.len() * 5);
let total_len = header_len + self.body.len();
if total_len > MAX_SCRIPT_BYTE_SIZE {
return Err(total_len);
}
let mut script = Vec::<u8>::with_capacity(total_len);
debug_assert!(self.lookup_table.len() <= u8::max_value() as usize);
script.push(self.lookup_table.len() as u8);
for fn_ref in self.lookup_table {
script.push(fn_ref.0);
// Offset the byte pointer by the length of the header
script.push_u32(header_len as u32 + fn_ref.1);
}
script.extend(self.body);
debug_assert_eq!(
script.len(),
total_len,
"buffer capacity under utilized, total length is incorrect"
);
debug_assert_eq!(
script.capacity(),
total_len,
"additional allocation was performed, total length is incorrect"
);
Ok(Script::new(script))
}
pub fn push(mut self, function: FnBuilder) -> Self {
if self.lookup_table.len() + 1 > usize::from(u8::max_value()) {
panic!("cannot push more than {} functions", u8::max_value());
}
let byte_pos = self.body.len() as u32;
self.lookup_table.push((function.id, byte_pos));
self.body.extend(&function.byte_code);
self
}
}
#[derive(Clone, Debug)]
pub struct FnBuilder {
id: u8,
byte_code: Vec<u8>,
}
impl FnBuilder {
/// Creates a function builder with the specified `id` and function definition `fn_def`. The function definition
/// frame must represent an OpDefine operation.
pub fn new(id: u8, fn_def: OpFrame) -> Self {
let mut byte_code = vec![];
match fn_def {
OpFrame::OpDefine(args) => {
assert!(
args.len() <= usize::from(u8::max_value()),
"too many arguments provided"
);
byte_code.push(Operand::OpDefine.into());
byte_code.push(args.len() as u8);
for arg in args {
byte_code.push(arg.into());
}
}
_ => panic!("expected a function definition"),
}
Self { id, byte_code }
}
pub fn push(mut self, frame: OpFrame) -> Self {
match frame {
// Function definition
OpFrame::OpDefine(_) => panic!("OpDefine cannot be pushed in a function"),
// Events
OpFrame::OpTransfer => self.byte_code.push(Operand::OpTransfer.into()),
// Push value
OpFrame::False => self.byte_code.push(Operand::PushFalse.into()),
OpFrame::True => self.byte_code.push(Operand::PushTrue.into()),
OpFrame::PubKey(key) => {
self.byte_code.push(Operand::PushPubKey.into());
self.byte_code.extend(key.as_ref());
}
OpFrame::ScriptHash(hash) => {
self.byte_code.push(Operand::PushScriptHash.into());
self.byte_code.extend(hash.as_ref());
}
OpFrame::Asset(asset) => {
self.byte_code.push(Operand::PushAsset.into());
self.byte_code.extend(&asset.amount.to_be_bytes());
}
// Arithmetic
OpFrame::OpLoadAmt => self.byte_code.push(Operand::OpLoadAmt.into()),
OpFrame::OpLoadRemAmt => self.byte_code.push(Operand::OpLoadRemAmt.into()),
OpFrame::OpAdd => self.byte_code.push(Operand::OpAdd.into()),
OpFrame::OpSub => self.byte_code.push(Operand::OpSub.into()),
OpFrame::OpMul => self.byte_code.push(Operand::OpMul.into()),
OpFrame::OpDiv => self.byte_code.push(Operand::OpDiv.into()),
// Logic
OpFrame::OpNot => self.byte_code.push(Operand::OpNot.into()),
OpFrame::OpIf => self.byte_code.push(Operand::OpIf.into()),
OpFrame::OpElse => self.byte_code.push(Operand::OpElse.into()),
OpFrame::OpEndIf => self.byte_code.push(Operand::OpEndIf.into()),
OpFrame::OpReturn => self.byte_code.push(Operand::OpReturn.into()),
// Crypto
OpFrame::OpCheckSig => self.byte_code.push(Operand::OpCheckSig.into()),
OpFrame::OpCheckSigFastFail => {
self.byte_code.push(Operand::OpCheckSigFastFail.into());
}
OpFrame::OpCheckMultiSig(threshold, key_count) => {
self.byte_code
.extend(&[Operand::OpCheckMultiSig.into(), threshold, key_count]);
}
OpFrame::OpCheckMultiSigFastFail(threshold, key_count) => self.byte_code.extend(&[
Operand::OpCheckMultiSigFastFail.into(),
threshold,
key_count,
]),
}
self
}
}
|
new
|
identifier_name
|
mod.rs
|
pub mod compare;
pub mod sort;
pub mod tool;
pub use self::compare::*;
pub use self::sort::*;
use gossyp_base::*;
use gossyp_base::basic::*;
///
/// ToolSet containing the algorithm tools
///
pub struct AlgorithmTools { }
impl AlgorithmTools {
pub fn new() -> AlgorithmTools {
AlgorithmTools { }
}
}
impl<'a> ToolSet for &'a AlgorithmTools {
fn create_tools(self, _environment: &Environment) -> Vec<(String, Box<Tool>)> {
vec![
(String::from(self::tool::COMPARE_VALUES), Box::new(CompareTool::new())),
(String::from(self::tool::SORT), Box::new(SortTool::new()))
]
}
}
|
fn create_tools(self, environment: &Environment) -> Vec<(String, Box<Tool>)> {
(&self).create_tools(environment)
}
}
|
impl ToolSet for AlgorithmTools {
|
random_line_split
|
mod.rs
|
pub mod compare;
pub mod sort;
pub mod tool;
pub use self::compare::*;
pub use self::sort::*;
use gossyp_base::*;
use gossyp_base::basic::*;
///
/// ToolSet containing the algorithm tools
///
pub struct
|
{ }
impl AlgorithmTools {
pub fn new() -> AlgorithmTools {
AlgorithmTools { }
}
}
impl<'a> ToolSet for &'a AlgorithmTools {
fn create_tools(self, _environment: &Environment) -> Vec<(String, Box<Tool>)> {
vec![
(String::from(self::tool::COMPARE_VALUES), Box::new(CompareTool::new())),
(String::from(self::tool::SORT), Box::new(SortTool::new()))
]
}
}
impl ToolSet for AlgorithmTools {
fn create_tools(self, environment: &Environment) -> Vec<(String, Box<Tool>)> {
(&self).create_tools(environment)
}
}
|
AlgorithmTools
|
identifier_name
|
mod.rs
|
pub mod compare;
pub mod sort;
pub mod tool;
pub use self::compare::*;
pub use self::sort::*;
use gossyp_base::*;
use gossyp_base::basic::*;
///
/// ToolSet containing the algorithm tools
///
pub struct AlgorithmTools { }
impl AlgorithmTools {
pub fn new() -> AlgorithmTools {
AlgorithmTools { }
}
}
impl<'a> ToolSet for &'a AlgorithmTools {
fn create_tools(self, _environment: &Environment) -> Vec<(String, Box<Tool>)> {
vec![
(String::from(self::tool::COMPARE_VALUES), Box::new(CompareTool::new())),
(String::from(self::tool::SORT), Box::new(SortTool::new()))
]
}
}
impl ToolSet for AlgorithmTools {
fn create_tools(self, environment: &Environment) -> Vec<(String, Box<Tool>)>
|
}
|
{
(&self).create_tools(environment)
}
|
identifier_body
|
configpaths_06.rs
|
use libnewsboat::configpaths::ConfigPaths;
use section_testing::{enable_sections, section};
use std::{env, fs, path};
use tempfile::TempDir;
fn assert_paths_are_inside_dirs(config_dir: &path::Path, data_dir: &path::Path) {
let paths = ConfigPaths::new();
assert!(paths.initialized());
assert_eq!(paths.config_file(), config_dir.join("config"));
assert_eq!(paths.url_file(), config_dir.join("urls"));
assert_eq!(paths.cache_file(), data_dir.join("cache.db"));
assert_eq!(paths.lock_file(), data_dir.join("cache.db.lock"));
assert_eq!(paths.queue_file(), data_dir.join("queue"));
assert_eq!(paths.search_file(), data_dir.join("history.search"));
|
assert_eq!(paths.cmdline_file(), data_dir.join("history.cmdline"));
}
enable_sections! {
#[test]
fn t_configpaths_returns_paths_to_newsboat_xdg_dirs_if_they_exist_and_dotdir_doesnt()
{
let tmp = TempDir::new().unwrap();
let config_dir = tmp.path().join(".config").join("newsboat");
fs::create_dir_all(&config_dir).ok();
let data_dir = tmp.path().join(".local").join("share").join("newsboat");
fs::create_dir_all(&data_dir).ok();
env::set_var("HOME", tmp.path());
if section!("XDG_CONFIG_HOME is set") {
env::set_var("XDG_CONFIG_HOME", tmp.path().join(".config"));
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
if section!("XDG_CONFIG_HOME is not set") {
env::remove_var("XDG_CONFIG_HOME");
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
}
}
|
random_line_split
|
|
configpaths_06.rs
|
use libnewsboat::configpaths::ConfigPaths;
use section_testing::{enable_sections, section};
use std::{env, fs, path};
use tempfile::TempDir;
fn
|
(config_dir: &path::Path, data_dir: &path::Path) {
let paths = ConfigPaths::new();
assert!(paths.initialized());
assert_eq!(paths.config_file(), config_dir.join("config"));
assert_eq!(paths.url_file(), config_dir.join("urls"));
assert_eq!(paths.cache_file(), data_dir.join("cache.db"));
assert_eq!(paths.lock_file(), data_dir.join("cache.db.lock"));
assert_eq!(paths.queue_file(), data_dir.join("queue"));
assert_eq!(paths.search_file(), data_dir.join("history.search"));
assert_eq!(paths.cmdline_file(), data_dir.join("history.cmdline"));
}
enable_sections! {
#[test]
fn t_configpaths_returns_paths_to_newsboat_xdg_dirs_if_they_exist_and_dotdir_doesnt()
{
let tmp = TempDir::new().unwrap();
let config_dir = tmp.path().join(".config").join("newsboat");
fs::create_dir_all(&config_dir).ok();
let data_dir = tmp.path().join(".local").join("share").join("newsboat");
fs::create_dir_all(&data_dir).ok();
env::set_var("HOME", tmp.path());
if section!("XDG_CONFIG_HOME is set") {
env::set_var("XDG_CONFIG_HOME", tmp.path().join(".config"));
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
if section!("XDG_CONFIG_HOME is not set") {
env::remove_var("XDG_CONFIG_HOME");
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
}
}
|
assert_paths_are_inside_dirs
|
identifier_name
|
configpaths_06.rs
|
use libnewsboat::configpaths::ConfigPaths;
use section_testing::{enable_sections, section};
use std::{env, fs, path};
use tempfile::TempDir;
fn assert_paths_are_inside_dirs(config_dir: &path::Path, data_dir: &path::Path)
|
enable_sections! {
#[test]
fn t_configpaths_returns_paths_to_newsboat_xdg_dirs_if_they_exist_and_dotdir_doesnt()
{
let tmp = TempDir::new().unwrap();
let config_dir = tmp.path().join(".config").join("newsboat");
fs::create_dir_all(&config_dir).ok();
let data_dir = tmp.path().join(".local").join("share").join("newsboat");
fs::create_dir_all(&data_dir).ok();
env::set_var("HOME", tmp.path());
if section!("XDG_CONFIG_HOME is set") {
env::set_var("XDG_CONFIG_HOME", tmp.path().join(".config"));
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
if section!("XDG_CONFIG_HOME is not set") {
env::remove_var("XDG_CONFIG_HOME");
if section!("XDG_DATA_HOME is set") {
env::set_var("XDG_DATA_HOME", tmp.path().join(".local").join("share"));
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
if section!("XDG_DATA_HOME is not set") {
env::remove_var("XDG_DATA_HOME");
assert_paths_are_inside_dirs(&config_dir, &data_dir);
}
}
}
}
|
{
let paths = ConfigPaths::new();
assert!(paths.initialized());
assert_eq!(paths.config_file(), config_dir.join("config"));
assert_eq!(paths.url_file(), config_dir.join("urls"));
assert_eq!(paths.cache_file(), data_dir.join("cache.db"));
assert_eq!(paths.lock_file(), data_dir.join("cache.db.lock"));
assert_eq!(paths.queue_file(), data_dir.join("queue"));
assert_eq!(paths.search_file(), data_dir.join("history.search"));
assert_eq!(paths.cmdline_file(), data_dir.join("history.cmdline"));
}
|
identifier_body
|
self_user.rs
|
use crate::server::is_authenticated;
use crate::server::model::guild::GuildModel;
use crate::server::model::self_user::SelfUserModel;
use crate::service::user_secret::UserSecretService;
use crate::Config;
use actix_web::{get, web, HttpResponse, Responder};
use typemap_rev::TypeMap;
#[get("/@me")]
pub async fn
|
(
config: web::Data<Config>,
services: web::Data<TypeMap>,
req: web::HttpRequest,
) -> impl Responder {
let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await {
id
} else {
return HttpResponse::Unauthorized().finish();
};
let user_secret_service = if let Some(service) = services.get::<UserSecretService>() {
service
} else {
return HttpResponse::InternalServerError().finish();
};
let self_user_guilds: Vec<GuildModel> = match user_secret_service
.get_self_user_guilds(&services, user_id)
.await
{
Ok(guilds) => guilds
.iter()
.map(|guild| GuildModel {
id: guild.id.to_string(),
name: guild.name.clone(),
icon_url: guild.icon_url.clone(),
})
.collect(),
Err(_) => return HttpResponse::Unauthorized().finish(),
};
let self_user = match user_secret_service.get_self_user(user_id).await {
Ok(self_user) => self_user,
Err(_) => return HttpResponse::Unauthorized().finish(),
};
HttpResponse::Ok().json(SelfUserModel {
id: self_user.id.to_string(),
name: self_user.tag.clone(),
avatar_url: self_user.avatar_url.clone(),
guilds: self_user_guilds,
})
}
|
get_self
|
identifier_name
|
self_user.rs
|
use crate::server::is_authenticated;
use crate::server::model::guild::GuildModel;
use crate::server::model::self_user::SelfUserModel;
use crate::service::user_secret::UserSecretService;
use crate::Config;
use actix_web::{get, web, HttpResponse, Responder};
use typemap_rev::TypeMap;
#[get("/@me")]
pub async fn get_self(
config: web::Data<Config>,
|
id
} else {
return HttpResponse::Unauthorized().finish();
};
let user_secret_service = if let Some(service) = services.get::<UserSecretService>() {
service
} else {
return HttpResponse::InternalServerError().finish();
};
let self_user_guilds: Vec<GuildModel> = match user_secret_service
.get_self_user_guilds(&services, user_id)
.await
{
Ok(guilds) => guilds
.iter()
.map(|guild| GuildModel {
id: guild.id.to_string(),
name: guild.name.clone(),
icon_url: guild.icon_url.clone(),
})
.collect(),
Err(_) => return HttpResponse::Unauthorized().finish(),
};
let self_user = match user_secret_service.get_self_user(user_id).await {
Ok(self_user) => self_user,
Err(_) => return HttpResponse::Unauthorized().finish(),
};
HttpResponse::Ok().json(SelfUserModel {
id: self_user.id.to_string(),
name: self_user.tag.clone(),
avatar_url: self_user.avatar_url.clone(),
guilds: self_user_guilds,
})
}
|
services: web::Data<TypeMap>,
req: web::HttpRequest,
) -> impl Responder {
let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await {
|
random_line_split
|
self_user.rs
|
use crate::server::is_authenticated;
use crate::server::model::guild::GuildModel;
use crate::server::model::self_user::SelfUserModel;
use crate::service::user_secret::UserSecretService;
use crate::Config;
use actix_web::{get, web, HttpResponse, Responder};
use typemap_rev::TypeMap;
#[get("/@me")]
pub async fn get_self(
config: web::Data<Config>,
services: web::Data<TypeMap>,
req: web::HttpRequest,
) -> impl Responder {
let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await
|
else {
return HttpResponse::Unauthorized().finish();
};
let user_secret_service = if let Some(service) = services.get::<UserSecretService>() {
service
} else {
return HttpResponse::InternalServerError().finish();
};
let self_user_guilds: Vec<GuildModel> = match user_secret_service
.get_self_user_guilds(&services, user_id)
.await
{
Ok(guilds) => guilds
.iter()
.map(|guild| GuildModel {
id: guild.id.to_string(),
name: guild.name.clone(),
icon_url: guild.icon_url.clone(),
})
.collect(),
Err(_) => return HttpResponse::Unauthorized().finish(),
};
let self_user = match user_secret_service.get_self_user(user_id).await {
Ok(self_user) => self_user,
Err(_) => return HttpResponse::Unauthorized().finish(),
};
HttpResponse::Ok().json(SelfUserModel {
id: self_user.id.to_string(),
name: self_user.tag.clone(),
avatar_url: self_user.avatar_url.clone(),
guilds: self_user_guilds,
})
}
|
{
id
}
|
conditional_block
|
self_user.rs
|
use crate::server::is_authenticated;
use crate::server::model::guild::GuildModel;
use crate::server::model::self_user::SelfUserModel;
use crate::service::user_secret::UserSecretService;
use crate::Config;
use actix_web::{get, web, HttpResponse, Responder};
use typemap_rev::TypeMap;
#[get("/@me")]
pub async fn get_self(
config: web::Data<Config>,
services: web::Data<TypeMap>,
req: web::HttpRequest,
) -> impl Responder
|
id: guild.id.to_string(),
name: guild.name.clone(),
icon_url: guild.icon_url.clone(),
})
.collect(),
Err(_) => return HttpResponse::Unauthorized().finish(),
};
let self_user = match user_secret_service.get_self_user(user_id).await {
Ok(self_user) => self_user,
Err(_) => return HttpResponse::Unauthorized().finish(),
};
HttpResponse::Ok().json(SelfUserModel {
id: self_user.id.to_string(),
name: self_user.tag.clone(),
avatar_url: self_user.avatar_url.clone(),
guilds: self_user_guilds,
})
}
|
{
let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await {
id
} else {
return HttpResponse::Unauthorized().finish();
};
let user_secret_service = if let Some(service) = services.get::<UserSecretService>() {
service
} else {
return HttpResponse::InternalServerError().finish();
};
let self_user_guilds: Vec<GuildModel> = match user_secret_service
.get_self_user_guilds(&services, user_id)
.await
{
Ok(guilds) => guilds
.iter()
.map(|guild| GuildModel {
|
identifier_body
|
playbin.rs
|
use ffi::*;
use pipeline::Pipeline;
use element::Element;
use ::Transfer;
use reference::Reference;
use std::ops::{Deref, DerefMut};
unsafe impl Sync for PlayBin {}
unsafe impl Send for PlayBin {}
pub struct PlayBin{
playbin: Pipeline
}
impl PlayBin{
pub fn new(name: &str) -> Option<PlayBin>{
let pipeline = Element::new("playbin",name);
match pipeline{
Some(p) => {
match unsafe{ Pipeline::new_from_gst_pipeline( p.transfer() as *mut GstPipeline) }{
Some(p) => Some(PlayBin{ playbin: p }),
None => None
}
}
None => None
}
}
pub fn set_audio_sink(&mut self, audio_sink: &Element){
self.set("audio-sink", audio_sink);
}
/*pub fn frame(&self) -> GBuffer{
GBuffer::new(playbin.get<GstBuffer*>("frame"))
}*/
pub fn set_subtitle_font_desc(&mut self, font: &str){
self.set("subtitle-font-desc", font);
}
pub fn set_video_sink(&mut self, video_sink: &Element){
self.set("video-sink", video_sink);
}
pub fn set_vis_plugin(&mut self, vis_plugin: &Element){
self.set("vis-plugin", vis_plugin);
}
pub fn set_volume(&mut self, volume: f64){
self.set("volume", volume);
}
pub fn set_connection_speed(&mut self, connection_speed: u64){
self.set("connection-speed",connection_speed);
}
pub fn set_av_offset(&mut self, av_offset: i64){
self.set("av-offset", av_offset);
}
pub fn set_buffer_duration(&mut self, buffer_duration: i64){
self.set("buffer-duration",buffer_duration);
}
pub fn set_current_audio(&mut self, current_audio: i32){
self.set("current-audio",current_audio);
}
pub fn set_current_text(&mut self, current_text: i32){
self.set("current-text", current_text);
}
/*pub fn set_flags(&self, flags: GstPlayFlags){
self.set("flags", flags);
}*/
pub fn mute(&mut self){
self.set("mute", 1 as gboolean);
}
pub fn unmute(&mut self){
self.set("mute", 0 as gboolean);
}
pub fn set_ring_buffer_max_size(&mut self, ring_buffer_max_size: u64){
self.set("ring-buffer-max-size", ring_buffer_max_size);
}
pub fn set_source(&mut self, source: &Element){
self.set("source", source);
}
pub fn set_subtitle_encoding(&mut self, encoding: &str){
self.set("subtitle-encoding", encoding);
}
pub fn set_suburi(&mut self, suburi: &str){
self.set("suburi", suburi);
}
pub fn set_text_sink(&mut self, textsink: &Element){
self.set("text-sink", textsink);
}
pub fn set_uri(&mut self, uri: &str){
self.set("uri", uri);
}
pub fn
|
(&mut self, force_aspect_ratio: bool){
self.set("force-aspect-ratio", force_aspect_ratio as gboolean);
}
pub fn set_audio_stream_combiner(&mut self, audio_stream_combiner: &Element){
self.set("audio-stream-combiner", audio_stream_combiner);
}
pub fn set_video_stream_combiner(&mut self, video_stream_combiner: &Element){
self.set("video-stream-combiner", video_stream_combiner);
}
pub fn set_flags(&mut self, flags: i32){
self.set("flags", flags);
}
}
impl ::Transfer for PlayBin{
unsafe fn transfer(self) -> *mut GstElement{
self.playbin.transfer()
}
}
impl Reference for PlayBin{
fn reference(&self) -> PlayBin{
PlayBin{ playbin: self.playbin.reference()}
}
}
impl AsRef<Pipeline> for PlayBin{
fn as_ref(&self) -> &Pipeline{
&self.playbin
}
}
impl AsMut<Pipeline> for PlayBin{
fn as_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
impl From<PlayBin> for Pipeline{
fn from(b: PlayBin) -> Pipeline{
b.playbin
}
}
impl Deref for PlayBin{
type Target = Pipeline;
fn deref(&self) -> &Pipeline{
&self.playbin
}
}
impl DerefMut for PlayBin{
fn deref_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
|
set_force_aspect_ratio
|
identifier_name
|
playbin.rs
|
use ffi::*;
use pipeline::Pipeline;
use element::Element;
use ::Transfer;
use reference::Reference;
use std::ops::{Deref, DerefMut};
unsafe impl Sync for PlayBin {}
unsafe impl Send for PlayBin {}
pub struct PlayBin{
playbin: Pipeline
}
impl PlayBin{
pub fn new(name: &str) -> Option<PlayBin>{
let pipeline = Element::new("playbin",name);
match pipeline{
Some(p) => {
match unsafe{ Pipeline::new_from_gst_pipeline( p.transfer() as *mut GstPipeline) }{
Some(p) => Some(PlayBin{ playbin: p }),
None => None
}
}
None => None
}
}
pub fn set_audio_sink(&mut self, audio_sink: &Element){
self.set("audio-sink", audio_sink);
}
/*pub fn frame(&self) -> GBuffer{
GBuffer::new(playbin.get<GstBuffer*>("frame"))
}*/
pub fn set_subtitle_font_desc(&mut self, font: &str){
self.set("subtitle-font-desc", font);
}
pub fn set_video_sink(&mut self, video_sink: &Element){
self.set("video-sink", video_sink);
}
pub fn set_vis_plugin(&mut self, vis_plugin: &Element){
self.set("vis-plugin", vis_plugin);
}
pub fn set_volume(&mut self, volume: f64){
self.set("volume", volume);
}
pub fn set_connection_speed(&mut self, connection_speed: u64){
self.set("connection-speed",connection_speed);
}
pub fn set_av_offset(&mut self, av_offset: i64){
self.set("av-offset", av_offset);
}
pub fn set_buffer_duration(&mut self, buffer_duration: i64){
self.set("buffer-duration",buffer_duration);
}
pub fn set_current_audio(&mut self, current_audio: i32){
self.set("current-audio",current_audio);
}
pub fn set_current_text(&mut self, current_text: i32){
self.set("current-text", current_text);
}
/*pub fn set_flags(&self, flags: GstPlayFlags){
self.set("flags", flags);
}*/
pub fn mute(&mut self){
self.set("mute", 1 as gboolean);
}
pub fn unmute(&mut self){
self.set("mute", 0 as gboolean);
}
pub fn set_ring_buffer_max_size(&mut self, ring_buffer_max_size: u64){
self.set("ring-buffer-max-size", ring_buffer_max_size);
}
pub fn set_source(&mut self, source: &Element){
self.set("source", source);
}
pub fn set_subtitle_encoding(&mut self, encoding: &str){
self.set("subtitle-encoding", encoding);
}
pub fn set_suburi(&mut self, suburi: &str){
self.set("suburi", suburi);
}
pub fn set_text_sink(&mut self, textsink: &Element)
|
pub fn set_uri(&mut self, uri: &str){
self.set("uri", uri);
}
pub fn set_force_aspect_ratio(&mut self, force_aspect_ratio: bool){
self.set("force-aspect-ratio", force_aspect_ratio as gboolean);
}
pub fn set_audio_stream_combiner(&mut self, audio_stream_combiner: &Element){
self.set("audio-stream-combiner", audio_stream_combiner);
}
pub fn set_video_stream_combiner(&mut self, video_stream_combiner: &Element){
self.set("video-stream-combiner", video_stream_combiner);
}
pub fn set_flags(&mut self, flags: i32){
self.set("flags", flags);
}
}
impl ::Transfer for PlayBin{
unsafe fn transfer(self) -> *mut GstElement{
self.playbin.transfer()
}
}
impl Reference for PlayBin{
fn reference(&self) -> PlayBin{
PlayBin{ playbin: self.playbin.reference()}
}
}
impl AsRef<Pipeline> for PlayBin{
fn as_ref(&self) -> &Pipeline{
&self.playbin
}
}
impl AsMut<Pipeline> for PlayBin{
fn as_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
impl From<PlayBin> for Pipeline{
fn from(b: PlayBin) -> Pipeline{
b.playbin
}
}
impl Deref for PlayBin{
type Target = Pipeline;
fn deref(&self) -> &Pipeline{
&self.playbin
}
}
impl DerefMut for PlayBin{
fn deref_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
|
{
self.set("text-sink", textsink);
}
|
identifier_body
|
playbin.rs
|
use ffi::*;
use pipeline::Pipeline;
use element::Element;
use ::Transfer;
use reference::Reference;
use std::ops::{Deref, DerefMut};
unsafe impl Sync for PlayBin {}
unsafe impl Send for PlayBin {}
pub struct PlayBin{
playbin: Pipeline
}
impl PlayBin{
pub fn new(name: &str) -> Option<PlayBin>{
let pipeline = Element::new("playbin",name);
match pipeline{
Some(p) => {
match unsafe{ Pipeline::new_from_gst_pipeline( p.transfer() as *mut GstPipeline) }{
Some(p) => Some(PlayBin{ playbin: p }),
None => None
}
}
None => None
}
}
pub fn set_audio_sink(&mut self, audio_sink: &Element){
self.set("audio-sink", audio_sink);
}
/*pub fn frame(&self) -> GBuffer{
GBuffer::new(playbin.get<GstBuffer*>("frame"))
}*/
pub fn set_subtitle_font_desc(&mut self, font: &str){
self.set("subtitle-font-desc", font);
}
pub fn set_video_sink(&mut self, video_sink: &Element){
self.set("video-sink", video_sink);
}
pub fn set_vis_plugin(&mut self, vis_plugin: &Element){
self.set("vis-plugin", vis_plugin);
}
pub fn set_volume(&mut self, volume: f64){
self.set("volume", volume);
}
pub fn set_connection_speed(&mut self, connection_speed: u64){
self.set("connection-speed",connection_speed);
}
pub fn set_av_offset(&mut self, av_offset: i64){
self.set("av-offset", av_offset);
}
pub fn set_buffer_duration(&mut self, buffer_duration: i64){
self.set("buffer-duration",buffer_duration);
}
pub fn set_current_audio(&mut self, current_audio: i32){
self.set("current-audio",current_audio);
}
pub fn set_current_text(&mut self, current_text: i32){
self.set("current-text", current_text);
}
/*pub fn set_flags(&self, flags: GstPlayFlags){
self.set("flags", flags);
}*/
pub fn mute(&mut self){
self.set("mute", 1 as gboolean);
}
pub fn unmute(&mut self){
self.set("mute", 0 as gboolean);
}
pub fn set_ring_buffer_max_size(&mut self, ring_buffer_max_size: u64){
self.set("ring-buffer-max-size", ring_buffer_max_size);
}
pub fn set_source(&mut self, source: &Element){
self.set("source", source);
}
pub fn set_subtitle_encoding(&mut self, encoding: &str){
self.set("subtitle-encoding", encoding);
}
pub fn set_suburi(&mut self, suburi: &str){
self.set("suburi", suburi);
}
pub fn set_text_sink(&mut self, textsink: &Element){
self.set("text-sink", textsink);
}
pub fn set_uri(&mut self, uri: &str){
self.set("uri", uri);
}
pub fn set_force_aspect_ratio(&mut self, force_aspect_ratio: bool){
self.set("force-aspect-ratio", force_aspect_ratio as gboolean);
}
pub fn set_audio_stream_combiner(&mut self, audio_stream_combiner: &Element){
self.set("audio-stream-combiner", audio_stream_combiner);
}
pub fn set_video_stream_combiner(&mut self, video_stream_combiner: &Element){
self.set("video-stream-combiner", video_stream_combiner);
|
self.set("flags", flags);
}
}
impl ::Transfer for PlayBin{
unsafe fn transfer(self) -> *mut GstElement{
self.playbin.transfer()
}
}
impl Reference for PlayBin{
fn reference(&self) -> PlayBin{
PlayBin{ playbin: self.playbin.reference()}
}
}
impl AsRef<Pipeline> for PlayBin{
fn as_ref(&self) -> &Pipeline{
&self.playbin
}
}
impl AsMut<Pipeline> for PlayBin{
fn as_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
impl From<PlayBin> for Pipeline{
fn from(b: PlayBin) -> Pipeline{
b.playbin
}
}
impl Deref for PlayBin{
type Target = Pipeline;
fn deref(&self) -> &Pipeline{
&self.playbin
}
}
impl DerefMut for PlayBin{
fn deref_mut(&mut self) -> &mut Pipeline{
&mut self.playbin
}
}
|
}
pub fn set_flags(&mut self, flags: i32){
|
random_line_split
|
visitor.rs
|
use rustc::middle::{ty, def};
use rustc::middle::ty::MethodCall;
use syntax::{ast, ast_util, ast_map};
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit;
use syntax::visit::Visitor;
use std::fmt;
use std::mem::replace;
use std::collections::BTreeMap;
fn type_is_unsafe_function(ty: ty::Ty) -> bool {
match ty.sty {
ty::ty_bare_fn(_, ref f) => f.unsafety == ast::Unsafety::Unsafe,
_ => false,
}
}
pub struct NodeInfo {
pub span: Span,
pub is_fn: bool,
pub compiler: bool,
pub ffi: Vec<Span>,
pub raw_deref: Vec<Span>,
pub static_mut: Vec<Span>,
pub unsafe_call: Vec<Span>,
pub transmute: Vec<Span>,
pub transmute_imm_to_mut: Vec<Span>,
// these are only picked up with written in unsafe blocks, but *const
// as *mut is legal anywhere.
pub cast_raw_ptr_const_to_mut: Vec<Span>,
pub asm: Vec<Span>,
}
impl NodeInfo {
fn new(span: Span, is_fn: bool, compiler: bool) -> NodeInfo {
NodeInfo {
span: span,
is_fn: is_fn,
compiler: compiler,
ffi: Vec::new(),
raw_deref: Vec::new(),
static_mut: Vec::new(),
unsafe_call: Vec::new(),
transmute: Vec::new(),
transmute_imm_to_mut: Vec::new(),
cast_raw_ptr_const_to_mut: Vec::new(),
asm: Vec::new()
}
}
}
impl fmt::Debug for NodeInfo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
macro_rules! p ( ($fmt: tt, $name: ident) => {
if!self.$name.is_empty() {
if!first {
try!(write!(fmt, ", "));
} else {
first = false
}
try!(write!(fmt, concat!("{} ", $fmt), self.$name.len()))
}
});
p!("asm", asm);
p!("deref", raw_deref);
p!("ffi", ffi);
p!("static mut", static_mut);
p!("transmute", transmute);
p!("transmute & to &mut", transmute_imm_to_mut);
p!("cast *const to *mut", cast_raw_ptr_const_to_mut);
p!("unsafe call", unsafe_call);
// silence dead assign warning
if first {}
Ok(())
}
}
pub struct UnsafeVisitor<'tcx, 'a: 'tcx> {
tcx: &'tcx ty::ctxt<'a>,
/// Whether we're in an unsafe context.
node_info: Option<(ast::NodeId, NodeInfo)>,
pub unsafes: BTreeMap<ast::NodeId, NodeInfo>,
}
impl<'tcx, 'a> UnsafeVisitor<'tcx, 'a> {
pub fn new(tcx: &'tcx ty::ctxt<'a>) -> UnsafeVisitor<'tcx, 'a> {
UnsafeVisitor {
tcx: tcx,
node_info: None,
unsafes: BTreeMap::new(),
}
}
pub fn check_crate(&mut self, krate: &ast::Crate) {
visit::walk_crate(self, krate)
}
fn info<'b>(&'b mut self) -> &'b mut NodeInfo {
&mut self.node_info.as_mut().unwrap().1
}
fn check_ptr_cast(&mut self, span: Span, from: &ast::Expr, to: &ast::Expr) -> bool {
let from_ty = ty::expr_ty(self.tcx, from);
let to_ty = ty::expr_ty(self.tcx, to);
match (&from_ty.sty, &to_ty.sty) {
(&ty::ty_rptr(_, ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_rptr(_, ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().transmute_imm_to_mut.push(span);
true
}
(&ty::ty_ptr(ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_ptr(ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().cast_raw_ptr_const_to_mut.push(span);
true
}
_ => {
false
}
}
}
}
impl<'tcx,'a,'b> Visitor<'a> for UnsafeVisitor<'tcx,'b> {
fn visit_fn(&mut self, fn_kind: visit::FnKind<'a>, fn_decl: &'a ast::FnDecl,
block: &ast::Block, span: Span, node_id: ast::NodeId) {
let (is_item_fn, is_unsafe_fn) = match fn_kind {
visit::FkItemFn(_, _, fn_style, _, _) =>
(true, fn_style == ast::Unsafety::Unsafe),
visit::FkMethod(_, sig, _) =>
(true, sig.unsafety == ast::Unsafety::Unsafe),
_ => (false, false),
};
let old_node_info = if is_unsafe_fn {
replace(&mut self.node_info, Some((node_id, NodeInfo::new(span, true, false))))
} else if is_item_fn {
replace(&mut self.node_info, None)
} else {
None
};
visit::walk_fn(self, fn_kind, fn_decl, block, span);
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
fn
|
(&mut self, block: &'a ast::Block) {
let (old_node_info, inserted) = match block.rules {
ast::DefaultBlock => (None, false),
ast::UnsafeBlock(source) => {
let compiler = source == ast::CompilerGenerated;
if self.node_info.is_none() || compiler {
(replace(&mut self.node_info,
Some((block.id, NodeInfo::new(block.span, false, compiler)))),
true)
} else {
(None, false)
}
}
};
visit::walk_block(self, block);
if inserted {
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
}
fn visit_expr(&mut self, expr: &'a ast::Expr) {
if self.node_info.is_some() {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
let base_type = self.tcx.method_map.borrow()[&method_call].ty;
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
ast::ExprCall(ref base, ref args) => {
match (&base.node, &**args) {
(&ast::ExprPath(_, ref p), [ref arg])
// ew, but whatever.
if p.segments.last().unwrap().identifier.name ==
token::intern("transmute") => {
if!self.check_ptr_cast(expr.span, &**arg, expr) {
// not a */& -> *mut/&mut cast.
self.info().transmute.push(expr.span)
}
}
_ => {
let is_ffi = match self.tcx.def_map.borrow().get(&base.id) {
Some(&def::PathResolution { base_def: def::DefFn(did, _),.. }) => {
// cross-crate calls are always
// just unsafe calls.
ast_util::is_local(did) &&
match self.tcx.map.get(did.node) {
ast_map::NodeForeignItem(_) => true,
_ => false
}
}
_ => false
};
if is_ffi {
self.info().ffi.push(expr.span)
} else {
let base_type = ty::node_id_to_type(self.tcx, base.id);
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
}
}
}
ast::ExprUnary(ast::UnDeref, ref base) => {
let base_type = ty::node_id_to_type(self.tcx, base.id);
match base_type.sty {
ty::ty_ptr(_) => {
self.info().raw_deref.push(expr.span)
}
_ => {}
}
}
ast::ExprInlineAsm(..) => {
self.info().asm.push(expr.span)
}
ast::ExprPath(..) => {
match ty::resolve_expr(self.tcx, expr) {
def::DefStatic(_, true) => {
self.info().static_mut.push(expr.span)
}
_ => {}
}
}
ast::ExprCast(ref from, _) => {
self.check_ptr_cast(expr.span, &**from, expr);
}
_ => {}
}
}
visit::walk_expr(self, expr);
}
}
|
visit_block
|
identifier_name
|
visitor.rs
|
use rustc::middle::{ty, def};
use rustc::middle::ty::MethodCall;
use syntax::{ast, ast_util, ast_map};
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit;
use syntax::visit::Visitor;
use std::fmt;
use std::mem::replace;
use std::collections::BTreeMap;
fn type_is_unsafe_function(ty: ty::Ty) -> bool {
match ty.sty {
ty::ty_bare_fn(_, ref f) => f.unsafety == ast::Unsafety::Unsafe,
_ => false,
}
}
pub struct NodeInfo {
pub span: Span,
pub is_fn: bool,
pub compiler: bool,
pub ffi: Vec<Span>,
pub raw_deref: Vec<Span>,
pub static_mut: Vec<Span>,
pub unsafe_call: Vec<Span>,
pub transmute: Vec<Span>,
pub transmute_imm_to_mut: Vec<Span>,
// these are only picked up with written in unsafe blocks, but *const
// as *mut is legal anywhere.
pub cast_raw_ptr_const_to_mut: Vec<Span>,
pub asm: Vec<Span>,
}
impl NodeInfo {
fn new(span: Span, is_fn: bool, compiler: bool) -> NodeInfo {
NodeInfo {
span: span,
is_fn: is_fn,
compiler: compiler,
ffi: Vec::new(),
raw_deref: Vec::new(),
static_mut: Vec::new(),
unsafe_call: Vec::new(),
transmute: Vec::new(),
transmute_imm_to_mut: Vec::new(),
cast_raw_ptr_const_to_mut: Vec::new(),
asm: Vec::new()
}
}
}
impl fmt::Debug for NodeInfo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
macro_rules! p ( ($fmt: tt, $name: ident) => {
if!self.$name.is_empty() {
if!first {
try!(write!(fmt, ", "));
} else {
first = false
}
try!(write!(fmt, concat!("{} ", $fmt), self.$name.len()))
}
});
p!("asm", asm);
p!("deref", raw_deref);
p!("ffi", ffi);
p!("static mut", static_mut);
p!("transmute", transmute);
p!("transmute & to &mut", transmute_imm_to_mut);
p!("cast *const to *mut", cast_raw_ptr_const_to_mut);
p!("unsafe call", unsafe_call);
// silence dead assign warning
if first {}
Ok(())
}
}
pub struct UnsafeVisitor<'tcx, 'a: 'tcx> {
tcx: &'tcx ty::ctxt<'a>,
/// Whether we're in an unsafe context.
node_info: Option<(ast::NodeId, NodeInfo)>,
pub unsafes: BTreeMap<ast::NodeId, NodeInfo>,
}
impl<'tcx, 'a> UnsafeVisitor<'tcx, 'a> {
pub fn new(tcx: &'tcx ty::ctxt<'a>) -> UnsafeVisitor<'tcx, 'a> {
UnsafeVisitor {
tcx: tcx,
node_info: None,
unsafes: BTreeMap::new(),
}
}
pub fn check_crate(&mut self, krate: &ast::Crate) {
visit::walk_crate(self, krate)
}
fn info<'b>(&'b mut self) -> &'b mut NodeInfo {
&mut self.node_info.as_mut().unwrap().1
}
fn check_ptr_cast(&mut self, span: Span, from: &ast::Expr, to: &ast::Expr) -> bool {
let from_ty = ty::expr_ty(self.tcx, from);
let to_ty = ty::expr_ty(self.tcx, to);
match (&from_ty.sty, &to_ty.sty) {
(&ty::ty_rptr(_, ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_rptr(_, ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().transmute_imm_to_mut.push(span);
true
}
(&ty::ty_ptr(ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_ptr(ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().cast_raw_ptr_const_to_mut.push(span);
true
}
_ => {
false
}
}
}
}
impl<'tcx,'a,'b> Visitor<'a> for UnsafeVisitor<'tcx,'b> {
fn visit_fn(&mut self, fn_kind: visit::FnKind<'a>, fn_decl: &'a ast::FnDecl,
block: &ast::Block, span: Span, node_id: ast::NodeId) {
let (is_item_fn, is_unsafe_fn) = match fn_kind {
visit::FkItemFn(_, _, fn_style, _, _) =>
(true, fn_style == ast::Unsafety::Unsafe),
visit::FkMethod(_, sig, _) =>
(true, sig.unsafety == ast::Unsafety::Unsafe),
_ => (false, false),
};
let old_node_info = if is_unsafe_fn {
replace(&mut self.node_info, Some((node_id, NodeInfo::new(span, true, false))))
} else if is_item_fn {
replace(&mut self.node_info, None)
} else {
None
};
visit::walk_fn(self, fn_kind, fn_decl, block, span);
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
fn visit_block(&mut self, block: &'a ast::Block) {
let (old_node_info, inserted) = match block.rules {
ast::DefaultBlock => (None, false),
ast::UnsafeBlock(source) => {
let compiler = source == ast::CompilerGenerated;
if self.node_info.is_none() || compiler {
(replace(&mut self.node_info,
Some((block.id, NodeInfo::new(block.span, false, compiler)))),
true)
} else {
(None, false)
}
}
};
visit::walk_block(self, block);
if inserted {
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
}
fn visit_expr(&mut self, expr: &'a ast::Expr) {
if self.node_info.is_some() {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
let base_type = self.tcx.method_map.borrow()[&method_call].ty;
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
ast::ExprCall(ref base, ref args) => {
match (&base.node, &**args) {
(&ast::ExprPath(_, ref p), [ref arg])
// ew, but whatever.
if p.segments.last().unwrap().identifier.name ==
token::intern("transmute") => {
if!self.check_ptr_cast(expr.span, &**arg, expr) {
// not a */& -> *mut/&mut cast.
self.info().transmute.push(expr.span)
}
}
_ => {
let is_ffi = match self.tcx.def_map.borrow().get(&base.id) {
Some(&def::PathResolution { base_def: def::DefFn(did, _),.. }) => {
// cross-crate calls are always
// just unsafe calls.
ast_util::is_local(did) &&
match self.tcx.map.get(did.node) {
ast_map::NodeForeignItem(_) => true,
_ => false
}
}
_ => false
};
if is_ffi {
self.info().ffi.push(expr.span)
} else {
let base_type = ty::node_id_to_type(self.tcx, base.id);
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
}
}
}
ast::ExprUnary(ast::UnDeref, ref base) =>
|
ast::ExprInlineAsm(..) => {
self.info().asm.push(expr.span)
}
ast::ExprPath(..) => {
match ty::resolve_expr(self.tcx, expr) {
def::DefStatic(_, true) => {
self.info().static_mut.push(expr.span)
}
_ => {}
}
}
ast::ExprCast(ref from, _) => {
self.check_ptr_cast(expr.span, &**from, expr);
}
_ => {}
}
}
visit::walk_expr(self, expr);
}
}
|
{
let base_type = ty::node_id_to_type(self.tcx, base.id);
match base_type.sty {
ty::ty_ptr(_) => {
self.info().raw_deref.push(expr.span)
}
_ => {}
}
}
|
conditional_block
|
visitor.rs
|
use rustc::middle::{ty, def};
use rustc::middle::ty::MethodCall;
use syntax::{ast, ast_util, ast_map};
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit;
use syntax::visit::Visitor;
use std::fmt;
use std::mem::replace;
use std::collections::BTreeMap;
fn type_is_unsafe_function(ty: ty::Ty) -> bool {
match ty.sty {
ty::ty_bare_fn(_, ref f) => f.unsafety == ast::Unsafety::Unsafe,
_ => false,
}
}
pub struct NodeInfo {
pub span: Span,
pub is_fn: bool,
pub compiler: bool,
pub ffi: Vec<Span>,
pub raw_deref: Vec<Span>,
pub static_mut: Vec<Span>,
pub unsafe_call: Vec<Span>,
pub transmute: Vec<Span>,
pub transmute_imm_to_mut: Vec<Span>,
// these are only picked up with written in unsafe blocks, but *const
// as *mut is legal anywhere.
pub cast_raw_ptr_const_to_mut: Vec<Span>,
pub asm: Vec<Span>,
}
impl NodeInfo {
fn new(span: Span, is_fn: bool, compiler: bool) -> NodeInfo {
NodeInfo {
span: span,
is_fn: is_fn,
compiler: compiler,
ffi: Vec::new(),
raw_deref: Vec::new(),
static_mut: Vec::new(),
unsafe_call: Vec::new(),
transmute: Vec::new(),
transmute_imm_to_mut: Vec::new(),
cast_raw_ptr_const_to_mut: Vec::new(),
asm: Vec::new()
}
}
}
impl fmt::Debug for NodeInfo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
macro_rules! p ( ($fmt: tt, $name: ident) => {
if!self.$name.is_empty() {
if!first {
try!(write!(fmt, ", "));
} else {
first = false
}
try!(write!(fmt, concat!("{} ", $fmt), self.$name.len()))
}
});
p!("asm", asm);
p!("deref", raw_deref);
p!("ffi", ffi);
p!("static mut", static_mut);
p!("transmute", transmute);
p!("transmute & to &mut", transmute_imm_to_mut);
p!("cast *const to *mut", cast_raw_ptr_const_to_mut);
p!("unsafe call", unsafe_call);
// silence dead assign warning
if first {}
Ok(())
}
}
pub struct UnsafeVisitor<'tcx, 'a: 'tcx> {
tcx: &'tcx ty::ctxt<'a>,
/// Whether we're in an unsafe context.
node_info: Option<(ast::NodeId, NodeInfo)>,
pub unsafes: BTreeMap<ast::NodeId, NodeInfo>,
}
impl<'tcx, 'a> UnsafeVisitor<'tcx, 'a> {
pub fn new(tcx: &'tcx ty::ctxt<'a>) -> UnsafeVisitor<'tcx, 'a> {
UnsafeVisitor {
tcx: tcx,
node_info: None,
unsafes: BTreeMap::new(),
}
}
pub fn check_crate(&mut self, krate: &ast::Crate) {
visit::walk_crate(self, krate)
}
fn info<'b>(&'b mut self) -> &'b mut NodeInfo {
&mut self.node_info.as_mut().unwrap().1
}
fn check_ptr_cast(&mut self, span: Span, from: &ast::Expr, to: &ast::Expr) -> bool {
let from_ty = ty::expr_ty(self.tcx, from);
let to_ty = ty::expr_ty(self.tcx, to);
match (&from_ty.sty, &to_ty.sty) {
(&ty::ty_rptr(_, ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_rptr(_, ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().transmute_imm_to_mut.push(span);
true
}
(&ty::ty_ptr(ty::mt { mutbl: ast::MutImmutable,.. }),
&ty::ty_ptr(ty::mt { mutbl: ast::MutMutable,.. })) => {
self.info().cast_raw_ptr_const_to_mut.push(span);
true
}
_ => {
false
}
}
}
}
impl<'tcx,'a,'b> Visitor<'a> for UnsafeVisitor<'tcx,'b> {
fn visit_fn(&mut self, fn_kind: visit::FnKind<'a>, fn_decl: &'a ast::FnDecl,
block: &ast::Block, span: Span, node_id: ast::NodeId) {
let (is_item_fn, is_unsafe_fn) = match fn_kind {
visit::FkItemFn(_, _, fn_style, _, _) =>
(true, fn_style == ast::Unsafety::Unsafe),
visit::FkMethod(_, sig, _) =>
(true, sig.unsafety == ast::Unsafety::Unsafe),
_ => (false, false),
};
let old_node_info = if is_unsafe_fn {
replace(&mut self.node_info, Some((node_id, NodeInfo::new(span, true, false))))
} else if is_item_fn {
replace(&mut self.node_info, None)
} else {
None
};
visit::walk_fn(self, fn_kind, fn_decl, block, span);
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
fn visit_block(&mut self, block: &'a ast::Block) {
let (old_node_info, inserted) = match block.rules {
ast::DefaultBlock => (None, false),
ast::UnsafeBlock(source) => {
let compiler = source == ast::CompilerGenerated;
if self.node_info.is_none() || compiler {
(replace(&mut self.node_info,
Some((block.id, NodeInfo::new(block.span, false, compiler)))),
true)
} else {
(None, false)
}
}
};
visit::walk_block(self, block);
if inserted {
match replace(&mut self.node_info, old_node_info) {
Some((id, info)) => assert!(self.unsafes.insert(id, info).is_none()),
//Some((id, info)) => { self.unsafes.insert(id, info); }
None => {}
}
}
}
fn visit_expr(&mut self, expr: &'a ast::Expr) {
if self.node_info.is_some() {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
let base_type = self.tcx.method_map.borrow()[&method_call].ty;
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
ast::ExprCall(ref base, ref args) => {
match (&base.node, &**args) {
(&ast::ExprPath(_, ref p), [ref arg])
// ew, but whatever.
if p.segments.last().unwrap().identifier.name ==
token::intern("transmute") => {
if!self.check_ptr_cast(expr.span, &**arg, expr) {
// not a */& -> *mut/&mut cast.
self.info().transmute.push(expr.span)
}
}
_ => {
let is_ffi = match self.tcx.def_map.borrow().get(&base.id) {
Some(&def::PathResolution { base_def: def::DefFn(did, _),.. }) => {
// cross-crate calls are always
// just unsafe calls.
ast_util::is_local(did) &&
match self.tcx.map.get(did.node) {
ast_map::NodeForeignItem(_) => true,
_ => false
}
}
_ => false
};
if is_ffi {
self.info().ffi.push(expr.span)
} else {
let base_type = ty::node_id_to_type(self.tcx, base.id);
if type_is_unsafe_function(base_type) {
self.info().unsafe_call.push(expr.span)
}
}
}
}
|
match base_type.sty {
ty::ty_ptr(_) => {
self.info().raw_deref.push(expr.span)
}
_ => {}
}
}
ast::ExprInlineAsm(..) => {
self.info().asm.push(expr.span)
}
ast::ExprPath(..) => {
match ty::resolve_expr(self.tcx, expr) {
def::DefStatic(_, true) => {
self.info().static_mut.push(expr.span)
}
_ => {}
}
}
ast::ExprCast(ref from, _) => {
self.check_ptr_cast(expr.span, &**from, expr);
}
_ => {}
}
}
visit::walk_expr(self, expr);
}
}
|
}
ast::ExprUnary(ast::UnDeref, ref base) => {
let base_type = ty::node_id_to_type(self.tcx, base.id);
|
random_line_split
|
rfc3596.rs
|
//! Record data from [RFC 3596].
//!
//! This RFC defines the Aaaa record type.
//!
//! [RFC 3596]: https://tools.ietf.org/html/rfc3596
use std::fmt;
use std::net::Ipv6Addr;
use std::str::FromStr;
use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData,
Parser, ParseResult, RecordData};
use ::iana::Rtype;
use ::master::{Scanner, ScanResult};
//------------ Aaaa ---------------------------------------------------------
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Aaaa {
addr: Ipv6Addr
}
impl Aaaa {
pub fn
|
(addr: Ipv6Addr) -> Aaaa {
Aaaa { addr: addr }
}
pub fn addr(&self) -> Ipv6Addr { self.addr }
pub fn set_addr(&mut self, addr: Ipv6Addr) { self.addr = addr }
fn parse_always(parser: &mut Parser) -> ParseResult<Self> {
Ok(Aaaa::new(Ipv6Addr::new(try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()))))
}
pub fn scan<S: Scanner>(scanner: &mut S, _origin: Option<&DNameSlice>)
-> ScanResult<Self> {
scanner.scan_str_phrase(|slice| {
let addr = try!(Ipv6Addr::from_str(slice));
Ok(Aaaa::new(addr))
})
}
}
impl RecordData for Aaaa {
fn rtype(&self) -> Rtype { Rtype::Aaaa }
fn compose<C: AsMut<Composer>>(&self, mut target: C)
-> ComposeResult<()> {
for i in &self.addr.segments() {
try!(i.compose(target.as_mut()));
}
Ok(())
}
}
impl<'a> ParsedRecordData<'a> for Aaaa {
fn parse(rtype: Rtype, parser: &mut Parser) -> ParseResult<Option<Self>> {
if rtype == Rtype::Aaaa { Aaaa::parse_always(parser).map(Some) }
else { Ok(None) }
}
}
impl fmt::Display for Aaaa {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.addr.fmt(f)
}
}
|
new
|
identifier_name
|
rfc3596.rs
|
//! Record data from [RFC 3596].
//!
//! This RFC defines the Aaaa record type.
//!
//! [RFC 3596]: https://tools.ietf.org/html/rfc3596
use std::fmt;
use std::net::Ipv6Addr;
use std::str::FromStr;
use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData,
Parser, ParseResult, RecordData};
use ::iana::Rtype;
use ::master::{Scanner, ScanResult};
//------------ Aaaa ---------------------------------------------------------
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Aaaa {
addr: Ipv6Addr
}
impl Aaaa {
pub fn new(addr: Ipv6Addr) -> Aaaa {
Aaaa { addr: addr }
}
pub fn addr(&self) -> Ipv6Addr { self.addr }
pub fn set_addr(&mut self, addr: Ipv6Addr) { self.addr = addr }
fn parse_always(parser: &mut Parser) -> ParseResult<Self> {
Ok(Aaaa::new(Ipv6Addr::new(try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()))))
}
pub fn scan<S: Scanner>(scanner: &mut S, _origin: Option<&DNameSlice>)
-> ScanResult<Self> {
|
}
impl RecordData for Aaaa {
fn rtype(&self) -> Rtype { Rtype::Aaaa }
fn compose<C: AsMut<Composer>>(&self, mut target: C)
-> ComposeResult<()> {
for i in &self.addr.segments() {
try!(i.compose(target.as_mut()));
}
Ok(())
}
}
impl<'a> ParsedRecordData<'a> for Aaaa {
fn parse(rtype: Rtype, parser: &mut Parser) -> ParseResult<Option<Self>> {
if rtype == Rtype::Aaaa { Aaaa::parse_always(parser).map(Some) }
else { Ok(None) }
}
}
impl fmt::Display for Aaaa {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.addr.fmt(f)
}
}
|
scanner.scan_str_phrase(|slice| {
let addr = try!(Ipv6Addr::from_str(slice));
Ok(Aaaa::new(addr))
})
}
|
random_line_split
|
rfc3596.rs
|
//! Record data from [RFC 3596].
//!
//! This RFC defines the Aaaa record type.
//!
//! [RFC 3596]: https://tools.ietf.org/html/rfc3596
use std::fmt;
use std::net::Ipv6Addr;
use std::str::FromStr;
use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData,
Parser, ParseResult, RecordData};
use ::iana::Rtype;
use ::master::{Scanner, ScanResult};
//------------ Aaaa ---------------------------------------------------------
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Aaaa {
addr: Ipv6Addr
}
impl Aaaa {
pub fn new(addr: Ipv6Addr) -> Aaaa {
Aaaa { addr: addr }
}
pub fn addr(&self) -> Ipv6Addr { self.addr }
pub fn set_addr(&mut self, addr: Ipv6Addr) { self.addr = addr }
fn parse_always(parser: &mut Parser) -> ParseResult<Self> {
Ok(Aaaa::new(Ipv6Addr::new(try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()),
try!(parser.parse_u16()))))
}
pub fn scan<S: Scanner>(scanner: &mut S, _origin: Option<&DNameSlice>)
-> ScanResult<Self> {
scanner.scan_str_phrase(|slice| {
let addr = try!(Ipv6Addr::from_str(slice));
Ok(Aaaa::new(addr))
})
}
}
impl RecordData for Aaaa {
fn rtype(&self) -> Rtype { Rtype::Aaaa }
fn compose<C: AsMut<Composer>>(&self, mut target: C)
-> ComposeResult<()> {
for i in &self.addr.segments() {
try!(i.compose(target.as_mut()));
}
Ok(())
}
}
impl<'a> ParsedRecordData<'a> for Aaaa {
fn parse(rtype: Rtype, parser: &mut Parser) -> ParseResult<Option<Self>> {
if rtype == Rtype::Aaaa
|
else { Ok(None) }
}
}
impl fmt::Display for Aaaa {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.addr.fmt(f)
}
}
|
{ Aaaa::parse_always(parser).map(Some) }
|
conditional_block
|
mock.rs
|
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Mock random number generator
use rand_core::{impls, Error, RngCore};
#[cfg(feature = "serde1")]
use serde::{Serialize, Deserialize};
/// A simple implementation of `RngCore` for testing purposes.
///
/// This generates an arithmetic sequence (i.e. adds a constant each step)
/// over a `u64` number, using wrapping arithmetic. If the increment is 0
/// the generator yields a constant.
///
/// ```
/// use rand::Rng;
/// use rand::rngs::mock::StepRng;
///
/// let mut my_rng = StepRng::new(2, 1);
/// let sample: [u64; 3] = my_rng.gen();
/// assert_eq!(sample, [2, 3, 4]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct StepRng {
v: u64,
a: u64,
}
impl StepRng {
/// Create a `StepRng`, yielding an arithmetic sequence starting with
/// `initial` and incremented by `increment` each time.
pub fn new(initial: u64, increment: u64) -> Self {
StepRng {
v: initial,
a: increment,
}
}
}
impl RngCore for StepRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
let result = self.v;
self.v = self.v.wrapping_add(self.a);
result
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8])
|
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "serde1")]
fn test_serialization_step_rng() {
use super::StepRng;
let some_rng = StepRng::new(42, 7);
let de_some_rng: StepRng =
bincode::deserialize(&bincode::serialize(&some_rng).unwrap()).unwrap();
assert_eq!(some_rng.v, de_some_rng.v);
assert_eq!(some_rng.a, de_some_rng.a);
}
}
|
{
impls::fill_bytes_via_next(self, dest);
}
|
identifier_body
|
mock.rs
|
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Mock random number generator
use rand_core::{impls, Error, RngCore};
#[cfg(feature = "serde1")]
use serde::{Serialize, Deserialize};
/// A simple implementation of `RngCore` for testing purposes.
///
/// This generates an arithmetic sequence (i.e. adds a constant each step)
/// over a `u64` number, using wrapping arithmetic. If the increment is 0
/// the generator yields a constant.
///
/// ```
/// use rand::Rng;
/// use rand::rngs::mock::StepRng;
///
/// let mut my_rng = StepRng::new(2, 1);
/// let sample: [u64; 3] = my_rng.gen();
/// assert_eq!(sample, [2, 3, 4]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct StepRng {
v: u64,
a: u64,
}
impl StepRng {
/// Create a `StepRng`, yielding an arithmetic sequence starting with
/// `initial` and incremented by `increment` each time.
pub fn new(initial: u64, increment: u64) -> Self {
StepRng {
v: initial,
a: increment,
}
}
}
impl RngCore for StepRng {
#[inline]
fn
|
(&mut self) -> u32 {
self.next_u64() as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
let result = self.v;
self.v = self.v.wrapping_add(self.a);
result
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
impls::fill_bytes_via_next(self, dest);
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "serde1")]
fn test_serialization_step_rng() {
use super::StepRng;
let some_rng = StepRng::new(42, 7);
let de_some_rng: StepRng =
bincode::deserialize(&bincode::serialize(&some_rng).unwrap()).unwrap();
assert_eq!(some_rng.v, de_some_rng.v);
assert_eq!(some_rng.a, de_some_rng.a);
}
}
|
next_u32
|
identifier_name
|
mock.rs
|
// Copyright 2018 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Mock random number generator
use rand_core::{impls, Error, RngCore};
#[cfg(feature = "serde1")]
use serde::{Serialize, Deserialize};
/// A simple implementation of `RngCore` for testing purposes.
///
/// This generates an arithmetic sequence (i.e. adds a constant each step)
/// over a `u64` number, using wrapping arithmetic. If the increment is 0
/// the generator yields a constant.
///
/// ```
/// use rand::Rng;
/// use rand::rngs::mock::StepRng;
///
/// let mut my_rng = StepRng::new(2, 1);
/// let sample: [u64; 3] = my_rng.gen();
/// assert_eq!(sample, [2, 3, 4]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct StepRng {
v: u64,
a: u64,
}
impl StepRng {
/// Create a `StepRng`, yielding an arithmetic sequence starting with
/// `initial` and incremented by `increment` each time.
pub fn new(initial: u64, increment: u64) -> Self {
StepRng {
v: initial,
a: increment,
}
}
}
impl RngCore for StepRng {
#[inline]
fn next_u32(&mut self) -> u32 {
self.next_u64() as u32
}
#[inline]
fn next_u64(&mut self) -> u64 {
let result = self.v;
self.v = self.v.wrapping_add(self.a);
result
}
#[inline]
fn fill_bytes(&mut self, dest: &mut [u8]) {
impls::fill_bytes_via_next(self, dest);
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
self.fill_bytes(dest);
|
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "serde1")]
fn test_serialization_step_rng() {
use super::StepRng;
let some_rng = StepRng::new(42, 7);
let de_some_rng: StepRng =
bincode::deserialize(&bincode::serialize(&some_rng).unwrap()).unwrap();
assert_eq!(some_rng.v, de_some_rng.v);
assert_eq!(some_rng.a, de_some_rng.a);
}
}
|
Ok(())
}
}
|
random_line_split
|
vec-slices.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32: FIXME #13256
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print empty.length
// check:$1 = 0
// debugger:print singleton.length
// check:$2 = 1
// debugger:print *((int64_t[1]*)(singleton.data_ptr))
// check:$3 = {1}
// debugger:print multiple.length
// check:$4 = 4
// debugger:print *((int64_t[4]*)(multiple.data_ptr))
// check:$5 = {2, 3, 4, 5}
// debugger:print slice_of_slice.length
|
// debugger:print padded_tuple.length
// check:$8 = 2
// debugger:print padded_tuple.data_ptr[0]
// check:$9 = {6, 7}
// debugger:print padded_tuple.data_ptr[1]
// check:$10 = {8, 9}
// debugger:print padded_struct.length
// check:$11 = 2
// debugger:print padded_struct.data_ptr[0]
// check:$12 = {x = 10, y = 11, z = 12}
// debugger:print padded_struct.data_ptr[1]
// check:$13 = {x = 13, y = 14, z = 15}
// debugger:print'vec-slices::MUT_VECT_SLICE'.length
// check:$14 = 2
// debugger:print *((int64_t[2]*)('vec-slices::MUT_VECT_SLICE'.data_ptr))
// check:$15 = {64, 65}
#![allow(unused_variable)]
struct AStruct {
x: i16,
y: i32,
z: i16
}
static VECT_SLICE: &'static [i64] = &[64, 65];
static mut MUT_VECT_SLICE: &'static [i64] = &[32];
fn main() {
let empty: &[i64] = &[];
let singleton: &[i64] = &[1];
let multiple: &[i64] = &[2, 3, 4, 5];
let slice_of_slice = multiple.slice(1,3);
let padded_tuple: &[(i32, i16)] = &[(6, 7), (8, 9)];
let padded_struct: &[AStruct] = &[
AStruct { x: 10, y: 11, z: 12 },
AStruct { x: 13, y: 14, z: 15 }
];
unsafe {
MUT_VECT_SLICE = VECT_SLICE;
}
zzz();
}
fn zzz() {()}
|
// check:$6 = 2
// debugger:print *((int64_t[2]*)(slice_of_slice.data_ptr))
// check:$7 = {3, 4}
|
random_line_split
|
vec-slices.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32: FIXME #13256
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print empty.length
// check:$1 = 0
// debugger:print singleton.length
// check:$2 = 1
// debugger:print *((int64_t[1]*)(singleton.data_ptr))
// check:$3 = {1}
// debugger:print multiple.length
// check:$4 = 4
// debugger:print *((int64_t[4]*)(multiple.data_ptr))
// check:$5 = {2, 3, 4, 5}
// debugger:print slice_of_slice.length
// check:$6 = 2
// debugger:print *((int64_t[2]*)(slice_of_slice.data_ptr))
// check:$7 = {3, 4}
// debugger:print padded_tuple.length
// check:$8 = 2
// debugger:print padded_tuple.data_ptr[0]
// check:$9 = {6, 7}
// debugger:print padded_tuple.data_ptr[1]
// check:$10 = {8, 9}
// debugger:print padded_struct.length
// check:$11 = 2
// debugger:print padded_struct.data_ptr[0]
// check:$12 = {x = 10, y = 11, z = 12}
// debugger:print padded_struct.data_ptr[1]
// check:$13 = {x = 13, y = 14, z = 15}
// debugger:print'vec-slices::MUT_VECT_SLICE'.length
// check:$14 = 2
// debugger:print *((int64_t[2]*)('vec-slices::MUT_VECT_SLICE'.data_ptr))
// check:$15 = {64, 65}
#![allow(unused_variable)]
struct
|
{
x: i16,
y: i32,
z: i16
}
static VECT_SLICE: &'static [i64] = &[64, 65];
static mut MUT_VECT_SLICE: &'static [i64] = &[32];
fn main() {
let empty: &[i64] = &[];
let singleton: &[i64] = &[1];
let multiple: &[i64] = &[2, 3, 4, 5];
let slice_of_slice = multiple.slice(1,3);
let padded_tuple: &[(i32, i16)] = &[(6, 7), (8, 9)];
let padded_struct: &[AStruct] = &[
AStruct { x: 10, y: 11, z: 12 },
AStruct { x: 13, y: 14, z: 15 }
];
unsafe {
MUT_VECT_SLICE = VECT_SLICE;
}
zzz();
}
fn zzz() {()}
|
AStruct
|
identifier_name
|
vec-slices.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32: FIXME #13256
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print empty.length
// check:$1 = 0
// debugger:print singleton.length
// check:$2 = 1
// debugger:print *((int64_t[1]*)(singleton.data_ptr))
// check:$3 = {1}
// debugger:print multiple.length
// check:$4 = 4
// debugger:print *((int64_t[4]*)(multiple.data_ptr))
// check:$5 = {2, 3, 4, 5}
// debugger:print slice_of_slice.length
// check:$6 = 2
// debugger:print *((int64_t[2]*)(slice_of_slice.data_ptr))
// check:$7 = {3, 4}
// debugger:print padded_tuple.length
// check:$8 = 2
// debugger:print padded_tuple.data_ptr[0]
// check:$9 = {6, 7}
// debugger:print padded_tuple.data_ptr[1]
// check:$10 = {8, 9}
// debugger:print padded_struct.length
// check:$11 = 2
// debugger:print padded_struct.data_ptr[0]
// check:$12 = {x = 10, y = 11, z = 12}
// debugger:print padded_struct.data_ptr[1]
// check:$13 = {x = 13, y = 14, z = 15}
// debugger:print'vec-slices::MUT_VECT_SLICE'.length
// check:$14 = 2
// debugger:print *((int64_t[2]*)('vec-slices::MUT_VECT_SLICE'.data_ptr))
// check:$15 = {64, 65}
#![allow(unused_variable)]
struct AStruct {
x: i16,
y: i32,
z: i16
}
static VECT_SLICE: &'static [i64] = &[64, 65];
static mut MUT_VECT_SLICE: &'static [i64] = &[32];
fn main() {
let empty: &[i64] = &[];
let singleton: &[i64] = &[1];
let multiple: &[i64] = &[2, 3, 4, 5];
let slice_of_slice = multiple.slice(1,3);
let padded_tuple: &[(i32, i16)] = &[(6, 7), (8, 9)];
let padded_struct: &[AStruct] = &[
AStruct { x: 10, y: 11, z: 12 },
AStruct { x: 13, y: 14, z: 15 }
];
unsafe {
MUT_VECT_SLICE = VECT_SLICE;
}
zzz();
}
fn zzz()
|
{()}
|
identifier_body
|
|
issue-26322.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! columnline {
() => (
(column!(), line!())
)
}
macro_rules! indirectcolumnline {
() => (
(||{ columnline!() })()
)
}
fn main() {
let closure = || {
columnline!()
};
let iflet = if let Some(_) = Some(0) {
columnline!()
} else
|
;
let cl = columnline!();
assert_eq!(closure(), (8, 25));
assert_eq!(iflet, (8, 28));
assert_eq!(cl, (13, 30));
let indirect = indirectcolumnline!();
assert_eq!(indirect, (19, 34));
}
|
{ (0, 0) }
|
conditional_block
|
issue-26322.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! columnline {
() => (
(column!(), line!())
)
}
macro_rules! indirectcolumnline {
() => (
(||{ columnline!() })()
)
}
fn
|
() {
let closure = || {
columnline!()
};
let iflet = if let Some(_) = Some(0) {
columnline!()
} else { (0, 0) };
let cl = columnline!();
assert_eq!(closure(), (8, 25));
assert_eq!(iflet, (8, 28));
assert_eq!(cl, (13, 30));
let indirect = indirectcolumnline!();
assert_eq!(indirect, (19, 34));
}
|
main
|
identifier_name
|
issue-26322.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! columnline {
() => (
(column!(), line!())
)
}
macro_rules! indirectcolumnline {
() => (
(||{ columnline!() })()
)
}
fn main() {
let closure = || {
columnline!()
};
let iflet = if let Some(_) = Some(0) {
|
assert_eq!(cl, (13, 30));
let indirect = indirectcolumnline!();
assert_eq!(indirect, (19, 34));
}
|
columnline!()
} else { (0, 0) };
let cl = columnline!();
assert_eq!(closure(), (8, 25));
assert_eq!(iflet, (8, 28));
|
random_line_split
|
issue-26322.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! columnline {
() => (
(column!(), line!())
)
}
macro_rules! indirectcolumnline {
() => (
(||{ columnline!() })()
)
}
fn main()
|
{
let closure = || {
columnline!()
};
let iflet = if let Some(_) = Some(0) {
columnline!()
} else { (0, 0) };
let cl = columnline!();
assert_eq!(closure(), (8, 25));
assert_eq!(iflet, (8, 28));
assert_eq!(cl, (13, 30));
let indirect = indirectcolumnline!();
assert_eq!(indirect, (19, 34));
}
|
identifier_body
|
|
packer-test.rs
|
extern crate image;
extern crate texture_packer;
use std::path::Path;
use std::fs::File;
use texture_packer::texture::Texture;
use texture_packer::{ TexturePacker, TexturePackerConfig };
use texture_packer::importer::ImageImporter;
use texture_packer::exporter::ImageExporter;
|
fn main() {
let mut config = TexturePackerConfig::default();
config.max_width = MAX_IMAGE_WIDTH;
config.max_height = MAX_IMAGE_HEIGHT;
config.allow_rotation = false;
config.texture_outlines = true;
config.border_padding = 2;
let ref mut texture_packer = TexturePacker::new_skyline(config);
for i in 1.. 11 {
let file = format!("{}.png", i);
let ref path = ["./examples/assets/", &file[..]].concat();
let ref path = Path::new(path);
let texture = ImageImporter::import_from_file(path).unwrap();
texture_packer.pack_own(file, texture);
}
let image = ImageExporter::export(texture_packer).unwrap();
let path = "./examples/output/skyline-packer-output.png";
let ref path = Path::new(path);
let ref mut file = File::create(path).unwrap();
println!("{} x {}", texture_packer.width(), texture_packer.height());
image.save(file, image::PNG).unwrap();
}
|
const MAX_IMAGE_WIDTH: u32 = 400;
const MAX_IMAGE_HEIGHT: u32 = 400;
|
random_line_split
|
packer-test.rs
|
extern crate image;
extern crate texture_packer;
use std::path::Path;
use std::fs::File;
use texture_packer::texture::Texture;
use texture_packer::{ TexturePacker, TexturePackerConfig };
use texture_packer::importer::ImageImporter;
use texture_packer::exporter::ImageExporter;
const MAX_IMAGE_WIDTH: u32 = 400;
const MAX_IMAGE_HEIGHT: u32 = 400;
fn main()
|
let path = "./examples/output/skyline-packer-output.png";
let ref path = Path::new(path);
let ref mut file = File::create(path).unwrap();
println!("{} x {}", texture_packer.width(), texture_packer.height());
image.save(file, image::PNG).unwrap();
}
|
{
let mut config = TexturePackerConfig::default();
config.max_width = MAX_IMAGE_WIDTH;
config.max_height = MAX_IMAGE_HEIGHT;
config.allow_rotation = false;
config.texture_outlines = true;
config.border_padding = 2;
let ref mut texture_packer = TexturePacker::new_skyline(config);
for i in 1 .. 11 {
let file = format!("{}.png", i);
let ref path = ["./examples/assets/", &file[..]].concat();
let ref path = Path::new(path);
let texture = ImageImporter::import_from_file(path).unwrap();
texture_packer.pack_own(file, texture);
}
let image = ImageExporter::export(texture_packer).unwrap();
|
identifier_body
|
packer-test.rs
|
extern crate image;
extern crate texture_packer;
use std::path::Path;
use std::fs::File;
use texture_packer::texture::Texture;
use texture_packer::{ TexturePacker, TexturePackerConfig };
use texture_packer::importer::ImageImporter;
use texture_packer::exporter::ImageExporter;
const MAX_IMAGE_WIDTH: u32 = 400;
const MAX_IMAGE_HEIGHT: u32 = 400;
fn
|
() {
let mut config = TexturePackerConfig::default();
config.max_width = MAX_IMAGE_WIDTH;
config.max_height = MAX_IMAGE_HEIGHT;
config.allow_rotation = false;
config.texture_outlines = true;
config.border_padding = 2;
let ref mut texture_packer = TexturePacker::new_skyline(config);
for i in 1.. 11 {
let file = format!("{}.png", i);
let ref path = ["./examples/assets/", &file[..]].concat();
let ref path = Path::new(path);
let texture = ImageImporter::import_from_file(path).unwrap();
texture_packer.pack_own(file, texture);
}
let image = ImageExporter::export(texture_packer).unwrap();
let path = "./examples/output/skyline-packer-output.png";
let ref path = Path::new(path);
let ref mut file = File::create(path).unwrap();
println!("{} x {}", texture_packer.width(), texture_packer.height());
image.save(file, image::PNG).unwrap();
}
|
main
|
identifier_name
|
bubble_sort.rs
|
//! Module contains pure implementations of bubble sort algorithm.
//!
//! * `sort` - is non distructive function (does not affects on input sequence)
//! * `mut_sort` - function with side effects (modify input sequence)
//!
//! It's better to use first one in functional style, second - in OOP-style
/// Pure implementation of Bubble sort algorithm
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
/// assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
/// ```
pub fn
|
<T: Ord + Clone>(list: &[T]) -> Vec<T> {
let mut sorted_list = list.clone().to_vec();
let length = sorted_list.len();
for i in 0..length {
let mut swapped = false;
for j in 0..length - i - 1 {
if sorted_list[j] > sorted_list[j + 1] {
sorted_list.swap(j, j + 1);
swapped = true;
}
}
if swapped == false {
break;
}
}
return sorted_list;
}
/// Pure implementation of bubble sort algorithm. Side-effects version
/// Modifies input sequense
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::mut_sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
/// ```
pub fn mut_sort<T: Ord>(list: &mut [T]) {
for n in (0..(list.len() as isize + 1)).rev() {
for m in 1..(n as usize) {
if list[m] < list[m - 1] {
list.swap(m, m - 1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::utils::is_sorted;
#[test]
fn sort_numbers() {
let empty_vec: Vec<i32> = Vec::new();
assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
assert!(is_sorted(&sort(&empty_vec)));
assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
}
#[test]
fn sort_chars() {
assert!(is_sorted(&sort(&['a', 'r', 'b'])))
}
#[test]
fn mut_sort_numbers() {
let mut test_vector = vec![0, 5, 2, 3, 2];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
let mut test_vector: Vec<i32> = Vec::new();
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
#[test]
fn mut_sort_chars() {
let mut test_vector = vec!['a', 'r', 'b'];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
}
|
sort
|
identifier_name
|
bubble_sort.rs
|
//! Module contains pure implementations of bubble sort algorithm.
//!
//! * `sort` - is non distructive function (does not affects on input sequence)
//! * `mut_sort` - function with side effects (modify input sequence)
//!
//! It's better to use first one in functional style, second - in OOP-style
/// Pure implementation of Bubble sort algorithm
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
/// assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
/// ```
pub fn sort<T: Ord + Clone>(list: &[T]) -> Vec<T> {
let mut sorted_list = list.clone().to_vec();
let length = sorted_list.len();
for i in 0..length {
let mut swapped = false;
for j in 0..length - i - 1 {
if sorted_list[j] > sorted_list[j + 1] {
sorted_list.swap(j, j + 1);
swapped = true;
}
}
if swapped == false {
break;
}
}
return sorted_list;
}
/// Pure implementation of bubble sort algorithm. Side-effects version
/// Modifies input sequense
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::mut_sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
/// ```
pub fn mut_sort<T: Ord>(list: &mut [T]) {
for n in (0..(list.len() as isize + 1)).rev() {
for m in 1..(n as usize) {
if list[m] < list[m - 1] {
list.swap(m, m - 1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::utils::is_sorted;
#[test]
fn sort_numbers() {
let empty_vec: Vec<i32> = Vec::new();
assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
assert!(is_sorted(&sort(&empty_vec)));
assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
}
#[test]
fn sort_chars() {
assert!(is_sorted(&sort(&['a', 'r', 'b'])))
}
#[test]
fn mut_sort_numbers() {
let mut test_vector = vec![0, 5, 2, 3, 2];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
let mut test_vector: Vec<i32> = Vec::new();
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
|
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
}
|
#[test]
fn mut_sort_chars() {
let mut test_vector = vec!['a', 'r', 'b'];
|
random_line_split
|
bubble_sort.rs
|
//! Module contains pure implementations of bubble sort algorithm.
//!
//! * `sort` - is non distructive function (does not affects on input sequence)
//! * `mut_sort` - function with side effects (modify input sequence)
//!
//! It's better to use first one in functional style, second - in OOP-style
/// Pure implementation of Bubble sort algorithm
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
/// assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
/// ```
pub fn sort<T: Ord + Clone>(list: &[T]) -> Vec<T> {
let mut sorted_list = list.clone().to_vec();
let length = sorted_list.len();
for i in 0..length {
let mut swapped = false;
for j in 0..length - i - 1 {
if sorted_list[j] > sorted_list[j + 1]
|
}
if swapped == false {
break;
}
}
return sorted_list;
}
/// Pure implementation of bubble sort algorithm. Side-effects version
/// Modifies input sequense
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::mut_sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
/// ```
pub fn mut_sort<T: Ord>(list: &mut [T]) {
for n in (0..(list.len() as isize + 1)).rev() {
for m in 1..(n as usize) {
if list[m] < list[m - 1] {
list.swap(m, m - 1);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::utils::is_sorted;
#[test]
fn sort_numbers() {
let empty_vec: Vec<i32> = Vec::new();
assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
assert!(is_sorted(&sort(&empty_vec)));
assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
}
#[test]
fn sort_chars() {
assert!(is_sorted(&sort(&['a', 'r', 'b'])))
}
#[test]
fn mut_sort_numbers() {
let mut test_vector = vec![0, 5, 2, 3, 2];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
let mut test_vector: Vec<i32> = Vec::new();
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
#[test]
fn mut_sort_chars() {
let mut test_vector = vec!['a', 'r', 'b'];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
}
|
{
sorted_list.swap(j, j + 1);
swapped = true;
}
|
conditional_block
|
bubble_sort.rs
|
//! Module contains pure implementations of bubble sort algorithm.
//!
//! * `sort` - is non distructive function (does not affects on input sequence)
//! * `mut_sort` - function with side effects (modify input sequence)
//!
//! It's better to use first one in functional style, second - in OOP-style
/// Pure implementation of Bubble sort algorithm
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
/// assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
/// ```
pub fn sort<T: Ord + Clone>(list: &[T]) -> Vec<T> {
let mut sorted_list = list.clone().to_vec();
let length = sorted_list.len();
for i in 0..length {
let mut swapped = false;
for j in 0..length - i - 1 {
if sorted_list[j] > sorted_list[j + 1] {
sorted_list.swap(j, j + 1);
swapped = true;
}
}
if swapped == false {
break;
}
}
return sorted_list;
}
/// Pure implementation of bubble sort algorithm. Side-effects version
/// Modifies input sequense
///
/// # Examples
///
/// ```
/// use algorithms::sorts::bubble_sort::mut_sort;
/// use algorithms::sorts::utils::is_sorted;
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
///
/// let mut test_sequence = [0, 5, 3, 2, 2];
/// mut_sort(&mut test_sequence);
/// assert!(is_sorted(&test_sequence));
/// ```
pub fn mut_sort<T: Ord>(list: &mut [T])
|
#[cfg(test)]
mod tests {
use super::*;
use super::super::utils::is_sorted;
#[test]
fn sort_numbers() {
let empty_vec: Vec<i32> = Vec::new();
assert!(is_sorted(&sort(&[0, 5, 3, 2, 2])));
assert!(is_sorted(&sort(&empty_vec)));
assert!(is_sorted(&sort(&[-1, -5, -10, 105])));
}
#[test]
fn sort_chars() {
assert!(is_sorted(&sort(&['a', 'r', 'b'])))
}
#[test]
fn mut_sort_numbers() {
let mut test_vector = vec![0, 5, 2, 3, 2];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
let mut test_vector: Vec<i32> = Vec::new();
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
#[test]
fn mut_sort_chars() {
let mut test_vector = vec!['a', 'r', 'b'];
mut_sort(&mut test_vector);
assert!(is_sorted(&test_vector));
}
}
|
{
for n in (0..(list.len() as isize + 1)).rev() {
for m in 1..(n as usize) {
if list[m] < list[m - 1] {
list.swap(m, m - 1);
}
}
}
}
|
identifier_body
|
spacing_after.rs
|
extern crate std as ruststd;
use core::hash::{self, Hash};
use core::intrinsics::{arith_offset, assume};
use core::iter::FromIterator;
use core::mem;
use core::ops::{Index, IndexMut};
const CAPACITY: usize = 2 * B - 1;
fn foo(a: i32, b: str, c: i32, d: f32) -> () {
let mut e: &'static [str] = "abcd";
let mut f: &[str] = "cdef";
bar();
let array: [i32; 45] = [0; 45];
let f: fn(i32, u64) -> i32;
let f2: fn(i32) -> i32;
let unit: () = ();
let foo = 2 + 2;
let moo = 2 * 2;
let meh = 2 * 2 + 3 * 3;
else_block.as_ref().map(|e| &**e);
match self.node {
ast::ExprKind::Field(..) |
ast::ExprKind::MethodCall(..) => rewrite_chain(self, context, width, offset)
};
let f: fn(&_, _) -> _ = unimplemented!();
let f = unimplemented! {};
{
foo();
}
for &(sample, radiance) in samples.iter() {}
map(|&s| moo());
match x {
S { foo } => 92
}
}
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}
enum Foo {
Bar = 123,
Baz = 0,
}
pub struct Vec<T> {
buf: RawVec<T>,
len: usize,
}
impl<T> Vec<T> {
pub fn new() -> Vec<T> {
Vec {
buf: RawVec::new(),
len: 0,
}
}
pub fn with_capacity(capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::with_capacity(capacity),
len: 0,
}
}
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::from_raw_parts(ptr, capacity),
len: length,
}
}
pub fn capacity(&self) -> usize {
self.buf.cap()
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(self.len, additional);
}
pub fn into_boxed_slice(mut self) -> Box<[T]> {
unsafe {
self.shrink_to_fit();
let buf = ptr::read(&self.buf);
mem::forget(self);
buf.into_box()
}
}
pub fn truncate(&mut self, len: usize) {
unsafe {
while len < self.len {
self.len -= 1;
let len = self.len;
ptr::drop_in_place(self.get_unchecked_mut(len));
}
}
}
pub fn as_slice(&self) -> &[T] {
self
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
&mut self[..]
}
pub unsafe fn set_len(&mut self, len: usize) {
self.len = len;
}
pub fn remove(&mut self, index: usize) -> T {
let len = self.len();
assert!(index < len);
unsafe {
let ret;
{
let ptr = self.as_mut_ptr().offset(index as isize);
ret = ptr::read(ptr);
ptr::copy(ptr.offset(1), ptr, len - index - 1);
}
self.set_len(len - 1);
ret
}
}
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
if!f(&v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
let len = self.len();
let start = *range.start().unwrap_or(&0);
let end = *range.end().unwrap_or(&len);
assert!(start <= end);
assert!(end <= len);
}
}
impl<T: Clone> Vec<T> {
pub fn extend_from_slice(&mut self, other: &[T]) {
self.reserve(other.len());
for i in 0..other.len() {
let len = self.len();
unsafe {
ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
self.set_len(len + 1);
}
}
}
}
impl<T: PartialEq> Vec<T> {
pub fn dedup(&mut self) {
unsafe {
let ln = self.len();
if ln <= 1 {
return;
}
let p = self.as_mut_ptr();
let mut r: usize = 1;
let mut w: usize = 1;
while r < ln {
let p_r = p.offset(r as isize);
let p_wm1 = p.offset((w - 1) as isize);
if *p_r!= *p_wm1 {
if r!= w {
let p_w = p_wm1.offset(1);
mem::swap(&mut *p_r, &mut *p_w);
|
w += 1;
}
r += 1;
}
self.truncate(w);
}
}
}
pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {}
impl<T: Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
<[T]>::to_vec(&**self)
}
fn clone(&self) -> Vec<T> {
::slice::to_vec(&**self)
}
fn clone_from(&mut self, other: &Vec<T>) {
self.truncate(other.len());
let len = self.len();
self.clone_from_slice(&other[..len]);
self.extend_from_slice(&other[len..]);
}
}
impl<T: Hash> Hash for Vec<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&**self, state)
}
}
impl<T> Index<usize> for Vec<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
&(**self)[index]
}
}
impl<T> IndexMut<usize> for Vec<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
&mut (**self)[index]
}
}
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Vec<T> {
let mut iterator = iter.into_iter();
let mut vector = match iterator.next() {
None => return Vec::new(),
Some(element) => {
let (lower, _) = iterator.size_hint();
//...
}
};
//...
}
}
impl<T> IntoIterator for Vec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(mut self) -> IntoIter<T> {
unsafe {
let ptr = self.as_mut_ptr();
assume(!ptr.is_null());
let begin = ptr as *const T;
let end = if mem::size_of::<T>() == 0 {
arith_offset(ptr as *const i8, self.len() as isize) as *const T
} else {
ptr.offset(self.len() as isize) as *const T
};
let buf = ptr::read(&self.buf);
mem::forget(self);
IntoIter {
_buf: buf,
ptr: begin,
end: end,
}
}
}
}
impl<'a, T> IntoIterator for &'a Vec<T> {
type Item = &'a T;
}
impl<T> Iterator for IntoIter<T> {
fn size_hint(&self) -> (usize, Option<usize>) {
let diff = (self.end as usize) - (self.ptr as usize);
let size = mem::size_of::<T>();
let exact = diff / (if size == 0 { 1 } else { size });
(exact, Some(exact))
}
}
impl<'a, T> Iterator for Drain<'a, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
}
}
trait Extend<A> {
fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
}
impl<R, F: FnOnce() -> R> FnOnce<()> for AssertRecoverSafe<F> {
extern "rust-call" fn call_once(self, _args: ()) -> R {
(self.0)()
}
}
fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
let mut result = None;
unsafe {
let result = &mut result;
unwind::try(move || *result = Some(f()))?
}
Ok(result.unwrap())
}
fn propagate(payload: Box<Any + Send>) ->! {}
impl<K, V> Root<K, V> {
pub fn as_ref(&self) -> NodeRef<marker::Immut, K, V, marker::LeafOrInternal> {
NodeRef {
root: self as *const _ as *mut _,
}
}
}
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
mod math {
type Complex = (f64, f64);
fn sin(f: f64) -> f64 {
/*... */
}
}
fn foo(&&(x, _): &&(i32, i32)) {}
|
}
|
random_line_split
|
spacing_after.rs
|
extern crate std as ruststd;
use core::hash::{self, Hash};
use core::intrinsics::{arith_offset, assume};
use core::iter::FromIterator;
use core::mem;
use core::ops::{Index, IndexMut};
const CAPACITY: usize = 2 * B - 1;
fn foo(a: i32, b: str, c: i32, d: f32) -> () {
let mut e: &'static [str] = "abcd";
let mut f: &[str] = "cdef";
bar();
let array: [i32; 45] = [0; 45];
let f: fn(i32, u64) -> i32;
let f2: fn(i32) -> i32;
let unit: () = ();
let foo = 2 + 2;
let moo = 2 * 2;
let meh = 2 * 2 + 3 * 3;
else_block.as_ref().map(|e| &**e);
match self.node {
ast::ExprKind::Field(..) |
ast::ExprKind::MethodCall(..) => rewrite_chain(self, context, width, offset)
};
let f: fn(&_, _) -> _ = unimplemented!();
let f = unimplemented! {};
{
foo();
}
for &(sample, radiance) in samples.iter() {}
map(|&s| moo());
match x {
S { foo } => 92
}
}
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}
enum Foo {
Bar = 123,
Baz = 0,
}
pub struct Vec<T> {
buf: RawVec<T>,
len: usize,
}
impl<T> Vec<T> {
pub fn new() -> Vec<T> {
Vec {
buf: RawVec::new(),
len: 0,
}
}
pub fn with_capacity(capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::with_capacity(capacity),
len: 0,
}
}
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::from_raw_parts(ptr, capacity),
len: length,
}
}
pub fn capacity(&self) -> usize {
self.buf.cap()
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(self.len, additional);
}
pub fn into_boxed_slice(mut self) -> Box<[T]> {
unsafe {
self.shrink_to_fit();
let buf = ptr::read(&self.buf);
mem::forget(self);
buf.into_box()
}
}
pub fn truncate(&mut self, len: usize) {
unsafe {
while len < self.len {
self.len -= 1;
let len = self.len;
ptr::drop_in_place(self.get_unchecked_mut(len));
}
}
}
pub fn as_slice(&self) -> &[T] {
self
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
&mut self[..]
}
pub unsafe fn set_len(&mut self, len: usize) {
self.len = len;
}
pub fn remove(&mut self, index: usize) -> T {
let len = self.len();
assert!(index < len);
unsafe {
let ret;
{
let ptr = self.as_mut_ptr().offset(index as isize);
ret = ptr::read(ptr);
ptr::copy(ptr.offset(1), ptr, len - index - 1);
}
self.set_len(len - 1);
ret
}
}
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
if!f(&v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
let len = self.len();
let start = *range.start().unwrap_or(&0);
let end = *range.end().unwrap_or(&len);
assert!(start <= end);
assert!(end <= len);
}
}
impl<T: Clone> Vec<T> {
pub fn extend_from_slice(&mut self, other: &[T]) {
self.reserve(other.len());
for i in 0..other.len() {
let len = self.len();
unsafe {
ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
self.set_len(len + 1);
}
}
}
}
impl<T: PartialEq> Vec<T> {
pub fn dedup(&mut self) {
unsafe {
let ln = self.len();
if ln <= 1 {
return;
}
let p = self.as_mut_ptr();
let mut r: usize = 1;
let mut w: usize = 1;
while r < ln {
let p_r = p.offset(r as isize);
let p_wm1 = p.offset((w - 1) as isize);
if *p_r!= *p_wm1 {
if r!= w {
let p_w = p_wm1.offset(1);
mem::swap(&mut *p_r, &mut *p_w);
}
w += 1;
}
r += 1;
}
self.truncate(w);
}
}
}
pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {}
impl<T: Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
<[T]>::to_vec(&**self)
}
fn clone(&self) -> Vec<T> {
::slice::to_vec(&**self)
}
fn clone_from(&mut self, other: &Vec<T>)
|
}
impl<T: Hash> Hash for Vec<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&**self, state)
}
}
impl<T> Index<usize> for Vec<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
&(**self)[index]
}
}
impl<T> IndexMut<usize> for Vec<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
&mut (**self)[index]
}
}
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Vec<T> {
let mut iterator = iter.into_iter();
let mut vector = match iterator.next() {
None => return Vec::new(),
Some(element) => {
let (lower, _) = iterator.size_hint();
//...
}
};
//...
}
}
impl<T> IntoIterator for Vec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(mut self) -> IntoIter<T> {
unsafe {
let ptr = self.as_mut_ptr();
assume(!ptr.is_null());
let begin = ptr as *const T;
let end = if mem::size_of::<T>() == 0 {
arith_offset(ptr as *const i8, self.len() as isize) as *const T
} else {
ptr.offset(self.len() as isize) as *const T
};
let buf = ptr::read(&self.buf);
mem::forget(self);
IntoIter {
_buf: buf,
ptr: begin,
end: end,
}
}
}
}
impl<'a, T> IntoIterator for &'a Vec<T> {
type Item = &'a T;
}
impl<T> Iterator for IntoIter<T> {
fn size_hint(&self) -> (usize, Option<usize>) {
let diff = (self.end as usize) - (self.ptr as usize);
let size = mem::size_of::<T>();
let exact = diff / (if size == 0 { 1 } else { size });
(exact, Some(exact))
}
}
impl<'a, T> Iterator for Drain<'a, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
}
}
trait Extend<A> {
fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
}
impl<R, F: FnOnce() -> R> FnOnce<()> for AssertRecoverSafe<F> {
extern "rust-call" fn call_once(self, _args: ()) -> R {
(self.0)()
}
}
fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
let mut result = None;
unsafe {
let result = &mut result;
unwind::try(move || *result = Some(f()))?
}
Ok(result.unwrap())
}
fn propagate(payload: Box<Any + Send>) ->! {}
impl<K, V> Root<K, V> {
pub fn as_ref(&self) -> NodeRef<marker::Immut, K, V, marker::LeafOrInternal> {
NodeRef {
root: self as *const _ as *mut _,
}
}
}
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
mod math {
type Complex = (f64, f64);
fn sin(f: f64) -> f64 {
/*... */
}
}
fn foo(&&(x, _): &&(i32, i32)) {}
|
{
self.truncate(other.len());
let len = self.len();
self.clone_from_slice(&other[..len]);
self.extend_from_slice(&other[len..]);
}
|
identifier_body
|
spacing_after.rs
|
extern crate std as ruststd;
use core::hash::{self, Hash};
use core::intrinsics::{arith_offset, assume};
use core::iter::FromIterator;
use core::mem;
use core::ops::{Index, IndexMut};
const CAPACITY: usize = 2 * B - 1;
fn foo(a: i32, b: str, c: i32, d: f32) -> () {
let mut e: &'static [str] = "abcd";
let mut f: &[str] = "cdef";
bar();
let array: [i32; 45] = [0; 45];
let f: fn(i32, u64) -> i32;
let f2: fn(i32) -> i32;
let unit: () = ();
let foo = 2 + 2;
let moo = 2 * 2;
let meh = 2 * 2 + 3 * 3;
else_block.as_ref().map(|e| &**e);
match self.node {
ast::ExprKind::Field(..) |
ast::ExprKind::MethodCall(..) => rewrite_chain(self, context, width, offset)
};
let f: fn(&_, _) -> _ = unimplemented!();
let f = unimplemented! {};
{
foo();
}
for &(sample, radiance) in samples.iter() {}
map(|&s| moo());
match x {
S { foo } => 92
}
}
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}
enum Foo {
Bar = 123,
Baz = 0,
}
pub struct Vec<T> {
buf: RawVec<T>,
len: usize,
}
impl<T> Vec<T> {
pub fn new() -> Vec<T> {
Vec {
buf: RawVec::new(),
len: 0,
}
}
pub fn with_capacity(capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::with_capacity(capacity),
len: 0,
}
}
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::from_raw_parts(ptr, capacity),
len: length,
}
}
pub fn capacity(&self) -> usize {
self.buf.cap()
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(self.len, additional);
}
pub fn into_boxed_slice(mut self) -> Box<[T]> {
unsafe {
self.shrink_to_fit();
let buf = ptr::read(&self.buf);
mem::forget(self);
buf.into_box()
}
}
pub fn truncate(&mut self, len: usize) {
unsafe {
while len < self.len {
self.len -= 1;
let len = self.len;
ptr::drop_in_place(self.get_unchecked_mut(len));
}
}
}
pub fn as_slice(&self) -> &[T] {
self
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
&mut self[..]
}
pub unsafe fn set_len(&mut self, len: usize) {
self.len = len;
}
pub fn remove(&mut self, index: usize) -> T {
let len = self.len();
assert!(index < len);
unsafe {
let ret;
{
let ptr = self.as_mut_ptr().offset(index as isize);
ret = ptr::read(ptr);
ptr::copy(ptr.offset(1), ptr, len - index - 1);
}
self.set_len(len - 1);
ret
}
}
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
if!f(&v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
let len = self.len();
let start = *range.start().unwrap_or(&0);
let end = *range.end().unwrap_or(&len);
assert!(start <= end);
assert!(end <= len);
}
}
impl<T: Clone> Vec<T> {
pub fn extend_from_slice(&mut self, other: &[T]) {
self.reserve(other.len());
for i in 0..other.len() {
let len = self.len();
unsafe {
ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
self.set_len(len + 1);
}
}
}
}
impl<T: PartialEq> Vec<T> {
pub fn dedup(&mut self) {
unsafe {
let ln = self.len();
if ln <= 1 {
return;
}
let p = self.as_mut_ptr();
let mut r: usize = 1;
let mut w: usize = 1;
while r < ln {
let p_r = p.offset(r as isize);
let p_wm1 = p.offset((w - 1) as isize);
if *p_r!= *p_wm1 {
if r!= w {
let p_w = p_wm1.offset(1);
mem::swap(&mut *p_r, &mut *p_w);
}
w += 1;
}
r += 1;
}
self.truncate(w);
}
}
}
pub fn
|
<T: Clone>(elem: T, n: usize) -> Vec<T> {}
impl<T: Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
<[T]>::to_vec(&**self)
}
fn clone(&self) -> Vec<T> {
::slice::to_vec(&**self)
}
fn clone_from(&mut self, other: &Vec<T>) {
self.truncate(other.len());
let len = self.len();
self.clone_from_slice(&other[..len]);
self.extend_from_slice(&other[len..]);
}
}
impl<T: Hash> Hash for Vec<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Hash::hash(&**self, state)
}
}
impl<T> Index<usize> for Vec<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
&(**self)[index]
}
}
impl<T> IndexMut<usize> for Vec<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
&mut (**self)[index]
}
}
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Vec<T> {
let mut iterator = iter.into_iter();
let mut vector = match iterator.next() {
None => return Vec::new(),
Some(element) => {
let (lower, _) = iterator.size_hint();
//...
}
};
//...
}
}
impl<T> IntoIterator for Vec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(mut self) -> IntoIter<T> {
unsafe {
let ptr = self.as_mut_ptr();
assume(!ptr.is_null());
let begin = ptr as *const T;
let end = if mem::size_of::<T>() == 0 {
arith_offset(ptr as *const i8, self.len() as isize) as *const T
} else {
ptr.offset(self.len() as isize) as *const T
};
let buf = ptr::read(&self.buf);
mem::forget(self);
IntoIter {
_buf: buf,
ptr: begin,
end: end,
}
}
}
}
impl<'a, T> IntoIterator for &'a Vec<T> {
type Item = &'a T;
}
impl<T> Iterator for IntoIter<T> {
fn size_hint(&self) -> (usize, Option<usize>) {
let diff = (self.end as usize) - (self.ptr as usize);
let size = mem::size_of::<T>();
let exact = diff / (if size == 0 { 1 } else { size });
(exact, Some(exact))
}
}
impl<'a, T> Iterator for Drain<'a, T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
}
}
trait Extend<A> {
fn extend<T: IntoIterator<Item=A>>(&mut self, iterable: T);
}
impl<R, F: FnOnce() -> R> FnOnce<()> for AssertRecoverSafe<F> {
extern "rust-call" fn call_once(self, _args: ()) -> R {
(self.0)()
}
}
fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
let mut result = None;
unsafe {
let result = &mut result;
unwind::try(move || *result = Some(f()))?
}
Ok(result.unwrap())
}
fn propagate(payload: Box<Any + Send>) ->! {}
impl<K, V> Root<K, V> {
pub fn as_ref(&self) -> NodeRef<marker::Immut, K, V, marker::LeafOrInternal> {
NodeRef {
root: self as *const _ as *mut _,
}
}
}
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
mod math {
type Complex = (f64, f64);
fn sin(f: f64) -> f64 {
/*... */
}
}
fn foo(&&(x, _): &&(i32, i32)) {}
|
from_elem
|
identifier_name
|
shootout-k-nucleotide.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.
// ignore-android see #10393 #13206
// ignore-pretty
extern crate sync;
use std::strbuf::StrBuf;
use std::slice;
use sync::Arc;
use sync::Future;
static TABLE: [u8,..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str,..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(Eq, Ord, TotalOrd, TotalEq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> StrBuf {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
StrBuf::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(*entry);
return;
}
Table::search_remainder(*entry, key, c)
}
}
}
|
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(*entry);
return;
}
Table::search_remainder(*entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= l.slice_to(key.len())).skip(1)
{
res.push_all(l.trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
|
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
|
random_line_split
|
shootout-k-nucleotide.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.
// ignore-android see #10393 #13206
// ignore-pretty
extern crate sync;
use std::strbuf::StrBuf;
use std::slice;
use sync::Arc;
use sync::Future;
static TABLE: [u8,..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str,..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(Eq, Ord, TotalOrd, TotalEq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn
|
(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> StrBuf {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
StrBuf::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(*entry);
return;
}
Table::search_remainder(*entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(*entry);
return;
}
Table::search_remainder(*entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= l.slice_to(key.len())).skip(1)
{
res.push_all(l.trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
|
push_char
|
identifier_name
|
fwz_est.rs
|
%-------------------------------------------------------------%
% Declarations:
% names are separated by a comma, a space or both
% "..." are used to describe the preceding variable
%-------------------------------------------------------------%
%Endogenous variables
endogenous X, "Output gap", PAI, "Inflation", R, "Fed Funds rate",
ZS, "Supply shock process", ZD "Demand shock process"
%Exogenous variables
exogenous ES, "Supply shock", ED, "Demand shock", ER, "Monetary policy shock"
%parameters
parameters tau, "$\tau $", beta_trans, "$100\left( \frac{1}{\beta }-1\right) $",
|
% the relationship between the two is given in the model
% observable variables
varobs R, X, PAI
model
% auxiliary parameters
# beta=1/(1+beta_trans/100);
% Main equations
% N.B: time is denoted by () as in dynare or by {}. Below, we use the {} notation
X = X{+1}-tau*(R-PAI{+1})+ZD;
PAI = beta*PAI{+1}+kappa*X+ZS;
R = rhor*R{-1}+(1-rhor)*(gamma_1*PAI+gamma_2*X)+sigr*ER;
% Shock processes
ZD = rhod*ZD{-1}+sigd*ED;
ZS = rhos*ZS{-1}+sigs*ES;
% the non-policy parameters never switch, they will be controlled by the const markov chain
parameterization
tau , 0.5376, 0.1000, 0.5000, gamma_pdf(.90);
kappa , 0.5800, 0.0500, 1.0000, gamma_pdf(.90);
beta_trans , 0.1000, 0.2000, 0.4000, beta_pdf(.90);
% for simplicity, we also assume that the persistence of the shocks is constant
% change this if you don't like the assumption
rhod , 0.83 , 0.5000, 0.9000, beta_pdf(.90);
rhos , 0.85 , 0.5000, 0.9000, beta_pdf(.90);
rhor , 0.60 , 0.5000, 0.9000, beta_pdf(.90);
|
kappa, "$\kappa $", rhor, "$\rho _{r}$",
rhod, "$\rho _{d}$" rhos, "$\rho _{s}$"
% N.B: we have removed the transition probabilities from the list of
% parameters since in some cases they will not matter
% N.B: we replace beta by beta_trans, just to make optimization easier
|
random_line_split
|
serialize-deserialize-state-format-old.rs
|
/*
Copyright © 2016 Zetok Zalbavar <[email protected]>
This file is part of Tox.
Tox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Tox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Tox. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate tox;
use tox::toxcore::binary_io::*;
use tox::toxcore::state_format::old::*;
/*
Load bytes of a real™ profile, de-serialize it and serialize again. Serialized
again bytes must be identical, except for the zeros that trail after the data
in original implementation – they're ommited. Just check if smaller length of
the resulting bytes are in fact due to original being appended with `0`s.
*/
#[test]
fn test_
|
let bytes = include_bytes!("state-format-old-data/profile-with-contacts.tox");
let profile_b = State::from_bytes(bytes).unwrap().to_bytes();
assert_eq!(&bytes[..profile_b.len()], profile_b.as_slice());
// c-toxcore appends `0`s after EOF because reasons
for b in &bytes[profile_b.len()..] {
assert_eq!(0, *b);
}
}
|
state_format_to_and_from_bytes() {
|
identifier_name
|
serialize-deserialize-state-format-old.rs
|
/*
Copyright © 2016 Zetok Zalbavar <[email protected]>
This file is part of Tox.
|
Tox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Tox. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate tox;
use tox::toxcore::binary_io::*;
use tox::toxcore::state_format::old::*;
/*
Load bytes of a real™ profile, de-serialize it and serialize again. Serialized
again bytes must be identical, except for the zeros that trail after the data
in original implementation – they're ommited. Just check if smaller length of
the resulting bytes are in fact due to original being appended with `0`s.
*/
#[test]
fn test_state_format_to_and_from_bytes() {
let bytes = include_bytes!("state-format-old-data/profile-with-contacts.tox");
let profile_b = State::from_bytes(bytes).unwrap().to_bytes();
assert_eq!(&bytes[..profile_b.len()], profile_b.as_slice());
// c-toxcore appends `0`s after EOF because reasons
for b in &bytes[profile_b.len()..] {
assert_eq!(0, *b);
}
}
|
Tox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
|
random_line_split
|
serialize-deserialize-state-format-old.rs
|
/*
Copyright © 2016 Zetok Zalbavar <[email protected]>
This file is part of Tox.
Tox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Tox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Tox. If not, see <http://www.gnu.org/licenses/>.
*/
extern crate tox;
use tox::toxcore::binary_io::*;
use tox::toxcore::state_format::old::*;
/*
Load bytes of a real™ profile, de-serialize it and serialize again. Serialized
again bytes must be identical, except for the zeros that trail after the data
in original implementation – they're ommited. Just check if smaller length of
the resulting bytes are in fact due to original being appended with `0`s.
*/
#[test]
fn test_state_format_to_and_from_bytes() {
|
let bytes = include_bytes!("state-format-old-data/profile-with-contacts.tox");
let profile_b = State::from_bytes(bytes).unwrap().to_bytes();
assert_eq!(&bytes[..profile_b.len()], profile_b.as_slice());
// c-toxcore appends `0`s after EOF because reasons
for b in &bytes[profile_b.len()..] {
assert_eq!(0, *b);
}
}
|
identifier_body
|
|
lib.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_trans"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(alloc)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(unicode)]
#![feature(path_ext)]
#![feature(fs)]
#![feature(path_relative_from)]
#![allow(trivial_casts)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use rustc::session;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::lint;
pub use rustc::plugin;
pub use rustc::util;
|
pub mod back {
pub use rustc_back::abi;
pub use rustc_back::archive;
pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel;
pub use rustc_back::rpath;
pub use rustc_back::svh;
pub use rustc_back::target_strs;
pub use rustc_back::x86;
pub use rustc_back::x86_64;
pub mod linker;
pub mod link;
pub mod lto;
pub mod write;
}
pub mod trans;
pub mod save;
pub mod lib {
pub use llvm;
}
|
random_line_split
|
|
node.rs
|
//! The sure stream.
//!
//! The sure stream represents a linearization of a SureTree. By keeping
//! representations as iterators across SureNodes instead of keeping an
//! entire tree in memory, we can process larger filesystem trees, using
//! temporary space on the hard disk instead of using memory.
use crate::{suretree::AttMap, Error, Result};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use std::{
fs::File,
io::{self, BufRead, BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
};
use weave::NamingConvention;
mod compare;
pub mod fs;
mod fullpath;
mod hashes;
pub use compare::compare_trees;
pub use fullpath::into_tracker;
pub use hashes::{HashCombiner, HashUpdater, Source};
#[derive(Clone, Debug)]
pub enum SureNode {
Enter { name: String, atts: AttMap },
Leave,
File { name: String, atts: AttMap },
Sep,
}
impl SureNode {
pub fn is_enter(&self) -> bool {
matches!(self, SureNode::Enter {.. })
}
pub fn is_reg_file(&self) -> bool {
match self {
SureNode::File { atts,.. } => atts["kind"] == "file",
_ => false,
}
}
pub fn is_file(&self) -> bool {
matches!(self, SureNode::File {.. })
}
pub fn is_leave(&self) -> bool {
matches!(self, SureNode::Leave)
}
pub fn is_sep(&self) -> bool {
matches!(self, SureNode::Sep)
}
pub fn needs_hash(&self) -> bool {
match self {
SureNode::File { atts,.. } => atts["kind"] == "file" &&!atts.contains_key("sha1"),
_ => false,
}
}
pub fn size(&self) -> u64 {
match self {
SureNode::File { atts,.. } => {
atts.get("size").map(|x| x.parse().unwrap()).unwrap_or(0)
}
_ => 0,
}
}
/// Get the name of this node. Panics if the node type does not have
/// an associated name.
pub fn name(&self) -> &str {
match self {
SureNode::File { ref name,.. } => name,
SureNode::Enter { ref name,.. } => name,
_ => panic!("Node does not have a name"),
}
}
/// Safely get the name of this node.
pub fn get_name(&self) -> Option<&str> {
match self {
SureNode::File { ref name,.. } => Some(name),
SureNode::Enter { ref name,.. } => Some(name),
_ => None,
}
}
/// Get a nice representation of the kind of this node. Returns "???"
/// if the kind isn't meaningful.
pub fn kind(&self) -> &str {
self.atts()
.map(|a| a.get("kind").map(|k| &k[..]).unwrap_or("???"))
.unwrap_or("???")
}
/// Access the nodes attributes.
pub fn atts(&self) -> Option<&AttMap> {
match self {
SureNode::File { ref atts,.. } => Some(atts),
SureNode::Enter { ref atts,.. } => Some(atts),
_ => None,
}
}
/// Access the nodes attributes mutably.
pub fn atts_mut(&mut self) -> Option<&mut AttMap> {
match self {
SureNode::File { ref mut atts,.. } => Some(atts),
SureNode::Enter { ref mut atts,.. } => Some(atts),
_ => None,
}
}
}
// TODO: These might be possible to make more generic, but it gets messy,
// as it might just be best to assume failure.
/// Write a sure iterator to a standard gzipped file of the given name.
pub fn save<P, I>(name: P, nodes: I) -> Result<()>
where
P: AsRef<Path>,
I: Iterator<Item = Result<SureNode>>,
{
let wr = File::create(name)?;
let wr = GzEncoder::new(wr, Compression::default());
save_to(wr, nodes)
}
/// Write a sure iterator to a new temp file with a given naming
/// convention. Returns the name of the file, if it could be created. The
/// data will not be written compressed.
pub fn save_naming<I, N>(naming: &N, nodes: I) -> Result<PathBuf>
where
N: NamingConvention,
I: Iterator<Item = Result<SureNode>>,
{
let (tmp_name, mut tmp_file) = naming.temp_file()?;
save_to(&mut tmp_file, nodes)?;
Ok(tmp_name)
}
/// Save a sure tree to the given writer.
pub fn save_to<W, I>(wr: W, nodes: I) -> Result<()>
where
W: Write,
I: Iterator<Item = Result<SureNode>>,
{
let mut wr = BufWriter::new(wr);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
for node in nodes {
match node? {
SureNode::Enter { name, atts } => header(&mut wr, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut wr, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut wr, "-")?,
SureNode::Leave => writeln!(&mut wr, "u")?,
}
}
Ok(())
}
/// For pushed based writing, we can also write using a NodeWriter.
pub struct NodeWriter<W: Write> {
writer: BufWriter<W>,
}
impl<W: Write> NodeWriter<W> {
pub fn new(writer: W) -> Result<NodeWriter<W>> {
let mut wr = BufWriter::new(writer);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
Ok(NodeWriter { writer: wr })
}
pub fn write_node(&mut self, node: &SureNode) -> Result<()> {
match node {
SureNode::Enter { name, atts } => header(&mut self.writer, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut self.writer, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut self.writer, "-")?,
SureNode::Leave => writeln!(&mut self.writer, "u")?,
}
Ok(())
}
}
fn header<W: Write>(out: &mut W, kind: char, name: &str, atts: &AttMap) -> Result<()> {
write!(out, "{}{} [", kind, name)?;
for (k, v) in atts {
write!(out, "{} {} ", k, v)?;
}
writeln!(out, "]")?;
Ok(())
}
/// Load and iterate a sure tree from a standard gzip compressed surefile.
pub fn load<P: AsRef<Path>>(name: P) -> Result<ReadIterator<GzDecoder<File>>> {
let rd = File::open(name)?;
let rd = GzDecoder::new(rd);
load_from(rd)
}
/// Load a surenode sequence from the given reader.
pub fn load_from<R: Read>(rd: R) -> Result<ReadIterator<R>>
|
fn fixed<I>(inp: &mut I, exp: &[u8]) -> Result<()>
where
I: Iterator<Item = io::Result<Vec<u8>>>,
{
match inp.next() {
Some(Ok(ref text)) if &text[..] == exp => Ok(()),
Some(Ok(ref text)) => Err(Error::UnexpectedLine(
String::from_utf8_lossy(text).into_owned(),
String::from_utf8_lossy(exp).into_owned(),
)),
Some(Err(e)) => Err(Error::SureFileError(e)),
None => Err(Error::SureFileEof),
}
}
pub struct ReadIterator<R> {
lines: io::Split<BufReader<R>>,
depth: usize,
done: bool,
}
impl<R: Read> Iterator for ReadIterator<R> {
type Item = Result<SureNode>;
fn next(&mut self) -> Option<Result<SureNode>> {
if self.done {
return None;
}
let line = match self.get_line() {
Ok(line) => line,
Err(e) => return Some(Err(e)),
};
match line[0] {
b'd' => {
let (dname, datts) = decode_entity(&line[1..]);
self.depth += 1;
Some(Ok(SureNode::Enter {
name: dname,
atts: datts,
}))
}
b'f' => {
let (fname, fatts) = decode_entity(&line[1..]);
Some(Ok(SureNode::File {
name: fname,
atts: fatts,
}))
}
b'-' => Some(Ok(SureNode::Sep)),
b'u' => {
self.depth -= 1;
if self.depth == 0 {
self.done = true;
}
Some(Ok(SureNode::Leave))
}
ch => Some(Err(Error::InvalidSurefileChar(ch as char))),
}
}
}
impl<R: Read> ReadIterator<R> {
fn get_line(&mut self) -> Result<Vec<u8>> {
match self.lines.next() {
None => Err(Error::TruncatedSurefile),
Some(l) => Ok(l?),
}
}
}
// TODO: This should return Result to handle errors.
pub(crate) fn decode_entity(text: &[u8]) -> (String, AttMap) {
let (name, mut text) = get_delim(text, b' ');
assert!(text[0] == b'[');
text = &text[1..];
let mut atts = AttMap::new();
while text[0]!= b']' {
let (key, t2) = get_delim(text, b' ');
let (value, t2) = get_delim(t2, b' ');
text = t2;
atts.insert(key, value);
}
(name, atts)
}
fn get_delim(text: &[u8], delim: u8) -> (String, &[u8]) {
let mut it = text.iter();
let space = it.position(|&s| s == delim).unwrap();
(
String::from_utf8(text[..space].to_owned()).unwrap(),
&text[space + 1..],
)
}
|
{
let rd = BufReader::new(rd);
let mut lines = rd.split(b'\n');
fixed(&mut lines, b"asure-2.0")?;
fixed(&mut lines, b"-----")?;
Ok(ReadIterator {
lines,
depth: 0,
done: false,
})
}
|
identifier_body
|
node.rs
|
//! The sure stream.
//!
//! The sure stream represents a linearization of a SureTree. By keeping
//! representations as iterators across SureNodes instead of keeping an
//! entire tree in memory, we can process larger filesystem trees, using
//! temporary space on the hard disk instead of using memory.
use crate::{suretree::AttMap, Error, Result};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use std::{
fs::File,
io::{self, BufRead, BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
};
use weave::NamingConvention;
mod compare;
pub mod fs;
mod fullpath;
mod hashes;
pub use compare::compare_trees;
pub use fullpath::into_tracker;
pub use hashes::{HashCombiner, HashUpdater, Source};
#[derive(Clone, Debug)]
pub enum SureNode {
Enter { name: String, atts: AttMap },
Leave,
File { name: String, atts: AttMap },
Sep,
}
impl SureNode {
pub fn is_enter(&self) -> bool {
matches!(self, SureNode::Enter {.. })
}
|
}
}
pub fn is_file(&self) -> bool {
matches!(self, SureNode::File {.. })
}
pub fn is_leave(&self) -> bool {
matches!(self, SureNode::Leave)
}
pub fn is_sep(&self) -> bool {
matches!(self, SureNode::Sep)
}
pub fn needs_hash(&self) -> bool {
match self {
SureNode::File { atts,.. } => atts["kind"] == "file" &&!atts.contains_key("sha1"),
_ => false,
}
}
pub fn size(&self) -> u64 {
match self {
SureNode::File { atts,.. } => {
atts.get("size").map(|x| x.parse().unwrap()).unwrap_or(0)
}
_ => 0,
}
}
/// Get the name of this node. Panics if the node type does not have
/// an associated name.
pub fn name(&self) -> &str {
match self {
SureNode::File { ref name,.. } => name,
SureNode::Enter { ref name,.. } => name,
_ => panic!("Node does not have a name"),
}
}
/// Safely get the name of this node.
pub fn get_name(&self) -> Option<&str> {
match self {
SureNode::File { ref name,.. } => Some(name),
SureNode::Enter { ref name,.. } => Some(name),
_ => None,
}
}
/// Get a nice representation of the kind of this node. Returns "???"
/// if the kind isn't meaningful.
pub fn kind(&self) -> &str {
self.atts()
.map(|a| a.get("kind").map(|k| &k[..]).unwrap_or("???"))
.unwrap_or("???")
}
/// Access the nodes attributes.
pub fn atts(&self) -> Option<&AttMap> {
match self {
SureNode::File { ref atts,.. } => Some(atts),
SureNode::Enter { ref atts,.. } => Some(atts),
_ => None,
}
}
/// Access the nodes attributes mutably.
pub fn atts_mut(&mut self) -> Option<&mut AttMap> {
match self {
SureNode::File { ref mut atts,.. } => Some(atts),
SureNode::Enter { ref mut atts,.. } => Some(atts),
_ => None,
}
}
}
// TODO: These might be possible to make more generic, but it gets messy,
// as it might just be best to assume failure.
/// Write a sure iterator to a standard gzipped file of the given name.
pub fn save<P, I>(name: P, nodes: I) -> Result<()>
where
P: AsRef<Path>,
I: Iterator<Item = Result<SureNode>>,
{
let wr = File::create(name)?;
let wr = GzEncoder::new(wr, Compression::default());
save_to(wr, nodes)
}
/// Write a sure iterator to a new temp file with a given naming
/// convention. Returns the name of the file, if it could be created. The
/// data will not be written compressed.
pub fn save_naming<I, N>(naming: &N, nodes: I) -> Result<PathBuf>
where
N: NamingConvention,
I: Iterator<Item = Result<SureNode>>,
{
let (tmp_name, mut tmp_file) = naming.temp_file()?;
save_to(&mut tmp_file, nodes)?;
Ok(tmp_name)
}
/// Save a sure tree to the given writer.
pub fn save_to<W, I>(wr: W, nodes: I) -> Result<()>
where
W: Write,
I: Iterator<Item = Result<SureNode>>,
{
let mut wr = BufWriter::new(wr);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
for node in nodes {
match node? {
SureNode::Enter { name, atts } => header(&mut wr, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut wr, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut wr, "-")?,
SureNode::Leave => writeln!(&mut wr, "u")?,
}
}
Ok(())
}
/// For pushed based writing, we can also write using a NodeWriter.
pub struct NodeWriter<W: Write> {
writer: BufWriter<W>,
}
impl<W: Write> NodeWriter<W> {
pub fn new(writer: W) -> Result<NodeWriter<W>> {
let mut wr = BufWriter::new(writer);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
Ok(NodeWriter { writer: wr })
}
pub fn write_node(&mut self, node: &SureNode) -> Result<()> {
match node {
SureNode::Enter { name, atts } => header(&mut self.writer, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut self.writer, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut self.writer, "-")?,
SureNode::Leave => writeln!(&mut self.writer, "u")?,
}
Ok(())
}
}
fn header<W: Write>(out: &mut W, kind: char, name: &str, atts: &AttMap) -> Result<()> {
write!(out, "{}{} [", kind, name)?;
for (k, v) in atts {
write!(out, "{} {} ", k, v)?;
}
writeln!(out, "]")?;
Ok(())
}
/// Load and iterate a sure tree from a standard gzip compressed surefile.
pub fn load<P: AsRef<Path>>(name: P) -> Result<ReadIterator<GzDecoder<File>>> {
let rd = File::open(name)?;
let rd = GzDecoder::new(rd);
load_from(rd)
}
/// Load a surenode sequence from the given reader.
pub fn load_from<R: Read>(rd: R) -> Result<ReadIterator<R>> {
let rd = BufReader::new(rd);
let mut lines = rd.split(b'\n');
fixed(&mut lines, b"asure-2.0")?;
fixed(&mut lines, b"-----")?;
Ok(ReadIterator {
lines,
depth: 0,
done: false,
})
}
fn fixed<I>(inp: &mut I, exp: &[u8]) -> Result<()>
where
I: Iterator<Item = io::Result<Vec<u8>>>,
{
match inp.next() {
Some(Ok(ref text)) if &text[..] == exp => Ok(()),
Some(Ok(ref text)) => Err(Error::UnexpectedLine(
String::from_utf8_lossy(text).into_owned(),
String::from_utf8_lossy(exp).into_owned(),
)),
Some(Err(e)) => Err(Error::SureFileError(e)),
None => Err(Error::SureFileEof),
}
}
pub struct ReadIterator<R> {
lines: io::Split<BufReader<R>>,
depth: usize,
done: bool,
}
impl<R: Read> Iterator for ReadIterator<R> {
type Item = Result<SureNode>;
fn next(&mut self) -> Option<Result<SureNode>> {
if self.done {
return None;
}
let line = match self.get_line() {
Ok(line) => line,
Err(e) => return Some(Err(e)),
};
match line[0] {
b'd' => {
let (dname, datts) = decode_entity(&line[1..]);
self.depth += 1;
Some(Ok(SureNode::Enter {
name: dname,
atts: datts,
}))
}
b'f' => {
let (fname, fatts) = decode_entity(&line[1..]);
Some(Ok(SureNode::File {
name: fname,
atts: fatts,
}))
}
b'-' => Some(Ok(SureNode::Sep)),
b'u' => {
self.depth -= 1;
if self.depth == 0 {
self.done = true;
}
Some(Ok(SureNode::Leave))
}
ch => Some(Err(Error::InvalidSurefileChar(ch as char))),
}
}
}
impl<R: Read> ReadIterator<R> {
fn get_line(&mut self) -> Result<Vec<u8>> {
match self.lines.next() {
None => Err(Error::TruncatedSurefile),
Some(l) => Ok(l?),
}
}
}
// TODO: This should return Result to handle errors.
pub(crate) fn decode_entity(text: &[u8]) -> (String, AttMap) {
let (name, mut text) = get_delim(text, b' ');
assert!(text[0] == b'[');
text = &text[1..];
let mut atts = AttMap::new();
while text[0]!= b']' {
let (key, t2) = get_delim(text, b' ');
let (value, t2) = get_delim(t2, b' ');
text = t2;
atts.insert(key, value);
}
(name, atts)
}
fn get_delim(text: &[u8], delim: u8) -> (String, &[u8]) {
let mut it = text.iter();
let space = it.position(|&s| s == delim).unwrap();
(
String::from_utf8(text[..space].to_owned()).unwrap(),
&text[space + 1..],
)
}
|
pub fn is_reg_file(&self) -> bool {
match self {
SureNode::File { atts, .. } => atts["kind"] == "file",
_ => false,
|
random_line_split
|
node.rs
|
//! The sure stream.
//!
//! The sure stream represents a linearization of a SureTree. By keeping
//! representations as iterators across SureNodes instead of keeping an
//! entire tree in memory, we can process larger filesystem trees, using
//! temporary space on the hard disk instead of using memory.
use crate::{suretree::AttMap, Error, Result};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use std::{
fs::File,
io::{self, BufRead, BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
};
use weave::NamingConvention;
mod compare;
pub mod fs;
mod fullpath;
mod hashes;
pub use compare::compare_trees;
pub use fullpath::into_tracker;
pub use hashes::{HashCombiner, HashUpdater, Source};
#[derive(Clone, Debug)]
pub enum SureNode {
Enter { name: String, atts: AttMap },
Leave,
File { name: String, atts: AttMap },
Sep,
}
impl SureNode {
pub fn is_enter(&self) -> bool {
matches!(self, SureNode::Enter {.. })
}
pub fn is_reg_file(&self) -> bool {
match self {
SureNode::File { atts,.. } => atts["kind"] == "file",
_ => false,
}
}
pub fn is_file(&self) -> bool {
matches!(self, SureNode::File {.. })
}
pub fn is_leave(&self) -> bool {
matches!(self, SureNode::Leave)
}
pub fn is_sep(&self) -> bool {
matches!(self, SureNode::Sep)
}
pub fn needs_hash(&self) -> bool {
match self {
SureNode::File { atts,.. } => atts["kind"] == "file" &&!atts.contains_key("sha1"),
_ => false,
}
}
pub fn size(&self) -> u64 {
match self {
SureNode::File { atts,.. } => {
atts.get("size").map(|x| x.parse().unwrap()).unwrap_or(0)
}
_ => 0,
}
}
/// Get the name of this node. Panics if the node type does not have
/// an associated name.
pub fn name(&self) -> &str {
match self {
SureNode::File { ref name,.. } => name,
SureNode::Enter { ref name,.. } => name,
_ => panic!("Node does not have a name"),
}
}
/// Safely get the name of this node.
pub fn get_name(&self) -> Option<&str> {
match self {
SureNode::File { ref name,.. } => Some(name),
SureNode::Enter { ref name,.. } => Some(name),
_ => None,
}
}
/// Get a nice representation of the kind of this node. Returns "???"
/// if the kind isn't meaningful.
pub fn kind(&self) -> &str {
self.atts()
.map(|a| a.get("kind").map(|k| &k[..]).unwrap_or("???"))
.unwrap_or("???")
}
/// Access the nodes attributes.
pub fn
|
(&self) -> Option<&AttMap> {
match self {
SureNode::File { ref atts,.. } => Some(atts),
SureNode::Enter { ref atts,.. } => Some(atts),
_ => None,
}
}
/// Access the nodes attributes mutably.
pub fn atts_mut(&mut self) -> Option<&mut AttMap> {
match self {
SureNode::File { ref mut atts,.. } => Some(atts),
SureNode::Enter { ref mut atts,.. } => Some(atts),
_ => None,
}
}
}
// TODO: These might be possible to make more generic, but it gets messy,
// as it might just be best to assume failure.
/// Write a sure iterator to a standard gzipped file of the given name.
pub fn save<P, I>(name: P, nodes: I) -> Result<()>
where
P: AsRef<Path>,
I: Iterator<Item = Result<SureNode>>,
{
let wr = File::create(name)?;
let wr = GzEncoder::new(wr, Compression::default());
save_to(wr, nodes)
}
/// Write a sure iterator to a new temp file with a given naming
/// convention. Returns the name of the file, if it could be created. The
/// data will not be written compressed.
pub fn save_naming<I, N>(naming: &N, nodes: I) -> Result<PathBuf>
where
N: NamingConvention,
I: Iterator<Item = Result<SureNode>>,
{
let (tmp_name, mut tmp_file) = naming.temp_file()?;
save_to(&mut tmp_file, nodes)?;
Ok(tmp_name)
}
/// Save a sure tree to the given writer.
pub fn save_to<W, I>(wr: W, nodes: I) -> Result<()>
where
W: Write,
I: Iterator<Item = Result<SureNode>>,
{
let mut wr = BufWriter::new(wr);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
for node in nodes {
match node? {
SureNode::Enter { name, atts } => header(&mut wr, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut wr, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut wr, "-")?,
SureNode::Leave => writeln!(&mut wr, "u")?,
}
}
Ok(())
}
/// For pushed based writing, we can also write using a NodeWriter.
pub struct NodeWriter<W: Write> {
writer: BufWriter<W>,
}
impl<W: Write> NodeWriter<W> {
pub fn new(writer: W) -> Result<NodeWriter<W>> {
let mut wr = BufWriter::new(writer);
writeln!(&mut wr, "asure-2.0")?;
writeln!(&mut wr, "-----")?;
Ok(NodeWriter { writer: wr })
}
pub fn write_node(&mut self, node: &SureNode) -> Result<()> {
match node {
SureNode::Enter { name, atts } => header(&mut self.writer, 'd', &name, &atts)?,
SureNode::File { name, atts } => header(&mut self.writer, 'f', &name, &atts)?,
SureNode::Sep => writeln!(&mut self.writer, "-")?,
SureNode::Leave => writeln!(&mut self.writer, "u")?,
}
Ok(())
}
}
fn header<W: Write>(out: &mut W, kind: char, name: &str, atts: &AttMap) -> Result<()> {
write!(out, "{}{} [", kind, name)?;
for (k, v) in atts {
write!(out, "{} {} ", k, v)?;
}
writeln!(out, "]")?;
Ok(())
}
/// Load and iterate a sure tree from a standard gzip compressed surefile.
pub fn load<P: AsRef<Path>>(name: P) -> Result<ReadIterator<GzDecoder<File>>> {
let rd = File::open(name)?;
let rd = GzDecoder::new(rd);
load_from(rd)
}
/// Load a surenode sequence from the given reader.
pub fn load_from<R: Read>(rd: R) -> Result<ReadIterator<R>> {
let rd = BufReader::new(rd);
let mut lines = rd.split(b'\n');
fixed(&mut lines, b"asure-2.0")?;
fixed(&mut lines, b"-----")?;
Ok(ReadIterator {
lines,
depth: 0,
done: false,
})
}
fn fixed<I>(inp: &mut I, exp: &[u8]) -> Result<()>
where
I: Iterator<Item = io::Result<Vec<u8>>>,
{
match inp.next() {
Some(Ok(ref text)) if &text[..] == exp => Ok(()),
Some(Ok(ref text)) => Err(Error::UnexpectedLine(
String::from_utf8_lossy(text).into_owned(),
String::from_utf8_lossy(exp).into_owned(),
)),
Some(Err(e)) => Err(Error::SureFileError(e)),
None => Err(Error::SureFileEof),
}
}
pub struct ReadIterator<R> {
lines: io::Split<BufReader<R>>,
depth: usize,
done: bool,
}
impl<R: Read> Iterator for ReadIterator<R> {
type Item = Result<SureNode>;
fn next(&mut self) -> Option<Result<SureNode>> {
if self.done {
return None;
}
let line = match self.get_line() {
Ok(line) => line,
Err(e) => return Some(Err(e)),
};
match line[0] {
b'd' => {
let (dname, datts) = decode_entity(&line[1..]);
self.depth += 1;
Some(Ok(SureNode::Enter {
name: dname,
atts: datts,
}))
}
b'f' => {
let (fname, fatts) = decode_entity(&line[1..]);
Some(Ok(SureNode::File {
name: fname,
atts: fatts,
}))
}
b'-' => Some(Ok(SureNode::Sep)),
b'u' => {
self.depth -= 1;
if self.depth == 0 {
self.done = true;
}
Some(Ok(SureNode::Leave))
}
ch => Some(Err(Error::InvalidSurefileChar(ch as char))),
}
}
}
impl<R: Read> ReadIterator<R> {
fn get_line(&mut self) -> Result<Vec<u8>> {
match self.lines.next() {
None => Err(Error::TruncatedSurefile),
Some(l) => Ok(l?),
}
}
}
// TODO: This should return Result to handle errors.
pub(crate) fn decode_entity(text: &[u8]) -> (String, AttMap) {
let (name, mut text) = get_delim(text, b' ');
assert!(text[0] == b'[');
text = &text[1..];
let mut atts = AttMap::new();
while text[0]!= b']' {
let (key, t2) = get_delim(text, b' ');
let (value, t2) = get_delim(t2, b' ');
text = t2;
atts.insert(key, value);
}
(name, atts)
}
fn get_delim(text: &[u8], delim: u8) -> (String, &[u8]) {
let mut it = text.iter();
let space = it.position(|&s| s == delim).unwrap();
(
String::from_utf8(text[..space].to_owned()).unwrap(),
&text[space + 1..],
)
}
|
atts
|
identifier_name
|
main.rs
|
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate websocket;
extern crate yassy;
extern crate midi;
mod jack;
mod jack_plugin;
use jack::*;
use std::time::Duration;
use std::ffi::CString;
// use std::thread;
// use websocket::{Server, Message, Sender, Receiver};
// use websocket::message::Type;
// use websocket::header::WebSocketProtocol;
// use std::ffi::CString;
// use std::ffi::CStr;
// use std::sync::{Arc, Mutex};
// use std::sync::mpsc;
// use std::ptr;
// use jack_plugin;
// use yassy::Plugin;
extern "C" fn process(jack_nframes_t: u32, ptr: *mut libc::c_void) -> isize
|
(*plugin).midievent(&*event.buffer);
ievent = ievent + 1;
// Need to check if ievent < event_count before next call to
// jack_midi_event_get()? Don't think so, but see
// https://github.com/jackaudio/example-clients/blob/master/midisine.c
jack_midi_event_get(&mut event, buf, ievent);
}
let amp = (*plugin).get_amp();
*out.offset(i as isize) = amp;
}
}
0
}
pub type Plugin<'a> = jack_plugin::jack_plugin<'a>;
fn main() {
// CString must stay alive after pointer is obtained
// see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-than-4-characters-breaks-client
let name = CString::new("yassyhost").unwrap();
let mut p = Plugin::new(&name);
p.initialize();
p.set_fs();
p.connect();
let cbpluginptr = (&p as *const Plugin) as *const libc::c_void;
unsafe {
jack_set_process_callback(p.client, process, cbpluginptr);
jack_activate(p.client);
let five = Duration::new(5, 0);
loop {
std::thread::sleep(five);
}
// jack_port_unregister(p.client, p.in_port.handle);
// jack_port_unregister(p.client, p.output.handle);
// jack_client_close(p.client);
}
}
|
{
unsafe {
let plugin = ptr as *mut Plugin;
let inport = &(*plugin).in_port;
let outport = &(*plugin).output;
let buf = jack_port_get_buffer(inport.handle, jack_nframes_t);
let out = jack_port_get_buffer(outport.handle, jack_nframes_t) as *mut f32;
let event_count = jack_midi_get_event_count(buf);
let mut event = JackMidiEvent {
time: 0,
size: 0,
buffer: std::ptr::null_mut() as *mut libc::c_uchar,
};
let mut ievent = 0;
jack_midi_event_get(&mut event, buf, ievent);
for i in 0..jack_nframes_t {
if (event.time == i) & (ievent < event_count) {
|
identifier_body
|
main.rs
|
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate websocket;
extern crate yassy;
extern crate midi;
mod jack;
mod jack_plugin;
use jack::*;
use std::time::Duration;
use std::ffi::CString;
// use std::thread;
// use websocket::{Server, Message, Sender, Receiver};
// use websocket::message::Type;
// use websocket::header::WebSocketProtocol;
// use std::ffi::CString;
// use std::ffi::CStr;
// use std::sync::{Arc, Mutex};
// use std::sync::mpsc;
// use std::ptr;
// use jack_plugin;
// use yassy::Plugin;
extern "C" fn process(jack_nframes_t: u32, ptr: *mut libc::c_void) -> isize {
unsafe {
let plugin = ptr as *mut Plugin;
let inport = &(*plugin).in_port;
let outport = &(*plugin).output;
let buf = jack_port_get_buffer(inport.handle, jack_nframes_t);
let out = jack_port_get_buffer(outport.handle, jack_nframes_t) as *mut f32;
let event_count = jack_midi_get_event_count(buf);
let mut event = JackMidiEvent {
time: 0,
size: 0,
buffer: std::ptr::null_mut() as *mut libc::c_uchar,
};
let mut ievent = 0;
jack_midi_event_get(&mut event, buf, ievent);
for i in 0..jack_nframes_t {
if (event.time == i) & (ievent < event_count) {
(*plugin).midievent(&*event.buffer);
ievent = ievent + 1;
// Need to check if ievent < event_count before next call to
// jack_midi_event_get()? Don't think so, but see
// https://github.com/jackaudio/example-clients/blob/master/midisine.c
jack_midi_event_get(&mut event, buf, ievent);
}
let amp = (*plugin).get_amp();
*out.offset(i as isize) = amp;
}
}
0
}
pub type Plugin<'a> = jack_plugin::jack_plugin<'a>;
fn
|
() {
// CString must stay alive after pointer is obtained
// see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-than-4-characters-breaks-client
let name = CString::new("yassyhost").unwrap();
let mut p = Plugin::new(&name);
p.initialize();
p.set_fs();
p.connect();
let cbpluginptr = (&p as *const Plugin) as *const libc::c_void;
unsafe {
jack_set_process_callback(p.client, process, cbpluginptr);
jack_activate(p.client);
let five = Duration::new(5, 0);
loop {
std::thread::sleep(five);
}
// jack_port_unregister(p.client, p.in_port.handle);
// jack_port_unregister(p.client, p.output.handle);
// jack_client_close(p.client);
}
}
|
main
|
identifier_name
|
main.rs
|
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate websocket;
extern crate yassy;
extern crate midi;
mod jack;
mod jack_plugin;
use jack::*;
use std::time::Duration;
use std::ffi::CString;
// use std::thread;
// use websocket::{Server, Message, Sender, Receiver};
// use websocket::message::Type;
// use websocket::header::WebSocketProtocol;
// use std::ffi::CString;
// use std::ffi::CStr;
// use std::sync::{Arc, Mutex};
// use std::sync::mpsc;
// use std::ptr;
// use jack_plugin;
// use yassy::Plugin;
extern "C" fn process(jack_nframes_t: u32, ptr: *mut libc::c_void) -> isize {
unsafe {
let plugin = ptr as *mut Plugin;
let inport = &(*plugin).in_port;
let outport = &(*plugin).output;
let buf = jack_port_get_buffer(inport.handle, jack_nframes_t);
let out = jack_port_get_buffer(outport.handle, jack_nframes_t) as *mut f32;
let event_count = jack_midi_get_event_count(buf);
let mut event = JackMidiEvent {
time: 0,
size: 0,
buffer: std::ptr::null_mut() as *mut libc::c_uchar,
};
let mut ievent = 0;
jack_midi_event_get(&mut event, buf, ievent);
for i in 0..jack_nframes_t {
if (event.time == i) & (ievent < event_count)
|
let amp = (*plugin).get_amp();
*out.offset(i as isize) = amp;
}
}
0
}
pub type Plugin<'a> = jack_plugin::jack_plugin<'a>;
fn main() {
// CString must stay alive after pointer is obtained
// see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-than-4-characters-breaks-client
let name = CString::new("yassyhost").unwrap();
let mut p = Plugin::new(&name);
p.initialize();
p.set_fs();
p.connect();
let cbpluginptr = (&p as *const Plugin) as *const libc::c_void;
unsafe {
jack_set_process_callback(p.client, process, cbpluginptr);
jack_activate(p.client);
let five = Duration::new(5, 0);
loop {
std::thread::sleep(five);
}
// jack_port_unregister(p.client, p.in_port.handle);
// jack_port_unregister(p.client, p.output.handle);
// jack_client_close(p.client);
}
}
|
{
(*plugin).midievent(&*event.buffer);
ievent = ievent + 1;
// Need to check if ievent < event_count before next call to
// jack_midi_event_get()? Don't think so, but see
// https://github.com/jackaudio/example-clients/blob/master/midisine.c
jack_midi_event_get(&mut event, buf, ievent);
}
|
conditional_block
|
main.rs
|
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate websocket;
extern crate yassy;
extern crate midi;
mod jack;
mod jack_plugin;
use jack::*;
use std::time::Duration;
|
// use websocket::message::Type;
// use websocket::header::WebSocketProtocol;
// use std::ffi::CString;
// use std::ffi::CStr;
// use std::sync::{Arc, Mutex};
// use std::sync::mpsc;
// use std::ptr;
// use jack_plugin;
// use yassy::Plugin;
extern "C" fn process(jack_nframes_t: u32, ptr: *mut libc::c_void) -> isize {
unsafe {
let plugin = ptr as *mut Plugin;
let inport = &(*plugin).in_port;
let outport = &(*plugin).output;
let buf = jack_port_get_buffer(inport.handle, jack_nframes_t);
let out = jack_port_get_buffer(outport.handle, jack_nframes_t) as *mut f32;
let event_count = jack_midi_get_event_count(buf);
let mut event = JackMidiEvent {
time: 0,
size: 0,
buffer: std::ptr::null_mut() as *mut libc::c_uchar,
};
let mut ievent = 0;
jack_midi_event_get(&mut event, buf, ievent);
for i in 0..jack_nframes_t {
if (event.time == i) & (ievent < event_count) {
(*plugin).midievent(&*event.buffer);
ievent = ievent + 1;
// Need to check if ievent < event_count before next call to
// jack_midi_event_get()? Don't think so, but see
// https://github.com/jackaudio/example-clients/blob/master/midisine.c
jack_midi_event_get(&mut event, buf, ievent);
}
let amp = (*plugin).get_amp();
*out.offset(i as isize) = amp;
}
}
0
}
pub type Plugin<'a> = jack_plugin::jack_plugin<'a>;
fn main() {
// CString must stay alive after pointer is obtained
// see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-than-4-characters-breaks-client
let name = CString::new("yassyhost").unwrap();
let mut p = Plugin::new(&name);
p.initialize();
p.set_fs();
p.connect();
let cbpluginptr = (&p as *const Plugin) as *const libc::c_void;
unsafe {
jack_set_process_callback(p.client, process, cbpluginptr);
jack_activate(p.client);
let five = Duration::new(5, 0);
loop {
std::thread::sleep(five);
}
// jack_port_unregister(p.client, p.in_port.handle);
// jack_port_unregister(p.client, p.output.handle);
// jack_client_close(p.client);
}
}
|
use std::ffi::CString;
// use std::thread;
// use websocket::{Server, Message, Sender, Receiver};
|
random_line_split
|
utils.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
// https://url.spec.whatwg.org/#fragment-percent-encode-set
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const USERINFO: &AsciiSet = &PATH
.add(b'/')
.add(b':')
|
.add(b']')
.add(b'^')
.add(b'|');
pub const HG_ENCODE_SET: &AsciiSet = &USERINFO.add(b',');
pub fn percent_encode(input: &str) -> String {
// This encode set doesn't exactly match what Python's urllib does, but it's
// close enough and importantly it encodes '=' which is the only important
// one.
utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>()
}
|
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
|
random_line_split
|
utils.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
// https://url.spec.whatwg.org/#fragment-percent-encode-set
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const USERINFO: &AsciiSet = &PATH
.add(b'/')
.add(b':')
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'|');
pub const HG_ENCODE_SET: &AsciiSet = &USERINFO.add(b',');
pub fn percent_encode(input: &str) -> String
|
{
// This encode set doesn't exactly match what Python's urllib does, but it's
// close enough and importantly it encodes '=' which is the only important
// one.
utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>()
}
|
identifier_body
|
|
utils.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
// https://url.spec.whatwg.org/#fragment-percent-encode-set
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
// https://url.spec.whatwg.org/#path-percent-encode-set
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
const USERINFO: &AsciiSet = &PATH
.add(b'/')
.add(b':')
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'|');
pub const HG_ENCODE_SET: &AsciiSet = &USERINFO.add(b',');
pub fn
|
(input: &str) -> String {
// This encode set doesn't exactly match what Python's urllib does, but it's
// close enough and importantly it encodes '=' which is the only important
// one.
utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>()
}
|
percent_encode
|
identifier_name
|
tag-align-dyn-variants.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.
// pretty-expanded FIXME #23616
use std::mem;
enum Tag<A,B> {
VarA(A),
VarB(B),
}
struct Rec<A,B> {
chA: u8,
tA: Tag<A,B>,
chB: u8,
tB: Tag<A,B>,
}
fn mk_rec<A,B>(a: A, b: B) -> Rec<A,B> {
Rec { chA:0, tA:Tag::VarA(a), chB:1, tB:Tag::VarB(b) }
}
fn is_aligned<A>(amnt: usize, u: &A) -> bool {
let p: usize = unsafe { mem::transmute(u) };
return (p & (amnt-1)) == 0;
}
fn variant_data_is_aligned<A,B>(amnt: usize, u: &Tag<A,B>) -> bool {
match u {
&Tag::VarA(ref a) => is_aligned(amnt, a),
&Tag::VarB(ref b) => is_aligned(amnt, b)
}
}
pub fn main() {
|
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u64, 23u32);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22u32, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u32, 23u32);
assert!(is_aligned(4, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(4, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22f64, 23f64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
}
|
let u64_align = std::mem::min_align_of::<u64>();
let x = mk_rec(22u64, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
|
random_line_split
|
tag-align-dyn-variants.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.
// pretty-expanded FIXME #23616
use std::mem;
enum
|
<A,B> {
VarA(A),
VarB(B),
}
struct Rec<A,B> {
chA: u8,
tA: Tag<A,B>,
chB: u8,
tB: Tag<A,B>,
}
fn mk_rec<A,B>(a: A, b: B) -> Rec<A,B> {
Rec { chA:0, tA:Tag::VarA(a), chB:1, tB:Tag::VarB(b) }
}
fn is_aligned<A>(amnt: usize, u: &A) -> bool {
let p: usize = unsafe { mem::transmute(u) };
return (p & (amnt-1)) == 0;
}
fn variant_data_is_aligned<A,B>(amnt: usize, u: &Tag<A,B>) -> bool {
match u {
&Tag::VarA(ref a) => is_aligned(amnt, a),
&Tag::VarB(ref b) => is_aligned(amnt, b)
}
}
pub fn main() {
let u64_align = std::mem::min_align_of::<u64>();
let x = mk_rec(22u64, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u64, 23u32);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22u32, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u32, 23u32);
assert!(is_aligned(4, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(4, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22f64, 23f64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
}
|
Tag
|
identifier_name
|
tag-align-dyn-variants.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.
// pretty-expanded FIXME #23616
use std::mem;
enum Tag<A,B> {
VarA(A),
VarB(B),
}
struct Rec<A,B> {
chA: u8,
tA: Tag<A,B>,
chB: u8,
tB: Tag<A,B>,
}
fn mk_rec<A,B>(a: A, b: B) -> Rec<A,B> {
Rec { chA:0, tA:Tag::VarA(a), chB:1, tB:Tag::VarB(b) }
}
fn is_aligned<A>(amnt: usize, u: &A) -> bool {
let p: usize = unsafe { mem::transmute(u) };
return (p & (amnt-1)) == 0;
}
fn variant_data_is_aligned<A,B>(amnt: usize, u: &Tag<A,B>) -> bool
|
pub fn main() {
let u64_align = std::mem::min_align_of::<u64>();
let x = mk_rec(22u64, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u64, 23u32);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22u32, 23u64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
let x = mk_rec(22u32, 23u32);
assert!(is_aligned(4, &x.tA));
assert!(variant_data_is_aligned(4, &x.tA));
assert!(is_aligned(4, &x.tB));
assert!(variant_data_is_aligned(4, &x.tB));
let x = mk_rec(22f64, 23f64);
assert!(is_aligned(u64_align, &x.tA));
assert!(variant_data_is_aligned(u64_align, &x.tA));
assert!(is_aligned(u64_align, &x.tB));
assert!(variant_data_is_aligned(u64_align, &x.tB));
}
|
{
match u {
&Tag::VarA(ref a) => is_aligned(amnt, a),
&Tag::VarB(ref b) => is_aligned(amnt, b)
}
}
|
identifier_body
|
worker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::bindings::error::{Fallible, ErrorResult};
use dom::bindings::error::Error::Syntax;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::refcounted::Trusted;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::bindings::js::Root;
use dom::window::WindowHelpers;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use devtools_traits::{DevtoolsControlMsg, DevtoolsPageInfo};
use util::str::DOMString;
use js::jsapi::{JSContext, HandleValue, RootedValue};
use js::jsapi::{JSAutoRequest, JSAutoCompartment};
use js::jsval::UndefinedValue;
use url::UrlParser;
use std::borrow::ToOwned;
use std::sync::mpsc::{channel, Sender};
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
global: GlobalField,
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
}
impl Worker {
fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
global: GlobalField::from_rooted(&global),
sender: sender,
}
}
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Root<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(Syntax),
};
let resource_task = global.resource_task();
let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone());
let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
if let Some(ref chan) = global.devtools_chan()
|
DedicatedWorkerGlobalScope::run_worker_scope(
worker_url, global.pipeline(), global.mem_profiler_chan(), global.devtools_chan(),
worker_ref, resource_task, global.script_chan(), sender, receiver);
Ok(worker)
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
data.read(global.r(), message.handle_mut());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.r().fire(target);
}
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = EventTargetCast::from_ref(worker.r());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle());
let event = EventCast::from_ref(errorevent.r());
event.fire(target);
}
}
impl<'a> WorkerMethods for &'a Worker {
fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap();
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
pub struct WorkerMessageHandler {
addr: TrustedWorkerAddress,
data: StructuredCloneData,
}
impl WorkerMessageHandler {
pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler {
WorkerMessageHandler {
addr: addr,
data: data,
}
}
}
impl Runnable for WorkerMessageHandler {
fn handler(self: Box<WorkerMessageHandler>) {
let this = *self;
Worker::handle_message(this.addr, this.data);
}
}
pub struct WorkerEventHandler {
addr: TrustedWorkerAddress,
}
impl WorkerEventHandler {
pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler {
WorkerEventHandler {
addr: addr
}
}
}
impl Runnable for WorkerEventHandler {
fn handler(self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32)
-> WorkerErrorHandler {
WorkerErrorHandler {
addr: addr,
msg: msg,
file_name: file_name,
line_num: line_num,
col_num: col_num,
}
}
}
impl Runnable for WorkerErrorHandler {
fn handler(self: Box<WorkerErrorHandler>) {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
}
}
|
{
let pipeline_id = global.pipeline();
let (devtools_sender, _) = channel();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let worker_id = global.get_next_worker_id();
chan.send(
DevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)
).unwrap();
}
|
conditional_block
|
worker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::bindings::error::{Fallible, ErrorResult};
use dom::bindings::error::Error::Syntax;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::refcounted::Trusted;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::bindings::js::Root;
use dom::window::WindowHelpers;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use devtools_traits::{DevtoolsControlMsg, DevtoolsPageInfo};
use util::str::DOMString;
use js::jsapi::{JSContext, HandleValue, RootedValue};
use js::jsapi::{JSAutoRequest, JSAutoCompartment};
use js::jsval::UndefinedValue;
use url::UrlParser;
use std::borrow::ToOwned;
use std::sync::mpsc::{channel, Sender};
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
global: GlobalField,
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
}
impl Worker {
fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
global: GlobalField::from_rooted(&global),
sender: sender,
}
}
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Root<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(Syntax),
};
let resource_task = global.resource_task();
let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone());
let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline();
let (devtools_sender, _) = channel();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let worker_id = global.get_next_worker_id();
chan.send(
DevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)
).unwrap();
}
DedicatedWorkerGlobalScope::run_worker_scope(
worker_url, global.pipeline(), global.mem_profiler_chan(), global.devtools_chan(),
worker_ref, resource_task, global.script_chan(), sender, receiver);
Ok(worker)
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
data.read(global.r(), message.handle_mut());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.r().fire(target);
}
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = EventTargetCast::from_ref(worker.r());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable,
|
event.fire(target);
}
}
impl<'a> WorkerMethods for &'a Worker {
fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap();
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
pub struct WorkerMessageHandler {
addr: TrustedWorkerAddress,
data: StructuredCloneData,
}
impl WorkerMessageHandler {
pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler {
WorkerMessageHandler {
addr: addr,
data: data,
}
}
}
impl Runnable for WorkerMessageHandler {
fn handler(self: Box<WorkerMessageHandler>) {
let this = *self;
Worker::handle_message(this.addr, this.data);
}
}
pub struct WorkerEventHandler {
addr: TrustedWorkerAddress,
}
impl WorkerEventHandler {
pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler {
WorkerEventHandler {
addr: addr
}
}
}
impl Runnable for WorkerEventHandler {
fn handler(self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32)
-> WorkerErrorHandler {
WorkerErrorHandler {
addr: addr,
msg: msg,
file_name: file_name,
line_num: line_num,
col_num: col_num,
}
}
}
impl Runnable for WorkerErrorHandler {
fn handler(self: Box<WorkerErrorHandler>) {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
}
}
|
message, filename, lineno, colno, error.handle());
let event = EventCast::from_ref(errorevent.r());
|
random_line_split
|
worker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::bindings::error::{Fallible, ErrorResult};
use dom::bindings::error::Error::Syntax;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::refcounted::Trusted;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::bindings::js::Root;
use dom::window::WindowHelpers;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use devtools_traits::{DevtoolsControlMsg, DevtoolsPageInfo};
use util::str::DOMString;
use js::jsapi::{JSContext, HandleValue, RootedValue};
use js::jsapi::{JSAutoRequest, JSAutoCompartment};
use js::jsval::UndefinedValue;
use url::UrlParser;
use std::borrow::ToOwned;
use std::sync::mpsc::{channel, Sender};
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
global: GlobalField,
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
}
impl Worker {
fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
global: GlobalField::from_rooted(&global),
sender: sender,
}
}
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Root<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(Syntax),
};
let resource_task = global.resource_task();
let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone());
let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline();
let (devtools_sender, _) = channel();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let worker_id = global.get_next_worker_id();
chan.send(
DevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)
).unwrap();
}
DedicatedWorkerGlobalScope::run_worker_scope(
worker_url, global.pipeline(), global.mem_profiler_chan(), global.devtools_chan(),
worker_ref, resource_task, global.script_chan(), sender, receiver);
Ok(worker)
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
data.read(global.r(), message.handle_mut());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.r().fire(target);
}
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = EventTargetCast::from_ref(worker.r());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle());
let event = EventCast::from_ref(errorevent.r());
event.fire(target);
}
}
impl<'a> WorkerMethods for &'a Worker {
fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap();
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
pub struct
|
{
addr: TrustedWorkerAddress,
data: StructuredCloneData,
}
impl WorkerMessageHandler {
pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler {
WorkerMessageHandler {
addr: addr,
data: data,
}
}
}
impl Runnable for WorkerMessageHandler {
fn handler(self: Box<WorkerMessageHandler>) {
let this = *self;
Worker::handle_message(this.addr, this.data);
}
}
pub struct WorkerEventHandler {
addr: TrustedWorkerAddress,
}
impl WorkerEventHandler {
pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler {
WorkerEventHandler {
addr: addr
}
}
}
impl Runnable for WorkerEventHandler {
fn handler(self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32)
-> WorkerErrorHandler {
WorkerErrorHandler {
addr: addr,
msg: msg,
file_name: file_name,
line_num: line_num,
col_num: col_num,
}
}
}
impl Runnable for WorkerErrorHandler {
fn handler(self: Box<WorkerErrorHandler>) {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
}
}
|
WorkerMessageHandler
|
identifier_name
|
worker.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::bindings::error::{Fallible, ErrorResult};
use dom::bindings::error::Error::Syntax;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::refcounted::Trusted;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::bindings::js::Root;
use dom::window::WindowHelpers;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use devtools_traits::{DevtoolsControlMsg, DevtoolsPageInfo};
use util::str::DOMString;
use js::jsapi::{JSContext, HandleValue, RootedValue};
use js::jsapi::{JSAutoRequest, JSAutoCompartment};
use js::jsval::UndefinedValue;
use url::UrlParser;
use std::borrow::ToOwned;
use std::sync::mpsc::{channel, Sender};
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
global: GlobalField,
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
}
impl Worker {
fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
global: GlobalField::from_rooted(&global),
sender: sender,
}
}
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Root<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(Syntax),
};
let resource_task = global.resource_task();
let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone());
let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
if let Some(ref chan) = global.devtools_chan() {
let pipeline_id = global.pipeline();
let (devtools_sender, _) = channel();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
let worker_id = global.get_next_worker_id();
chan.send(
DevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)), devtools_sender.clone(), page_info)
).unwrap();
}
DedicatedWorkerGlobalScope::run_worker_scope(
worker_url, global.pipeline(), global.mem_profiler_chan(), global.devtools_chan(),
worker_ref, resource_task, global.script_chan(), sender, receiver);
Ok(worker)
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
data.read(global.r(), message.handle_mut());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.r().fire(target);
}
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = EventTargetCast::from_ref(worker.r());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle());
let event = EventCast::from_ref(errorevent.r());
event.fire(target);
}
}
impl<'a> WorkerMethods for &'a Worker {
fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap();
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
pub struct WorkerMessageHandler {
addr: TrustedWorkerAddress,
data: StructuredCloneData,
}
impl WorkerMessageHandler {
pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler
|
}
impl Runnable for WorkerMessageHandler {
fn handler(self: Box<WorkerMessageHandler>) {
let this = *self;
Worker::handle_message(this.addr, this.data);
}
}
pub struct WorkerEventHandler {
addr: TrustedWorkerAddress,
}
impl WorkerEventHandler {
pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler {
WorkerEventHandler {
addr: addr
}
}
}
impl Runnable for WorkerEventHandler {
fn handler(self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32)
-> WorkerErrorHandler {
WorkerErrorHandler {
addr: addr,
msg: msg,
file_name: file_name,
line_num: line_num,
col_num: col_num,
}
}
}
impl Runnable for WorkerErrorHandler {
fn handler(self: Box<WorkerErrorHandler>) {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
}
}
|
{
WorkerMessageHandler {
addr: addr,
data: data,
}
}
|
identifier_body
|
syntax.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*! This module contains the Rust parser. It maps source text
* to token trees and to ASTs. It contains code for expanding
* macros.
*/
#[link(name = "syntax",
vers = "0.8",
uuid = "9311401b-d6ea-4cd9-a1d9-61f89499c645")];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
extern mod extra;
pub mod util {
pub mod interner;
#[cfg(test)]
pub mod parser_testing;
}
pub mod syntax {
pub use ext;
pub use parse;
}
pub mod opt_vec;
pub mod attr;
pub mod diagnostic;
pub mod codemap;
pub mod abi;
pub mod ast;
pub mod ast_util;
pub mod ast_map;
pub mod visit;
pub mod fold;
pub mod parse;
pub mod print {
|
pub mod ext {
pub mod asm;
pub mod base;
pub mod expand;
pub mod quote;
pub mod deriving;
pub mod build;
pub mod tt {
pub mod transcribe;
pub mod macro_parser;
pub mod macro_rules;
}
pub mod cfg;
pub mod fmt;
pub mod format;
pub mod env;
pub mod bytes;
pub mod concat_idents;
pub mod log_syntax;
pub mod auto_encode;
pub mod source_util;
pub mod trace_macros;
}
|
pub mod pp;
pub mod pprust;
}
|
random_line_split
|
flex_box.rs
|
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized
//! reusable boxes.
use std;
use cripes::util::flex_box::*;
#[test]
/// Test that FlexBox works for simple value types.
fn test_simple_value() {
let mut b = FlexBox::new();
{
let x = b.store(3u8);
println!("{:?}", x);
}
{
let x = b.store(vec![0x55usize;32]);
assert_eq!(*x, &[0x55usize;32]);
println!("{:?}", x);
}
{
let y = b.store("foo");
println!("{:?}", y);
}
}
#[test]
/// Test that FlexBox works for values with Drop implementations.
fn test_with_drop() {
use std::rc::Rc;
use std::ops::Drop;
use std::mem::drop;
use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize,Ordering};
let ran_drop = Rc::new(RefCell::new(AtomicUsize::new(0)));
struct HasDrop(Rc<RefCell<AtomicUsize>>);
impl Drop for HasDrop {
fn drop(&mut self)
|
}
let mut b = FlexBox::new();
{
let x = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
ran_drop.borrow().store(0, Ordering::SeqCst);
{
let x: Ref<Drop> = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
}
#[test]
/// Ensure that trait objects work.
fn test_with_trait_object() {
use std;
let mut b = FlexBox::new();
{
let y: Ref<std::fmt::Debug> = b.store("eeny meeny meiny moe");
println!("{:?}", y);
}
}
#[test]
/// Check that the iterator implementations on flex_box::Ref work as expected.
/// This is mostly a compile-time check.
fn test_with_iterator() {
let mut b = FlexBox::new();
{
let u = vec![1, 2, 3, 4];
let it: Ref<Iterator<Item=_>> = b.store(u.iter());
for x in it {
println!("{:?} ", x);
}
}
}
#[test]
/// Check that we can store items in a FlexBox indirectly. This is mostly
/// a compile-time check.
fn test_store_indirect() {
let mut b = FlexBox::new();
for x in store_and_return_iterator::<()>(&mut b) {
println!("{:?}", x);
}
}
fn store_and_return_iterator<'a,I: 'a>(b: &'a mut FlexBox) -> Ref<'a,Iterator<Item=I>> {
b.store(std::iter::empty::<I>())
}
#[test]
/// Check that we can implement traits that use FlexBox for storage,
/// potentially via chained calls to subobjects. This is mostly
/// a compile-time check.
fn test_trait_store_iterator_chained() {
trait StoresIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b, Iterator<Item=T>>
where T: 'b;
}
struct LikesIterators<T: Copy> {
//...but doesn't own them directly.
holder: HasIterator<T>
}
impl<T: Copy> StoresIterator<T> for LikesIterators<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
self.holder.give_me_an_iterator(b)
}
}
struct HasIterator<T: Copy> { value: T }
impl<T: Copy> StoresIterator<T> for HasIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
b.store(std::iter::once(self.value))
}
}
let mut b = FlexBox::new();
let hi = HasIterator{value: 2};
let likes_iterators = LikesIterators{holder: HasIterator{value: 2}};
for u in hi.give_me_an_iterator(&mut b) {
println!("{}", u);
}
for v in likes_iterators.give_me_an_iterator(&mut b) {
println!("{}", v);
}
}
|
{
println!("Goodbye, World!");
self.0.borrow_mut().fetch_add(1, Ordering::SeqCst);
}
|
identifier_body
|
flex_box.rs
|
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized
//! reusable boxes.
use std;
use cripes::util::flex_box::*;
#[test]
/// Test that FlexBox works for simple value types.
fn test_simple_value() {
let mut b = FlexBox::new();
{
let x = b.store(3u8);
println!("{:?}", x);
}
{
let x = b.store(vec![0x55usize;32]);
assert_eq!(*x, &[0x55usize;32]);
println!("{:?}", x);
}
{
let y = b.store("foo");
println!("{:?}", y);
}
}
#[test]
/// Test that FlexBox works for values with Drop implementations.
fn
|
() {
use std::rc::Rc;
use std::ops::Drop;
use std::mem::drop;
use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize,Ordering};
let ran_drop = Rc::new(RefCell::new(AtomicUsize::new(0)));
struct HasDrop(Rc<RefCell<AtomicUsize>>);
impl Drop for HasDrop {
fn drop(&mut self) {
println!("Goodbye, World!");
self.0.borrow_mut().fetch_add(1, Ordering::SeqCst);
}
}
let mut b = FlexBox::new();
{
let x = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
ran_drop.borrow().store(0, Ordering::SeqCst);
{
let x: Ref<Drop> = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
}
#[test]
/// Ensure that trait objects work.
fn test_with_trait_object() {
use std;
let mut b = FlexBox::new();
{
let y: Ref<std::fmt::Debug> = b.store("eeny meeny meiny moe");
println!("{:?}", y);
}
}
#[test]
/// Check that the iterator implementations on flex_box::Ref work as expected.
/// This is mostly a compile-time check.
fn test_with_iterator() {
let mut b = FlexBox::new();
{
let u = vec![1, 2, 3, 4];
let it: Ref<Iterator<Item=_>> = b.store(u.iter());
for x in it {
println!("{:?} ", x);
}
}
}
#[test]
/// Check that we can store items in a FlexBox indirectly. This is mostly
/// a compile-time check.
fn test_store_indirect() {
let mut b = FlexBox::new();
for x in store_and_return_iterator::<()>(&mut b) {
println!("{:?}", x);
}
}
fn store_and_return_iterator<'a,I: 'a>(b: &'a mut FlexBox) -> Ref<'a,Iterator<Item=I>> {
b.store(std::iter::empty::<I>())
}
#[test]
/// Check that we can implement traits that use FlexBox for storage,
/// potentially via chained calls to subobjects. This is mostly
/// a compile-time check.
fn test_trait_store_iterator_chained() {
trait StoresIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b, Iterator<Item=T>>
where T: 'b;
}
struct LikesIterators<T: Copy> {
//...but doesn't own them directly.
holder: HasIterator<T>
}
impl<T: Copy> StoresIterator<T> for LikesIterators<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
self.holder.give_me_an_iterator(b)
}
}
struct HasIterator<T: Copy> { value: T }
impl<T: Copy> StoresIterator<T> for HasIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
b.store(std::iter::once(self.value))
}
}
let mut b = FlexBox::new();
let hi = HasIterator{value: 2};
let likes_iterators = LikesIterators{holder: HasIterator{value: 2}};
for u in hi.give_me_an_iterator(&mut b) {
println!("{}", u);
}
for v in likes_iterators.give_me_an_iterator(&mut b) {
println!("{}", v);
}
}
|
test_with_drop
|
identifier_name
|
flex_box.rs
|
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized
//! reusable boxes.
use std;
use cripes::util::flex_box::*;
#[test]
/// Test that FlexBox works for simple value types.
fn test_simple_value() {
let mut b = FlexBox::new();
{
let x = b.store(3u8);
println!("{:?}", x);
}
{
let x = b.store(vec![0x55usize;32]);
assert_eq!(*x, &[0x55usize;32]);
println!("{:?}", x);
}
{
let y = b.store("foo");
println!("{:?}", y);
}
}
#[test]
/// Test that FlexBox works for values with Drop implementations.
fn test_with_drop() {
use std::rc::Rc;
use std::ops::Drop;
use std::mem::drop;
use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize,Ordering};
let ran_drop = Rc::new(RefCell::new(AtomicUsize::new(0)));
struct HasDrop(Rc<RefCell<AtomicUsize>>);
impl Drop for HasDrop {
fn drop(&mut self) {
println!("Goodbye, World!");
self.0.borrow_mut().fetch_add(1, Ordering::SeqCst);
}
}
let mut b = FlexBox::new();
{
let x = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
ran_drop.borrow().store(0, Ordering::SeqCst);
{
let x: Ref<Drop> = b.store(HasDrop(ran_drop.clone()));
assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) );
drop(x);
assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) );
}
}
#[test]
/// Ensure that trait objects work.
fn test_with_trait_object() {
use std;
let mut b = FlexBox::new();
{
let y: Ref<std::fmt::Debug> = b.store("eeny meeny meiny moe");
println!("{:?}", y);
}
}
#[test]
/// Check that the iterator implementations on flex_box::Ref work as expected.
/// This is mostly a compile-time check.
fn test_with_iterator() {
let mut b = FlexBox::new();
|
for x in it {
println!("{:?} ", x);
}
}
}
#[test]
/// Check that we can store items in a FlexBox indirectly. This is mostly
/// a compile-time check.
fn test_store_indirect() {
let mut b = FlexBox::new();
for x in store_and_return_iterator::<()>(&mut b) {
println!("{:?}", x);
}
}
fn store_and_return_iterator<'a,I: 'a>(b: &'a mut FlexBox) -> Ref<'a,Iterator<Item=I>> {
b.store(std::iter::empty::<I>())
}
#[test]
/// Check that we can implement traits that use FlexBox for storage,
/// potentially via chained calls to subobjects. This is mostly
/// a compile-time check.
fn test_trait_store_iterator_chained() {
trait StoresIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b, Iterator<Item=T>>
where T: 'b;
}
struct LikesIterators<T: Copy> {
//...but doesn't own them directly.
holder: HasIterator<T>
}
impl<T: Copy> StoresIterator<T> for LikesIterators<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
self.holder.give_me_an_iterator(b)
}
}
struct HasIterator<T: Copy> { value: T }
impl<T: Copy> StoresIterator<T> for HasIterator<T> {
fn give_me_an_iterator<'b>(&self, b: &'b mut FlexBox) -> Ref<'b,Iterator<Item=T>>
where T: 'b {
b.store(std::iter::once(self.value))
}
}
let mut b = FlexBox::new();
let hi = HasIterator{value: 2};
let likes_iterators = LikesIterators{holder: HasIterator{value: 2}};
for u in hi.give_me_an_iterator(&mut b) {
println!("{}", u);
}
for v in likes_iterators.give_me_an_iterator(&mut b) {
println!("{}", v);
}
}
|
{
let u = vec![1, 2, 3, 4];
let it: Ref<Iterator<Item=_>> = b.store(u.iter());
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(box_syntax, plugin, plugin_registrar, quote, rustc_private, slice_patterns)]
#![deny(unsafe_code)]
#[cfg(feature = "clippy")]
extern crate clippy_lints;
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
pub mod lints;
/// Utilities for writing plugins
mod utils;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
Symbol::intern("dom_struct"),
MultiModifier(box jstraceable::expand_dom_struct));
|
reg.register_early_lint_pass(box lints::ban::BanPass);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
reg.register_attribute("must_root".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry) {
::clippy_lints::register_plugins(reg);
}
#[cfg(not(feature = "clippy"))]
fn register_clippy(_reg: &mut Registry) {
}
|
reg.register_late_lint_pass(box lints::unrooted_must_root::UnrootedPass::new());
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(box_syntax, plugin, plugin_registrar, quote, rustc_private, slice_patterns)]
#![deny(unsafe_code)]
#[cfg(feature = "clippy")]
extern crate clippy_lints;
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
pub mod lints;
/// Utilities for writing plugins
mod utils;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(
Symbol::intern("dom_struct"),
MultiModifier(box jstraceable::expand_dom_struct));
reg.register_late_lint_pass(box lints::unrooted_must_root::UnrootedPass::new());
reg.register_early_lint_pass(box lints::ban::BanPass);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
reg.register_attribute("must_root".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry)
|
#[cfg(not(feature = "clippy"))]
fn register_clippy(_reg: &mut Registry) {
}
|
{
::clippy_lints::register_plugins(reg);
}
|
identifier_body
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(box_syntax, plugin, plugin_registrar, quote, rustc_private, slice_patterns)]
#![deny(unsafe_code)]
#[cfg(feature = "clippy")]
extern crate clippy_lints;
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
pub mod lints;
/// Utilities for writing plugins
mod utils;
#[plugin_registrar]
pub fn
|
(reg: &mut Registry) {
reg.register_syntax_extension(
Symbol::intern("dom_struct"),
MultiModifier(box jstraceable::expand_dom_struct));
reg.register_late_lint_pass(box lints::unrooted_must_root::UnrootedPass::new());
reg.register_early_lint_pass(box lints::ban::BanPass);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
reg.register_attribute("must_root".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry) {
::clippy_lints::register_plugins(reg);
}
#[cfg(not(feature = "clippy"))]
fn register_clippy(_reg: &mut Registry) {
}
|
plugin_registrar
|
identifier_name
|
windowing.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use canvas::{SurfaceProviders, WebGlExecutor};
use embedder_traits::EventLoopWaker;
use euclid::Scale;
#[cfg(feature = "gl")]
use gleam::gl;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::{PipelineId, TopLevelBrowsingContextId, TraversalDirection};
use script_traits::{MediaSessionActionType, MouseButton, TouchEventType, TouchId, WheelDelta};
use servo_geometry::DeviceIndependentPixel;
use servo_media::player::context::{GlApi, GlContext, NativeDisplay};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
#[cfg(feature = "gl")]
use std::rc::Rc;
use std::time::Duration;
use style_traits::DevicePixel;
use rust_webvr::VRServiceManager;
use webrender_api::units::DevicePoint;
use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
use webrender_api::ScrollLocation;
use webvr_traits::WebVRMainThreadHeartbeat;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, DevicePoint),
MouseDown(MouseButton, DevicePoint),
MouseUp(MouseButton, DevicePoint),
}
/// Various debug and profiling flags that WebRender supports.
#[derive(Clone)]
pub enum
|
{
Profiler,
TextureCacheDebug,
RenderTargetDebug,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent when the window is resized.
Resize,
/// Sent when a navigation request from script is allowed/refused.
AllowNavigationResponse(PipelineId, bool),
/// Sent when a new URL is to be loaded.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(DevicePoint),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, DevicePoint),
/// Sent when user moves the mouse wheel.
Wheel(WheelDelta, DevicePoint),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, DeviceIntPoint, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(TopLevelBrowsingContextId, TraversalDirection),
/// Sent when the user quits the application
Quit,
/// Sent when the user exits from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Sent when a key input state changes
Keyboard(KeyboardEvent),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload(TopLevelBrowsingContextId),
/// Create a new top level browsing context
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make a top level browsing context visible, hiding the previous
/// visible one.
SelectBrowser(TopLevelBrowsingContextId),
/// Toggles a debug flag in WebRender
ToggleWebRenderDebug(WebRenderDebugOption),
/// Capture current WebRender
CaptureWebRender,
/// Toggle sampling profiler with the given sampling rate and max duration.
ToggleSamplingProfiler(Duration, Duration),
/// Sent when the user triggers a media action through the UA exposed media UI
/// (play, pause, seek, etc.).
MediaSessionAction(MediaSessionActionType),
/// Set browser visibility. A hidden browser will not tick the animations.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize => write!(f, "Resize"),
WindowEvent::Keyboard(..) => write!(f, "Keyboard"),
WindowEvent::AllowNavigationResponse(..) => write!(f, "AllowNavigationResponse"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Wheel(..) => write!(f, "Wheel"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload(..) => write!(f, "Reload"),
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SendError(..) => write!(f, "SendError"),
WindowEvent::CloseBrowser(..) => write!(f, "CloseBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
WindowEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"),
WindowEvent::CaptureWebRender => write!(f, "CaptureWebRender"),
WindowEvent::ToggleSamplingProfiler(..) => write!(f, "ToggleSamplingProfiler"),
WindowEvent::ExitFullScreen(..) => write!(f, "ExitFullScreen"),
WindowEvent::MediaSessionAction(..) => write!(f, "MediaSessionAction"),
WindowEvent::ChangeBrowserVisibility(..) => write!(f, "ChangeBrowserVisibility"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationState {
Idle,
Animating,
}
pub trait WindowMethods {
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Make the OpenGL context current.
fn make_gl_context_current(&self);
/// Return the GL function pointer trait.
#[cfg(feature = "gl")]
fn gl(&self) -> Rc<dyn gl::Gl>;
/// Get the coordinates of the native window, the screen and the framebuffer.
fn get_coordinates(&self) -> EmbedderCoordinates;
/// Set whether the application is currently animating.
/// Typically, when animations are active, the window
/// will want to avoid blocking on UI events, and just
/// run the event loop at the vsync interval.
fn set_animation_state(&self, _state: AnimationState);
/// Get the GL context
fn get_gl_context(&self) -> GlContext;
/// Get the native display
fn get_native_display(&self) -> NativeDisplay;
/// Get the GL api
fn get_gl_api(&self) -> GlApi;
}
pub trait EmbedderMethods {
/// Returns a thread-safe object to wake up the window's event loop.
fn create_event_loop_waker(&mut self) -> Box<dyn EventLoopWaker>;
/// Register services with a VRServiceManager.
fn register_vr_services(
&mut self,
_: &mut VRServiceManager,
_: &mut Vec<Box<dyn WebVRMainThreadHeartbeat>>,
) {
}
/// Register services with a WebXR Registry.
fn register_webxr(
&mut self,
_: &mut webxr::MainThreadRegistry,
_: WebGlExecutor,
_: SurfaceProviders,
) {
}
}
#[derive(Clone, Copy, Debug)]
pub struct EmbedderCoordinates {
/// The pixel density of the display.
pub hidpi_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
/// Size of the screen.
pub screen: DeviceIntSize,
/// Size of the available screen space (screen without toolbars and docks).
pub screen_avail: DeviceIntSize,
/// Size of the native window.
pub window: (DeviceIntSize, DeviceIntPoint),
/// Size of the GL buffer in the window.
pub framebuffer: DeviceIntSize,
/// Coordinates of the document within the framebuffer.
pub viewport: DeviceIntRect,
}
impl EmbedderCoordinates {
pub fn get_flipped_viewport(&self) -> DeviceIntRect {
let fb_height = self.framebuffer.height;
let mut view = self.viewport.clone();
view.origin.y = fb_height - view.origin.y - view.size.height;
DeviceIntRect::from_untyped(&view.to_untyped())
}
}
|
WebRenderDebugOption
|
identifier_name
|
windowing.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use canvas::{SurfaceProviders, WebGlExecutor};
use embedder_traits::EventLoopWaker;
use euclid::Scale;
#[cfg(feature = "gl")]
use gleam::gl;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::{PipelineId, TopLevelBrowsingContextId, TraversalDirection};
use script_traits::{MediaSessionActionType, MouseButton, TouchEventType, TouchId, WheelDelta};
use servo_geometry::DeviceIndependentPixel;
use servo_media::player::context::{GlApi, GlContext, NativeDisplay};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
#[cfg(feature = "gl")]
use std::rc::Rc;
use std::time::Duration;
use style_traits::DevicePixel;
use rust_webvr::VRServiceManager;
use webrender_api::units::DevicePoint;
use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
use webrender_api::ScrollLocation;
use webvr_traits::WebVRMainThreadHeartbeat;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, DevicePoint),
MouseDown(MouseButton, DevicePoint),
MouseUp(MouseButton, DevicePoint),
}
/// Various debug and profiling flags that WebRender supports.
#[derive(Clone)]
pub enum WebRenderDebugOption {
Profiler,
TextureCacheDebug,
RenderTargetDebug,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent when the window is resized.
Resize,
/// Sent when a navigation request from script is allowed/refused.
AllowNavigationResponse(PipelineId, bool),
/// Sent when a new URL is to be loaded.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(DevicePoint),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, DevicePoint),
/// Sent when user moves the mouse wheel.
Wheel(WheelDelta, DevicePoint),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, DeviceIntPoint, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(TopLevelBrowsingContextId, TraversalDirection),
/// Sent when the user quits the application
Quit,
/// Sent when the user exits from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Sent when a key input state changes
Keyboard(KeyboardEvent),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload(TopLevelBrowsingContextId),
/// Create a new top level browsing context
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make a top level browsing context visible, hiding the previous
/// visible one.
SelectBrowser(TopLevelBrowsingContextId),
/// Toggles a debug flag in WebRender
ToggleWebRenderDebug(WebRenderDebugOption),
/// Capture current WebRender
CaptureWebRender,
/// Toggle sampling profiler with the given sampling rate and max duration.
ToggleSamplingProfiler(Duration, Duration),
/// Sent when the user triggers a media action through the UA exposed media UI
/// (play, pause, seek, etc.).
MediaSessionAction(MediaSessionActionType),
/// Set browser visibility. A hidden browser will not tick the animations.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize => write!(f, "Resize"),
WindowEvent::Keyboard(..) => write!(f, "Keyboard"),
WindowEvent::AllowNavigationResponse(..) => write!(f, "AllowNavigationResponse"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Wheel(..) => write!(f, "Wheel"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload(..) => write!(f, "Reload"),
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SendError(..) => write!(f, "SendError"),
WindowEvent::CloseBrowser(..) => write!(f, "CloseBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
WindowEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"),
WindowEvent::CaptureWebRender => write!(f, "CaptureWebRender"),
WindowEvent::ToggleSamplingProfiler(..) => write!(f, "ToggleSamplingProfiler"),
WindowEvent::ExitFullScreen(..) => write!(f, "ExitFullScreen"),
WindowEvent::MediaSessionAction(..) => write!(f, "MediaSessionAction"),
WindowEvent::ChangeBrowserVisibility(..) => write!(f, "ChangeBrowserVisibility"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationState {
Idle,
Animating,
}
pub trait WindowMethods {
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Make the OpenGL context current.
fn make_gl_context_current(&self);
/// Return the GL function pointer trait.
#[cfg(feature = "gl")]
fn gl(&self) -> Rc<dyn gl::Gl>;
/// Get the coordinates of the native window, the screen and the framebuffer.
fn get_coordinates(&self) -> EmbedderCoordinates;
/// Set whether the application is currently animating.
/// Typically, when animations are active, the window
/// will want to avoid blocking on UI events, and just
/// run the event loop at the vsync interval.
fn set_animation_state(&self, _state: AnimationState);
/// Get the GL context
fn get_gl_context(&self) -> GlContext;
/// Get the native display
fn get_native_display(&self) -> NativeDisplay;
/// Get the GL api
fn get_gl_api(&self) -> GlApi;
}
pub trait EmbedderMethods {
/// Returns a thread-safe object to wake up the window's event loop.
fn create_event_loop_waker(&mut self) -> Box<dyn EventLoopWaker>;
/// Register services with a VRServiceManager.
fn register_vr_services(
&mut self,
_: &mut VRServiceManager,
_: &mut Vec<Box<dyn WebVRMainThreadHeartbeat>>,
) {
}
/// Register services with a WebXR Registry.
fn register_webxr(
&mut self,
_: &mut webxr::MainThreadRegistry,
_: WebGlExecutor,
_: SurfaceProviders,
) {
}
}
#[derive(Clone, Copy, Debug)]
pub struct EmbedderCoordinates {
/// The pixel density of the display.
pub hidpi_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
/// Size of the screen.
pub screen: DeviceIntSize,
/// Size of the available screen space (screen without toolbars and docks).
pub screen_avail: DeviceIntSize,
/// Size of the native window.
pub window: (DeviceIntSize, DeviceIntPoint),
/// Size of the GL buffer in the window.
pub framebuffer: DeviceIntSize,
/// Coordinates of the document within the framebuffer.
pub viewport: DeviceIntRect,
}
impl EmbedderCoordinates {
pub fn get_flipped_viewport(&self) -> DeviceIntRect
|
}
|
{
let fb_height = self.framebuffer.height;
let mut view = self.viewport.clone();
view.origin.y = fb_height - view.origin.y - view.size.height;
DeviceIntRect::from_untyped(&view.to_untyped())
}
|
identifier_body
|
windowing.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use canvas::{SurfaceProviders, WebGlExecutor};
use embedder_traits::EventLoopWaker;
use euclid::Scale;
#[cfg(feature = "gl")]
use gleam::gl;
use keyboard_types::KeyboardEvent;
use msg::constellation_msg::{PipelineId, TopLevelBrowsingContextId, TraversalDirection};
use script_traits::{MediaSessionActionType, MouseButton, TouchEventType, TouchId, WheelDelta};
use servo_geometry::DeviceIndependentPixel;
use servo_media::player::context::{GlApi, GlContext, NativeDisplay};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
#[cfg(feature = "gl")]
use std::rc::Rc;
use std::time::Duration;
use style_traits::DevicePixel;
use rust_webvr::VRServiceManager;
use webrender_api::units::DevicePoint;
use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
use webrender_api::ScrollLocation;
use webvr_traits::WebVRMainThreadHeartbeat;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, DevicePoint),
MouseDown(MouseButton, DevicePoint),
MouseUp(MouseButton, DevicePoint),
}
/// Various debug and profiling flags that WebRender supports.
#[derive(Clone)]
pub enum WebRenderDebugOption {
Profiler,
TextureCacheDebug,
RenderTargetDebug,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent when the window is resized.
Resize,
/// Sent when a navigation request from script is allowed/refused.
AllowNavigationResponse(PipelineId, bool),
/// Sent when a new URL is to be loaded.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(DevicePoint),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, DevicePoint),
/// Sent when user moves the mouse wheel.
Wheel(WheelDelta, DevicePoint),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, DeviceIntPoint, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(TopLevelBrowsingContextId, TraversalDirection),
/// Sent when the user quits the application
Quit,
/// Sent when the user exits from fullscreen mode
ExitFullScreen(TopLevelBrowsingContextId),
/// Sent when a key input state changes
Keyboard(KeyboardEvent),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload(TopLevelBrowsingContextId),
/// Create a new top level browsing context
NewBrowser(ServoUrl, TopLevelBrowsingContextId),
/// Close a top level browsing context
CloseBrowser(TopLevelBrowsingContextId),
/// Panic a top level browsing context.
SendError(Option<TopLevelBrowsingContextId>, String),
/// Make a top level browsing context visible, hiding the previous
/// visible one.
SelectBrowser(TopLevelBrowsingContextId),
/// Toggles a debug flag in WebRender
ToggleWebRenderDebug(WebRenderDebugOption),
/// Capture current WebRender
CaptureWebRender,
/// Toggle sampling profiler with the given sampling rate and max duration.
ToggleSamplingProfiler(Duration, Duration),
/// Sent when the user triggers a media action through the UA exposed media UI
/// (play, pause, seek, etc.).
MediaSessionAction(MediaSessionActionType),
/// Set browser visibility. A hidden browser will not tick the animations.
ChangeBrowserVisibility(TopLevelBrowsingContextId, bool),
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize => write!(f, "Resize"),
WindowEvent::Keyboard(..) => write!(f, "Keyboard"),
WindowEvent::AllowNavigationResponse(..) => write!(f, "AllowNavigationResponse"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Wheel(..) => write!(f, "Wheel"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload(..) => write!(f, "Reload"),
|
WindowEvent::CloseBrowser(..) => write!(f, "CloseBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
WindowEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"),
WindowEvent::CaptureWebRender => write!(f, "CaptureWebRender"),
WindowEvent::ToggleSamplingProfiler(..) => write!(f, "ToggleSamplingProfiler"),
WindowEvent::ExitFullScreen(..) => write!(f, "ExitFullScreen"),
WindowEvent::MediaSessionAction(..) => write!(f, "MediaSessionAction"),
WindowEvent::ChangeBrowserVisibility(..) => write!(f, "ChangeBrowserVisibility"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationState {
Idle,
Animating,
}
pub trait WindowMethods {
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Make the OpenGL context current.
fn make_gl_context_current(&self);
/// Return the GL function pointer trait.
#[cfg(feature = "gl")]
fn gl(&self) -> Rc<dyn gl::Gl>;
/// Get the coordinates of the native window, the screen and the framebuffer.
fn get_coordinates(&self) -> EmbedderCoordinates;
/// Set whether the application is currently animating.
/// Typically, when animations are active, the window
/// will want to avoid blocking on UI events, and just
/// run the event loop at the vsync interval.
fn set_animation_state(&self, _state: AnimationState);
/// Get the GL context
fn get_gl_context(&self) -> GlContext;
/// Get the native display
fn get_native_display(&self) -> NativeDisplay;
/// Get the GL api
fn get_gl_api(&self) -> GlApi;
}
pub trait EmbedderMethods {
/// Returns a thread-safe object to wake up the window's event loop.
fn create_event_loop_waker(&mut self) -> Box<dyn EventLoopWaker>;
/// Register services with a VRServiceManager.
fn register_vr_services(
&mut self,
_: &mut VRServiceManager,
_: &mut Vec<Box<dyn WebVRMainThreadHeartbeat>>,
) {
}
/// Register services with a WebXR Registry.
fn register_webxr(
&mut self,
_: &mut webxr::MainThreadRegistry,
_: WebGlExecutor,
_: SurfaceProviders,
) {
}
}
#[derive(Clone, Copy, Debug)]
pub struct EmbedderCoordinates {
/// The pixel density of the display.
pub hidpi_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
/// Size of the screen.
pub screen: DeviceIntSize,
/// Size of the available screen space (screen without toolbars and docks).
pub screen_avail: DeviceIntSize,
/// Size of the native window.
pub window: (DeviceIntSize, DeviceIntPoint),
/// Size of the GL buffer in the window.
pub framebuffer: DeviceIntSize,
/// Coordinates of the document within the framebuffer.
pub viewport: DeviceIntRect,
}
impl EmbedderCoordinates {
pub fn get_flipped_viewport(&self) -> DeviceIntRect {
let fb_height = self.framebuffer.height;
let mut view = self.viewport.clone();
view.origin.y = fb_height - view.origin.y - view.size.height;
DeviceIntRect::from_untyped(&view.to_untyped())
}
}
|
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SendError(..) => write!(f, "SendError"),
|
random_line_split
|
account.rs
|
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// 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.
use crate::client::MDataInfo;
use crate::crypto::{shared_box, shared_secretbox, shared_sign};
use crate::errors::CoreError;
use crate::DIR_TAG;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use routing::{FullId, XorName, XOR_NAME_LEN};
use rust_sodium::crypto::sign::Seed;
use rust_sodium::crypto::{box_, pwhash, secretbox, sign};
use tiny_keccak::sha3_256;
/// Representing the User Account information on the network.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Account {
/// The User Account Keys.
pub maid_keys: ClientKeys,
/// The user's access container.
pub access_container: MDataInfo,
/// The user's configuration directory.
pub config_root: MDataInfo,
/// Set to `true` when all root and standard containers
/// have been created successfully. `false` signifies that
/// previous attempt might have failed - check on login.
pub root_dirs_created: bool,
}
impl Account {
/// Create new Account with a provided set of keys.
pub fn new(maid_keys: ClientKeys) -> Result<Self, CoreError> {
Ok(Account {
maid_keys,
access_container: MDataInfo::random_private(DIR_TAG)?,
config_root: MDataInfo::random_private(DIR_TAG)?,
root_dirs_created: false,
})
}
/// Symmetric encryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn encrypt(&self, password: &[u8], pin: &[u8]) -> Result<Vec<u8>, CoreError> {
let serialised_self = serialise(self)?;
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
Ok(secretbox::seal(&serialised_self, &nonce, &key))
}
/// Symmetric decryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn decrypt(encrypted_self: &[u8], password: &[u8], pin: &[u8]) -> Result<Self, CoreError> {
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
let decrypted_self = secretbox::open(encrypted_self, &nonce, &key)
.map_err(|_| CoreError::SymmetricDecipherFailure)?;
Ok(deserialise(&decrypted_self)?)
}
/// Generate User's Identity for the network using supplied credentials in
/// a deterministic way. This is similar to the username in various places.
pub fn generate_network_id(keyword: &[u8], pin: &[u8]) -> Result<XorName, CoreError> {
let mut id = XorName([0; XOR_NAME_LEN]);
Self::derive_key(&mut id.0[..], keyword, pin)?;
Ok(id)
}
fn generate_crypto_keys(
password: &[u8],
pin: &[u8],
) -> Result<(secretbox::Key, secretbox::Nonce), CoreError> {
let mut output = [0; secretbox::KEYBYTES + secretbox::NONCEBYTES];
Self::derive_key(&mut output[..], password, pin)?;
// OK to unwrap here, as we guaranteed the slices have the correct length.
let key = unwrap!(secretbox::Key::from_slice(&output[..secretbox::KEYBYTES]));
let nonce = unwrap!(secretbox::Nonce::from_slice(&output[secretbox::KEYBYTES..]));
Ok((key, nonce))
}
fn derive_key(output: &mut [u8], input: &[u8], user_salt: &[u8]) -> Result<(), CoreError> {
let mut salt = pwhash::Salt([0; pwhash::SALTBYTES]);
{
let pwhash::Salt(ref mut salt_bytes) = salt;
if salt_bytes.len() == 32 {
let hashed_pin = sha3_256(user_salt);
for it in salt_bytes.iter_mut().enumerate() {
*it.1 = hashed_pin[it.0];
}
} else {
return Err(CoreError::UnsupportedSaltSizeForPwHash);
}
}
pwhash::derive_key(
output,
input,
&salt,
pwhash::OPSLIMIT_INTERACTIVE,
pwhash::MEMLIMIT_INTERACTIVE,
)
.map(|_| ())
.map_err(|_| CoreError::UnsuccessfulPwHash)
}
}
/// Client signing and encryption keypairs
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ClientKeys {
/// Signing public key
pub sign_pk: sign::PublicKey,
/// Signing secret key
pub sign_sk: shared_sign::SecretKey,
/// Encryption public key
pub enc_pk: box_::PublicKey,
/// Encryption private key
pub enc_sk: shared_box::SecretKey,
/// Symmetric encryption key
pub enc_key: shared_secretbox::Key,
}
impl ClientKeys {
/// Construct new `ClientKeys`
pub fn new(seed: Option<&Seed>) -> Self {
let sign = match seed {
Some(s) => shared_sign::keypair_from_seed(s),
None => shared_sign::gen_keypair(),
};
let enc = shared_box::gen_keypair();
let enc_key = shared_secretbox::gen_key();
ClientKeys {
sign_pk: sign.0,
sign_sk: sign.1,
enc_pk: enc.0,
enc_sk: enc.1,
enc_key,
}
}
}
impl Default for ClientKeys {
fn
|
() -> Self {
Self::new(None)
}
}
impl Into<FullId> for ClientKeys {
fn into(self) -> FullId {
let enc_sk = (*self.enc_sk).clone();
let sign_sk = (*self.sign_sk).clone();
FullId::with_keys((self.enc_pk, enc_sk), (self.sign_pk, sign_sk))
}
}
#[cfg(test)]
mod tests {
use super::*;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use std::u32;
// Test deterministically generating User's Identity for the network using supplied credentials.
#[test]
fn generate_network_id() {
let keyword1 = b"user1";
let user1_id1 = unwrap!(Account::generate_network_id(keyword1, b"0"));
let user1_id2 = unwrap!(Account::generate_network_id(keyword1, b"1234"));
let user1_id3 = unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(user1_id1, user1_id2);
assert_ne!(user1_id1, user1_id3);
assert_ne!(user1_id2, user1_id3);
assert_eq!(
user1_id1,
unwrap!(Account::generate_network_id(keyword1, b"0"))
);
assert_eq!(
user1_id2,
unwrap!(Account::generate_network_id(keyword1, b"1234"))
);
assert_eq!(
user1_id3,
unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
))
);
let keyword2 = b"user2";
let user1_id = unwrap!(Account::generate_network_id(keyword1, b"248"));
let user2_id = unwrap!(Account::generate_network_id(keyword2, b"248"));
assert_ne!(user1_id, user2_id);
}
// Test deterministically generating cryptographic keys.
#[test]
fn generate_crypto_keys() {
let password1 = b"super great password";
let password2 = b"even better password";
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"1234"));
let keys3 = unwrap!(Account::generate_crypto_keys(
password1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(keys1, keys2);
assert_ne!(keys1, keys3);
assert_ne!(keys2, keys3);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password2, b"0"));
assert_ne!(keys1, keys2);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
assert_eq!(keys1, keys2);
}
// Test serialising and deserialising accounts.
#[test]
fn serialisation() {
let account = unwrap!(Account::new(ClientKeys::new(None)));
let encoded = unwrap!(serialise(&account));
let decoded: Account = unwrap!(deserialise(&encoded));
assert_eq!(decoded, account);
}
// Test encryption and decryption of accounts.
#[test]
fn encryption() {
let account = unwrap!(Account::new(ClientKeys::new(None)));
let password = b"impossible to guess";
let pin = b"1000";
let encrypted = unwrap!(account.encrypt(password, pin));
let encoded = unwrap!(serialise(&account));
assert!(!encrypted.is_empty());
assert_ne!(encrypted, encoded);
let decrypted = unwrap!(Account::decrypt(&encrypted, password, pin));
assert_eq!(account, decrypted);
}
}
|
default
|
identifier_name
|
account.rs
|
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// 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.
use crate::client::MDataInfo;
use crate::crypto::{shared_box, shared_secretbox, shared_sign};
use crate::errors::CoreError;
use crate::DIR_TAG;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use routing::{FullId, XorName, XOR_NAME_LEN};
use rust_sodium::crypto::sign::Seed;
use rust_sodium::crypto::{box_, pwhash, secretbox, sign};
use tiny_keccak::sha3_256;
/// Representing the User Account information on the network.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Account {
/// The User Account Keys.
pub maid_keys: ClientKeys,
/// The user's access container.
pub access_container: MDataInfo,
/// The user's configuration directory.
pub config_root: MDataInfo,
/// Set to `true` when all root and standard containers
/// have been created successfully. `false` signifies that
/// previous attempt might have failed - check on login.
pub root_dirs_created: bool,
}
impl Account {
/// Create new Account with a provided set of keys.
pub fn new(maid_keys: ClientKeys) -> Result<Self, CoreError> {
Ok(Account {
maid_keys,
access_container: MDataInfo::random_private(DIR_TAG)?,
config_root: MDataInfo::random_private(DIR_TAG)?,
root_dirs_created: false,
})
}
/// Symmetric encryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn encrypt(&self, password: &[u8], pin: &[u8]) -> Result<Vec<u8>, CoreError> {
let serialised_self = serialise(self)?;
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
Ok(secretbox::seal(&serialised_self, &nonce, &key))
}
/// Symmetric decryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn decrypt(encrypted_self: &[u8], password: &[u8], pin: &[u8]) -> Result<Self, CoreError> {
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
let decrypted_self = secretbox::open(encrypted_self, &nonce, &key)
.map_err(|_| CoreError::SymmetricDecipherFailure)?;
Ok(deserialise(&decrypted_self)?)
}
/// Generate User's Identity for the network using supplied credentials in
/// a deterministic way. This is similar to the username in various places.
pub fn generate_network_id(keyword: &[u8], pin: &[u8]) -> Result<XorName, CoreError> {
let mut id = XorName([0; XOR_NAME_LEN]);
Self::derive_key(&mut id.0[..], keyword, pin)?;
Ok(id)
}
fn generate_crypto_keys(
password: &[u8],
pin: &[u8],
) -> Result<(secretbox::Key, secretbox::Nonce), CoreError> {
let mut output = [0; secretbox::KEYBYTES + secretbox::NONCEBYTES];
Self::derive_key(&mut output[..], password, pin)?;
// OK to unwrap here, as we guaranteed the slices have the correct length.
let key = unwrap!(secretbox::Key::from_slice(&output[..secretbox::KEYBYTES]));
let nonce = unwrap!(secretbox::Nonce::from_slice(&output[secretbox::KEYBYTES..]));
Ok((key, nonce))
}
fn derive_key(output: &mut [u8], input: &[u8], user_salt: &[u8]) -> Result<(), CoreError> {
let mut salt = pwhash::Salt([0; pwhash::SALTBYTES]);
{
let pwhash::Salt(ref mut salt_bytes) = salt;
if salt_bytes.len() == 32 {
let hashed_pin = sha3_256(user_salt);
for it in salt_bytes.iter_mut().enumerate() {
*it.1 = hashed_pin[it.0];
}
} else {
return Err(CoreError::UnsupportedSaltSizeForPwHash);
}
|
pwhash::derive_key(
output,
input,
&salt,
pwhash::OPSLIMIT_INTERACTIVE,
pwhash::MEMLIMIT_INTERACTIVE,
)
.map(|_| ())
.map_err(|_| CoreError::UnsuccessfulPwHash)
}
}
/// Client signing and encryption keypairs
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ClientKeys {
/// Signing public key
pub sign_pk: sign::PublicKey,
/// Signing secret key
pub sign_sk: shared_sign::SecretKey,
/// Encryption public key
pub enc_pk: box_::PublicKey,
/// Encryption private key
pub enc_sk: shared_box::SecretKey,
/// Symmetric encryption key
pub enc_key: shared_secretbox::Key,
}
impl ClientKeys {
/// Construct new `ClientKeys`
pub fn new(seed: Option<&Seed>) -> Self {
let sign = match seed {
Some(s) => shared_sign::keypair_from_seed(s),
None => shared_sign::gen_keypair(),
};
let enc = shared_box::gen_keypair();
let enc_key = shared_secretbox::gen_key();
ClientKeys {
sign_pk: sign.0,
sign_sk: sign.1,
enc_pk: enc.0,
enc_sk: enc.1,
enc_key,
}
}
}
impl Default for ClientKeys {
fn default() -> Self {
Self::new(None)
}
}
impl Into<FullId> for ClientKeys {
fn into(self) -> FullId {
let enc_sk = (*self.enc_sk).clone();
let sign_sk = (*self.sign_sk).clone();
FullId::with_keys((self.enc_pk, enc_sk), (self.sign_pk, sign_sk))
}
}
#[cfg(test)]
mod tests {
use super::*;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use std::u32;
// Test deterministically generating User's Identity for the network using supplied credentials.
#[test]
fn generate_network_id() {
let keyword1 = b"user1";
let user1_id1 = unwrap!(Account::generate_network_id(keyword1, b"0"));
let user1_id2 = unwrap!(Account::generate_network_id(keyword1, b"1234"));
let user1_id3 = unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(user1_id1, user1_id2);
assert_ne!(user1_id1, user1_id3);
assert_ne!(user1_id2, user1_id3);
assert_eq!(
user1_id1,
unwrap!(Account::generate_network_id(keyword1, b"0"))
);
assert_eq!(
user1_id2,
unwrap!(Account::generate_network_id(keyword1, b"1234"))
);
assert_eq!(
user1_id3,
unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
))
);
let keyword2 = b"user2";
let user1_id = unwrap!(Account::generate_network_id(keyword1, b"248"));
let user2_id = unwrap!(Account::generate_network_id(keyword2, b"248"));
assert_ne!(user1_id, user2_id);
}
// Test deterministically generating cryptographic keys.
#[test]
fn generate_crypto_keys() {
let password1 = b"super great password";
let password2 = b"even better password";
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"1234"));
let keys3 = unwrap!(Account::generate_crypto_keys(
password1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(keys1, keys2);
assert_ne!(keys1, keys3);
assert_ne!(keys2, keys3);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password2, b"0"));
assert_ne!(keys1, keys2);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
assert_eq!(keys1, keys2);
}
// Test serialising and deserialising accounts.
#[test]
fn serialisation() {
let account = unwrap!(Account::new(ClientKeys::new(None)));
let encoded = unwrap!(serialise(&account));
let decoded: Account = unwrap!(deserialise(&encoded));
assert_eq!(decoded, account);
}
// Test encryption and decryption of accounts.
#[test]
fn encryption() {
let account = unwrap!(Account::new(ClientKeys::new(None)));
let password = b"impossible to guess";
let pin = b"1000";
let encrypted = unwrap!(account.encrypt(password, pin));
let encoded = unwrap!(serialise(&account));
assert!(!encrypted.is_empty());
assert_ne!(encrypted, encoded);
let decrypted = unwrap!(Account::decrypt(&encrypted, password, pin));
assert_eq!(account, decrypted);
}
}
|
}
|
random_line_split
|
account.rs
|
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// 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.
use crate::client::MDataInfo;
use crate::crypto::{shared_box, shared_secretbox, shared_sign};
use crate::errors::CoreError;
use crate::DIR_TAG;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use routing::{FullId, XorName, XOR_NAME_LEN};
use rust_sodium::crypto::sign::Seed;
use rust_sodium::crypto::{box_, pwhash, secretbox, sign};
use tiny_keccak::sha3_256;
/// Representing the User Account information on the network.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Account {
/// The User Account Keys.
pub maid_keys: ClientKeys,
/// The user's access container.
pub access_container: MDataInfo,
/// The user's configuration directory.
pub config_root: MDataInfo,
/// Set to `true` when all root and standard containers
/// have been created successfully. `false` signifies that
/// previous attempt might have failed - check on login.
pub root_dirs_created: bool,
}
impl Account {
/// Create new Account with a provided set of keys.
pub fn new(maid_keys: ClientKeys) -> Result<Self, CoreError> {
Ok(Account {
maid_keys,
access_container: MDataInfo::random_private(DIR_TAG)?,
config_root: MDataInfo::random_private(DIR_TAG)?,
root_dirs_created: false,
})
}
/// Symmetric encryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn encrypt(&self, password: &[u8], pin: &[u8]) -> Result<Vec<u8>, CoreError> {
let serialised_self = serialise(self)?;
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
Ok(secretbox::seal(&serialised_self, &nonce, &key))
}
/// Symmetric decryption of Account using User's credentials.
/// Credentials are passed through key-derivation-function first
pub fn decrypt(encrypted_self: &[u8], password: &[u8], pin: &[u8]) -> Result<Self, CoreError> {
let (key, nonce) = Self::generate_crypto_keys(password, pin)?;
let decrypted_self = secretbox::open(encrypted_self, &nonce, &key)
.map_err(|_| CoreError::SymmetricDecipherFailure)?;
Ok(deserialise(&decrypted_self)?)
}
/// Generate User's Identity for the network using supplied credentials in
/// a deterministic way. This is similar to the username in various places.
pub fn generate_network_id(keyword: &[u8], pin: &[u8]) -> Result<XorName, CoreError> {
let mut id = XorName([0; XOR_NAME_LEN]);
Self::derive_key(&mut id.0[..], keyword, pin)?;
Ok(id)
}
fn generate_crypto_keys(
password: &[u8],
pin: &[u8],
) -> Result<(secretbox::Key, secretbox::Nonce), CoreError> {
let mut output = [0; secretbox::KEYBYTES + secretbox::NONCEBYTES];
Self::derive_key(&mut output[..], password, pin)?;
// OK to unwrap here, as we guaranteed the slices have the correct length.
let key = unwrap!(secretbox::Key::from_slice(&output[..secretbox::KEYBYTES]));
let nonce = unwrap!(secretbox::Nonce::from_slice(&output[secretbox::KEYBYTES..]));
Ok((key, nonce))
}
fn derive_key(output: &mut [u8], input: &[u8], user_salt: &[u8]) -> Result<(), CoreError> {
let mut salt = pwhash::Salt([0; pwhash::SALTBYTES]);
{
let pwhash::Salt(ref mut salt_bytes) = salt;
if salt_bytes.len() == 32 {
let hashed_pin = sha3_256(user_salt);
for it in salt_bytes.iter_mut().enumerate() {
*it.1 = hashed_pin[it.0];
}
} else {
return Err(CoreError::UnsupportedSaltSizeForPwHash);
}
}
pwhash::derive_key(
output,
input,
&salt,
pwhash::OPSLIMIT_INTERACTIVE,
pwhash::MEMLIMIT_INTERACTIVE,
)
.map(|_| ())
.map_err(|_| CoreError::UnsuccessfulPwHash)
}
}
/// Client signing and encryption keypairs
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ClientKeys {
/// Signing public key
pub sign_pk: sign::PublicKey,
/// Signing secret key
pub sign_sk: shared_sign::SecretKey,
/// Encryption public key
pub enc_pk: box_::PublicKey,
/// Encryption private key
pub enc_sk: shared_box::SecretKey,
/// Symmetric encryption key
pub enc_key: shared_secretbox::Key,
}
impl ClientKeys {
/// Construct new `ClientKeys`
pub fn new(seed: Option<&Seed>) -> Self {
let sign = match seed {
Some(s) => shared_sign::keypair_from_seed(s),
None => shared_sign::gen_keypair(),
};
let enc = shared_box::gen_keypair();
let enc_key = shared_secretbox::gen_key();
ClientKeys {
sign_pk: sign.0,
sign_sk: sign.1,
enc_pk: enc.0,
enc_sk: enc.1,
enc_key,
}
}
}
impl Default for ClientKeys {
fn default() -> Self {
Self::new(None)
}
}
impl Into<FullId> for ClientKeys {
fn into(self) -> FullId {
let enc_sk = (*self.enc_sk).clone();
let sign_sk = (*self.sign_sk).clone();
FullId::with_keys((self.enc_pk, enc_sk), (self.sign_pk, sign_sk))
}
}
#[cfg(test)]
mod tests {
use super::*;
use maidsafe_utilities::serialisation::{deserialise, serialise};
use std::u32;
// Test deterministically generating User's Identity for the network using supplied credentials.
#[test]
fn generate_network_id() {
let keyword1 = b"user1";
let user1_id1 = unwrap!(Account::generate_network_id(keyword1, b"0"));
let user1_id2 = unwrap!(Account::generate_network_id(keyword1, b"1234"));
let user1_id3 = unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(user1_id1, user1_id2);
assert_ne!(user1_id1, user1_id3);
assert_ne!(user1_id2, user1_id3);
assert_eq!(
user1_id1,
unwrap!(Account::generate_network_id(keyword1, b"0"))
);
assert_eq!(
user1_id2,
unwrap!(Account::generate_network_id(keyword1, b"1234"))
);
assert_eq!(
user1_id3,
unwrap!(Account::generate_network_id(
keyword1,
u32::MAX.to_string().as_bytes(),
))
);
let keyword2 = b"user2";
let user1_id = unwrap!(Account::generate_network_id(keyword1, b"248"));
let user2_id = unwrap!(Account::generate_network_id(keyword2, b"248"));
assert_ne!(user1_id, user2_id);
}
// Test deterministically generating cryptographic keys.
#[test]
fn generate_crypto_keys() {
let password1 = b"super great password";
let password2 = b"even better password";
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"1234"));
let keys3 = unwrap!(Account::generate_crypto_keys(
password1,
u32::MAX.to_string().as_bytes(),
));
assert_ne!(keys1, keys2);
assert_ne!(keys1, keys3);
assert_ne!(keys2, keys3);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password2, b"0"));
assert_ne!(keys1, keys2);
let keys1 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
let keys2 = unwrap!(Account::generate_crypto_keys(password1, b"0"));
assert_eq!(keys1, keys2);
}
// Test serialising and deserialising accounts.
#[test]
fn serialisation() {
let account = unwrap!(Account::new(ClientKeys::new(None)));
let encoded = unwrap!(serialise(&account));
let decoded: Account = unwrap!(deserialise(&encoded));
assert_eq!(decoded, account);
}
// Test encryption and decryption of accounts.
#[test]
fn encryption()
|
}
|
{
let account = unwrap!(Account::new(ClientKeys::new(None)));
let password = b"impossible to guess";
let pin = b"1000";
let encrypted = unwrap!(account.encrypt(password, pin));
let encoded = unwrap!(serialise(&account));
assert!(!encrypted.is_empty());
assert_ne!(encrypted, encoded);
let decrypted = unwrap!(Account::decrypt(&encrypted, password, pin));
assert_eq!(account, decrypted);
}
|
identifier_body
|
message.rs
|
use std::error::Error;
// general notifications
define_msg! { pub CannotReadConfig:
"ko" => "프로젝트에서 `kailua.json`이나 `.vscode/kailua.json`을 읽을 수 없습니다. \
이번 세션에서 타입 체크가 비활성화됩니다.",
_ => "Cannot read `kailua.json` or `.vscode/kailua.json` in the project; \
type checking is disabled for this session.",
}
define_msg! { pub NoStartPath:
"ko" => "`kailua.json`에 시작 경로가 지정되어 있지 않습니다. \
이번 세션에서 타입 체크가 비활성화됩니다.",
_ => "There is no start path specified in `kailua.json`; \
type checking is disabled for this session.",
}
define_msg! { pub CannotRename:
"ko" => "이 이름은 고칠 수 없습니다.",
_ => "You cannot rename this name.",
}
// reports generated by language server
define_msg! { pub RestartRequired:
"ko" => "`kailua.json`에 문제가 있습니다. 고친 뒤 세션을 재시작해 주십시오",
_ => "`kailua.json` has an issue; please fix it and restart the session",
}
define_msg! { pub CannotOpenStartPath<'a> { error: &'a Error }:
"ko" => "시작 경로를 열 수 없습니다. (이유: {error})",
_ => "Couldn't open a start path. (Cause: {error})",
|
}
define_msg! { pub OmittedSelfLabel:
"ko" => "<생략됨>",
_ => "<omitted>",
}
|
random_line_split
|
|
field_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{black_box, Bencher, Criterion};
use oppai_field::construct_field::construct_moves;
use oppai_field::field::{self, Field, Pos};
use oppai_field::player::Player;
use oppai_field::zobrist::Zobrist;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256PlusPlus;
use std::sync::Arc;
const SEED_1: u64 = 3;
const SEED_2: u64 = 5;
const SEED_3: u64 = 7;
fn random_game(bencher: &mut Bencher, width: u32, height: u32, seed: u64) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
let mut moves = (field::min_pos(width)..field::max_pos(width, height) + 1).collect::<Vec<Pos>>();
moves.shuffle(&mut rng);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
let mut player = Player::Red;
for &pos in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
player = player.next();
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn random_game_1(c: &mut Criterion) {
c.bench_function("random_game_1", |bencher| random_game(bencher, 30, 30, SEED_1));
}
fn random_game_2(c: &mut Criterion) {
c.bench_function("random_game_2", |bencher| random_game(bencher, 30, 30, SEED_2));
}
fn random_game_3(c: &mut Criterion) {
c.bench_function("random_game_3", |bencher| random_game(bencher, 30, 30, SEED_3));
}
fn game(bencher: &mut Bencher, width: u32, height: u32, moves: Vec<(Player, Pos)>) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(SEED_1);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
for &(player, pos) in black_box(&moves) {
if field.is_putting_allowed(pos) {
|
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn game_without_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
..............
.aDFgjMOprUWx.
.BceHKlnQStvY.
..............
",
);
c.bench_function("game_without_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
fn game_with_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
.........
....R....
...QhS...
..PgCjT..
.OfBaDkU.
..ZnElV..
...YmW...
....X....
.........
",
);
c.bench_function("game_with_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
criterion_group!(random_games, random_game_1, random_game_2, random_game_3);
criterion_group!(games, game_without_surroundings, game_with_surroundings);
criterion_main!(random_games, games);
|
field.put_point(pos, player);
}
|
random_line_split
|
field_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{black_box, Bencher, Criterion};
use oppai_field::construct_field::construct_moves;
use oppai_field::field::{self, Field, Pos};
use oppai_field::player::Player;
use oppai_field::zobrist::Zobrist;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256PlusPlus;
use std::sync::Arc;
const SEED_1: u64 = 3;
const SEED_2: u64 = 5;
const SEED_3: u64 = 7;
fn random_game(bencher: &mut Bencher, width: u32, height: u32, seed: u64) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
let mut moves = (field::min_pos(width)..field::max_pos(width, height) + 1).collect::<Vec<Pos>>();
moves.shuffle(&mut rng);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
let mut player = Player::Red;
for &pos in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
player = player.next();
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn random_game_1(c: &mut Criterion) {
c.bench_function("random_game_1", |bencher| random_game(bencher, 30, 30, SEED_1));
}
fn random_game_2(c: &mut Criterion) {
c.bench_function("random_game_2", |bencher| random_game(bencher, 30, 30, SEED_2));
}
fn random_game_3(c: &mut Criterion)
|
fn game(bencher: &mut Bencher, width: u32, height: u32, moves: Vec<(Player, Pos)>) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(SEED_1);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
for &(player, pos) in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn game_without_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
..............
.aDFgjMOprUWx.
.BceHKlnQStvY.
..............
",
);
c.bench_function("game_without_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
fn game_with_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
.........
....R....
...QhS...
..PgCjT..
.OfBaDkU.
..ZnElV..
...YmW...
....X....
.........
",
);
c.bench_function("game_with_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
criterion_group!(random_games, random_game_1, random_game_2, random_game_3);
criterion_group!(games, game_without_surroundings, game_with_surroundings);
criterion_main!(random_games, games);
|
{
c.bench_function("random_game_3", |bencher| random_game(bencher, 30, 30, SEED_3));
}
|
identifier_body
|
field_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{black_box, Bencher, Criterion};
use oppai_field::construct_field::construct_moves;
use oppai_field::field::{self, Field, Pos};
use oppai_field::player::Player;
use oppai_field::zobrist::Zobrist;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256PlusPlus;
use std::sync::Arc;
const SEED_1: u64 = 3;
const SEED_2: u64 = 5;
const SEED_3: u64 = 7;
fn random_game(bencher: &mut Bencher, width: u32, height: u32, seed: u64) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
let mut moves = (field::min_pos(width)..field::max_pos(width, height) + 1).collect::<Vec<Pos>>();
moves.shuffle(&mut rng);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
let mut player = Player::Red;
for &pos in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
player = player.next();
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn
|
(c: &mut Criterion) {
c.bench_function("random_game_1", |bencher| random_game(bencher, 30, 30, SEED_1));
}
fn random_game_2(c: &mut Criterion) {
c.bench_function("random_game_2", |bencher| random_game(bencher, 30, 30, SEED_2));
}
fn random_game_3(c: &mut Criterion) {
c.bench_function("random_game_3", |bencher| random_game(bencher, 30, 30, SEED_3));
}
fn game(bencher: &mut Bencher, width: u32, height: u32, moves: Vec<(Player, Pos)>) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(SEED_1);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
for &(player, pos) in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn game_without_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
..............
.aDFgjMOprUWx.
.BceHKlnQStvY.
..............
",
);
c.bench_function("game_without_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
fn game_with_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
.........
....R....
...QhS...
..PgCjT..
.OfBaDkU.
..ZnElV..
...YmW...
....X....
.........
",
);
c.bench_function("game_with_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
criterion_group!(random_games, random_game_1, random_game_2, random_game_3);
criterion_group!(games, game_without_surroundings, game_with_surroundings);
criterion_main!(random_games, games);
|
random_game_1
|
identifier_name
|
field_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{black_box, Bencher, Criterion};
use oppai_field::construct_field::construct_moves;
use oppai_field::field::{self, Field, Pos};
use oppai_field::player::Player;
use oppai_field::zobrist::Zobrist;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256PlusPlus;
use std::sync::Arc;
const SEED_1: u64 = 3;
const SEED_2: u64 = 5;
const SEED_3: u64 = 7;
fn random_game(bencher: &mut Bencher, width: u32, height: u32, seed: u64) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
let mut moves = (field::min_pos(width)..field::max_pos(width, height) + 1).collect::<Vec<Pos>>();
moves.shuffle(&mut rng);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
let mut player = Player::Red;
for &pos in black_box(&moves) {
if field.is_putting_allowed(pos) {
field.put_point(pos, player);
player = player.next();
}
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn random_game_1(c: &mut Criterion) {
c.bench_function("random_game_1", |bencher| random_game(bencher, 30, 30, SEED_1));
}
fn random_game_2(c: &mut Criterion) {
c.bench_function("random_game_2", |bencher| random_game(bencher, 30, 30, SEED_2));
}
fn random_game_3(c: &mut Criterion) {
c.bench_function("random_game_3", |bencher| random_game(bencher, 30, 30, SEED_3));
}
fn game(bencher: &mut Bencher, width: u32, height: u32, moves: Vec<(Player, Pos)>) {
let mut rng = Xoshiro256PlusPlus::seed_from_u64(SEED_1);
let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng));
bencher.iter(|| {
let mut field = Field::new(width, height, zobrist.clone());
for &(player, pos) in black_box(&moves) {
if field.is_putting_allowed(pos)
|
}
for _ in 0..field.moves_count() {
field.undo();
}
field
});
}
fn game_without_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
..............
.aDFgjMOprUWx.
.BceHKlnQStvY.
..............
",
);
c.bench_function("game_without_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
fn game_with_surroundings(c: &mut Criterion) {
let (width, height, moves) = construct_moves(
"
.........
....R....
...QhS...
..PgCjT..
.OfBaDkU.
..ZnElV..
...YmW...
....X....
.........
",
);
c.bench_function("game_with_surroundings", |bencher| {
game(bencher, width, height, moves.clone())
});
}
criterion_group!(random_games, random_game_1, random_game_2, random_game_3);
criterion_group!(games, game_without_surroundings, game_with_surroundings);
criterion_main!(random_games, games);
|
{
field.put_point(pos, player);
}
|
conditional_block
|
mod.rs
|
mod codec;
mod handshake;
pub use self::codec::ApCodec;
pub use self::handshake::handshake;
use std::io::{self, ErrorKind};
use std::net::ToSocketAddrs;
use futures_util::{SinkExt, StreamExt};
use protobuf::{self, Message, ProtobufError};
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use url::Url;
use crate::authentication::Credentials;
use crate::protocol::keyexchange::{APLoginFailed, ErrorCode};
use crate::proxytunnel;
use crate::version;
pub type Transport = Framed<TcpStream, ApCodec>;
fn login_error_message(code: &ErrorCode) -> &'static str {
pub use ErrorCode::*;
match code {
ProtocolError => "Protocol error",
TryAnotherAP => "Try another AP",
BadConnectionId => "Bad connection id",
TravelRestriction => "Travel restriction",
PremiumAccountRequired => "Premium account required",
BadCredentials => "Bad credentials",
CouldNotValidateCredentials => "Could not validate credentials",
AccountExists => "Account exists",
ExtraVerificationRequired => "Extra verification required",
InvalidAppKey => "Invalid app key",
ApplicationBanned => "Application banned",
}
|
#[derive(Debug, Error)]
pub enum AuthenticationError {
#[error("Login failed with reason: {}", login_error_message(.0))]
LoginFailed(ErrorCode),
#[error("Authentication failed: {0}")]
IoError(#[from] io::Error),
}
impl From<ProtobufError> for AuthenticationError {
fn from(e: ProtobufError) -> Self {
io::Error::new(ErrorKind::InvalidData, e).into()
}
}
impl From<APLoginFailed> for AuthenticationError {
fn from(login_failure: APLoginFailed) -> Self {
Self::LoginFailed(login_failure.get_error_code())
}
}
pub async fn connect(addr: String, proxy: Option<&Url>) -> io::Result<Transport> {
let socket = if let Some(proxy_url) = proxy {
info!("Using proxy \"{}\"", proxy_url);
let socket_addr = proxy_url.socket_addrs(|| None).and_then(|addrs| {
addrs.into_iter().next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve proxy server address",
)
})
})?;
let socket = TcpStream::connect(&socket_addr).await?;
let uri = addr.parse::<http::Uri>().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"Can't parse access point address",
)
})?;
let host = uri.host().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no hostname",
)
})?;
let port = uri.port().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no port",
)
})?;
proxytunnel::proxy_connect(socket, host, port.as_str()).await?
} else {
let socket_addr = addr.to_socket_addrs()?.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve access point address",
)
})?;
TcpStream::connect(&socket_addr).await?
};
handshake(socket).await
}
pub async fn authenticate(
transport: &mut Transport,
credentials: Credentials,
device_id: &str,
) -> Result<Credentials, AuthenticationError> {
use crate::protocol::authentication::{APWelcome, ClientResponseEncrypted, CpuFamily, Os};
let mut packet = ClientResponseEncrypted::new();
packet
.mut_login_credentials()
.set_username(credentials.username);
packet
.mut_login_credentials()
.set_typ(credentials.auth_type);
packet
.mut_login_credentials()
.set_auth_data(credentials.auth_data);
packet
.mut_system_info()
.set_cpu_family(CpuFamily::CPU_UNKNOWN);
packet.mut_system_info().set_os(Os::OS_UNKNOWN);
packet
.mut_system_info()
.set_system_information_string(format!(
"librespot_{}_{}",
version::SHA_SHORT,
version::BUILD_ID
));
packet
.mut_system_info()
.set_device_id(device_id.to_string());
packet.set_version_string(version::VERSION_STRING.to_string());
let cmd = 0xab;
let data = packet.write_to_bytes().unwrap();
transport.send((cmd, data)).await?;
let (cmd, data) = transport.next().await.expect("EOF")?;
match cmd {
0xac => {
let welcome_data = APWelcome::parse_from_bytes(data.as_ref())?;
let reusable_credentials = Credentials {
username: welcome_data.get_canonical_username().to_owned(),
auth_type: welcome_data.get_reusable_auth_credentials_type(),
auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),
};
Ok(reusable_credentials)
}
0xad => {
let error_data = APLoginFailed::parse_from_bytes(data.as_ref())?;
Err(error_data.into())
}
_ => {
let msg = format!("Received invalid packet: {}", cmd);
Err(io::Error::new(ErrorKind::InvalidData, msg).into())
}
}
}
|
}
|
random_line_split
|
mod.rs
|
mod codec;
mod handshake;
pub use self::codec::ApCodec;
pub use self::handshake::handshake;
use std::io::{self, ErrorKind};
use std::net::ToSocketAddrs;
use futures_util::{SinkExt, StreamExt};
use protobuf::{self, Message, ProtobufError};
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use url::Url;
use crate::authentication::Credentials;
use crate::protocol::keyexchange::{APLoginFailed, ErrorCode};
use crate::proxytunnel;
use crate::version;
pub type Transport = Framed<TcpStream, ApCodec>;
fn login_error_message(code: &ErrorCode) -> &'static str {
pub use ErrorCode::*;
match code {
ProtocolError => "Protocol error",
TryAnotherAP => "Try another AP",
BadConnectionId => "Bad connection id",
TravelRestriction => "Travel restriction",
PremiumAccountRequired => "Premium account required",
BadCredentials => "Bad credentials",
CouldNotValidateCredentials => "Could not validate credentials",
AccountExists => "Account exists",
ExtraVerificationRequired => "Extra verification required",
InvalidAppKey => "Invalid app key",
ApplicationBanned => "Application banned",
}
}
#[derive(Debug, Error)]
pub enum AuthenticationError {
#[error("Login failed with reason: {}", login_error_message(.0))]
LoginFailed(ErrorCode),
#[error("Authentication failed: {0}")]
IoError(#[from] io::Error),
}
impl From<ProtobufError> for AuthenticationError {
fn
|
(e: ProtobufError) -> Self {
io::Error::new(ErrorKind::InvalidData, e).into()
}
}
impl From<APLoginFailed> for AuthenticationError {
fn from(login_failure: APLoginFailed) -> Self {
Self::LoginFailed(login_failure.get_error_code())
}
}
pub async fn connect(addr: String, proxy: Option<&Url>) -> io::Result<Transport> {
let socket = if let Some(proxy_url) = proxy {
info!("Using proxy \"{}\"", proxy_url);
let socket_addr = proxy_url.socket_addrs(|| None).and_then(|addrs| {
addrs.into_iter().next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve proxy server address",
)
})
})?;
let socket = TcpStream::connect(&socket_addr).await?;
let uri = addr.parse::<http::Uri>().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"Can't parse access point address",
)
})?;
let host = uri.host().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no hostname",
)
})?;
let port = uri.port().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no port",
)
})?;
proxytunnel::proxy_connect(socket, host, port.as_str()).await?
} else {
let socket_addr = addr.to_socket_addrs()?.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve access point address",
)
})?;
TcpStream::connect(&socket_addr).await?
};
handshake(socket).await
}
pub async fn authenticate(
transport: &mut Transport,
credentials: Credentials,
device_id: &str,
) -> Result<Credentials, AuthenticationError> {
use crate::protocol::authentication::{APWelcome, ClientResponseEncrypted, CpuFamily, Os};
let mut packet = ClientResponseEncrypted::new();
packet
.mut_login_credentials()
.set_username(credentials.username);
packet
.mut_login_credentials()
.set_typ(credentials.auth_type);
packet
.mut_login_credentials()
.set_auth_data(credentials.auth_data);
packet
.mut_system_info()
.set_cpu_family(CpuFamily::CPU_UNKNOWN);
packet.mut_system_info().set_os(Os::OS_UNKNOWN);
packet
.mut_system_info()
.set_system_information_string(format!(
"librespot_{}_{}",
version::SHA_SHORT,
version::BUILD_ID
));
packet
.mut_system_info()
.set_device_id(device_id.to_string());
packet.set_version_string(version::VERSION_STRING.to_string());
let cmd = 0xab;
let data = packet.write_to_bytes().unwrap();
transport.send((cmd, data)).await?;
let (cmd, data) = transport.next().await.expect("EOF")?;
match cmd {
0xac => {
let welcome_data = APWelcome::parse_from_bytes(data.as_ref())?;
let reusable_credentials = Credentials {
username: welcome_data.get_canonical_username().to_owned(),
auth_type: welcome_data.get_reusable_auth_credentials_type(),
auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),
};
Ok(reusable_credentials)
}
0xad => {
let error_data = APLoginFailed::parse_from_bytes(data.as_ref())?;
Err(error_data.into())
}
_ => {
let msg = format!("Received invalid packet: {}", cmd);
Err(io::Error::new(ErrorKind::InvalidData, msg).into())
}
}
}
|
from
|
identifier_name
|
self-impl.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
// Test that unsupported uses of `Self` in impls don't crash
struct Bar;
trait Foo {
type Baz;
}
trait SuperFoo {
type SuperBaz;
}
impl Foo for Bar {
type Baz = bool;
}
impl SuperFoo for Bar {
type SuperBaz = bool;
}
impl Bar {
fn f() {
let _: <Self>::Baz = true;
//~^ ERROR ambiguous associated type
let _: Self::Baz = true;
//~^ ERROR ambiguous associated type
}
}
fn main() {}
|
random_line_split
|
|
self-impl.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that unsupported uses of `Self` in impls don't crash
struct
|
;
trait Foo {
type Baz;
}
trait SuperFoo {
type SuperBaz;
}
impl Foo for Bar {
type Baz = bool;
}
impl SuperFoo for Bar {
type SuperBaz = bool;
}
impl Bar {
fn f() {
let _: <Self>::Baz = true;
//~^ ERROR ambiguous associated type
let _: Self::Baz = true;
//~^ ERROR ambiguous associated type
}
}
fn main() {}
|
Bar
|
identifier_name
|
macros.rs
|
macro_rules! irq_handler {
($idt:expr, $irq:expr, $irq_handler:ident) => {{
extern "x86-interrupt" fn base_handler(_: &mut ExceptionStackFrame) {
// Base handler. Push and pop context between call to handler implementation.
unsafe {
asm!("push rbp
push r15
push r14
push r13
push r12
push r11
push r10
push r9
push r8
push rsi
push rdi
push rdx
push rcx
push rbx
push rax
mov rdi, rsp
call $0
pop rax
pop rbx
pop rcx
pop rdx
pop rdi
pop rsi
pop r8
pop r9
pop r10
pop r11
pop r12
pop r13
pop r14
pop r15
pop rbp" :: "s"(base_handler_impl as unsafe fn(_)) :: "volatile", "intel");
}
}
unsafe fn base_handler_impl(context: *mut TaskContext) {
// Call the interrupt specific handler
$irq_handler();
PIC.send_end_of_interrupt($irq);
// Perform any rescheduling thats required
let scheduler = &mut *kget().scheduler.get();
if scheduler.need_resched() {
let context_ref = &mut *context;
scheduler.schedule(context_ref);
|
$idt.interrupts[$irq].set_handler_fn(base_handler);
}}
}
|
}
}
|
random_line_split
|
attr_iterator.rs
|
// Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use glib::translate::*;
use glib_sys;
use pango_sys;
use AttrIterator;
use Attribute;
use FontDescription;
use Language;
use std::ptr;
impl AttrIterator {
pub fn
|
(
&mut self,
desc: &mut FontDescription,
language: Option<&Language>,
extra_attrs: &[&Attribute],
) {
unsafe {
let stash_vec: Vec<_> = extra_attrs.iter().rev().map(|v| v.to_glib_none()).collect();
let mut list: *mut glib_sys::GSList = ptr::null_mut();
for stash in &stash_vec {
list = glib_sys::g_slist_prepend(list, Ptr::to(stash.0));
}
pango_sys::pango_attr_iterator_get_font(
self.to_glib_none_mut().0,
desc.to_glib_none_mut().0,
&mut language.to_glib_none().0,
&mut list,
);
}
}
}
|
get_font
|
identifier_name
|
attr_iterator.rs
|
// Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use glib::translate::*;
use glib_sys;
use pango_sys;
use AttrIterator;
use Attribute;
use FontDescription;
use Language;
use std::ptr;
impl AttrIterator {
pub fn get_font(
&mut self,
desc: &mut FontDescription,
language: Option<&Language>,
extra_attrs: &[&Attribute],
) {
unsafe {
let stash_vec: Vec<_> = extra_attrs.iter().rev().map(|v| v.to_glib_none()).collect();
let mut list: *mut glib_sys::GSList = ptr::null_mut();
for stash in &stash_vec {
list = glib_sys::g_slist_prepend(list, Ptr::to(stash.0));
}
pango_sys::pango_attr_iterator_get_font(
self.to_glib_none_mut().0,
desc.to_glib_none_mut().0,
&mut language.to_glib_none().0,
&mut list,
|
}
|
);
}
}
|
random_line_split
|
attr_iterator.rs
|
// Copyright 2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use glib::translate::*;
use glib_sys;
use pango_sys;
use AttrIterator;
use Attribute;
use FontDescription;
use Language;
use std::ptr;
impl AttrIterator {
pub fn get_font(
&mut self,
desc: &mut FontDescription,
language: Option<&Language>,
extra_attrs: &[&Attribute],
)
|
}
|
{
unsafe {
let stash_vec: Vec<_> = extra_attrs.iter().rev().map(|v| v.to_glib_none()).collect();
let mut list: *mut glib_sys::GSList = ptr::null_mut();
for stash in &stash_vec {
list = glib_sys::g_slist_prepend(list, Ptr::to(stash.0));
}
pango_sys::pango_attr_iterator_get_font(
self.to_glib_none_mut().0,
desc.to_glib_none_mut().0,
&mut language.to_glib_none().0,
&mut list,
);
}
}
|
identifier_body
|
paging.rs
|
//! Definitions for paging structures
use ::core::mem::size_of;
use arch::x86_64::x86::paging;
pub trait Level {
type Table;
fn new() -> Self::Table;
}
trait ParentLevel: Level {
type Child;
}
pub enum PML4Table {}
pub enum PDPTTable {}
pub enum PDTable {}
pub enum PTTable {}
impl Level for PML4Table {
type Table = paging::PML4;
fn new() -> paging::PML4 {
[paging::PML4Entry::empty(); 512]
}
}
impl Level for PDPTTable {
type Table = paging::PDPT;
fn new() -> paging::PDPT {
[paging::PDPTEntry::empty(); 512]
}
}
impl Level for PDTable {
type Table = paging::PD;
fn new() -> paging::PD {
[paging::PDEntry::empty(); 512]
}
}
impl Level for PTTable {
type Table = paging::PT;
|
pub struct Table<L: Level> {
tables: L::Table,
}
pub type PML4 = Table<PML4Table>;
pub type PDPT = Table<PDPTTable>;
pub type PD = Table<PDTable>;
pub type PT = Table<PTTable>;
impl<L: Level> Table<L> {
pub fn mem_align() -> usize {
size_of::<L::Table>()
}
}
impl<L: Level> Default for Table<L> {
fn default() -> Table<L> {
Table { tables: L::new() }
}
}
|
fn new() -> paging::PT {
[paging::PTEntry::empty(); 512]
}
}
|
random_line_split
|
paging.rs
|
//! Definitions for paging structures
use ::core::mem::size_of;
use arch::x86_64::x86::paging;
pub trait Level {
type Table;
fn new() -> Self::Table;
}
trait ParentLevel: Level {
type Child;
}
pub enum PML4Table {}
pub enum PDPTTable {}
pub enum PDTable {}
pub enum PTTable {}
impl Level for PML4Table {
type Table = paging::PML4;
fn new() -> paging::PML4 {
[paging::PML4Entry::empty(); 512]
}
}
impl Level for PDPTTable {
type Table = paging::PDPT;
fn new() -> paging::PDPT {
[paging::PDPTEntry::empty(); 512]
}
}
impl Level for PDTable {
type Table = paging::PD;
fn new() -> paging::PD {
[paging::PDEntry::empty(); 512]
}
}
impl Level for PTTable {
type Table = paging::PT;
fn new() -> paging::PT {
[paging::PTEntry::empty(); 512]
}
}
pub struct Table<L: Level> {
tables: L::Table,
}
pub type PML4 = Table<PML4Table>;
pub type PDPT = Table<PDPTTable>;
pub type PD = Table<PDTable>;
pub type PT = Table<PTTable>;
impl<L: Level> Table<L> {
pub fn mem_align() -> usize {
size_of::<L::Table>()
}
}
impl<L: Level> Default for Table<L> {
fn default() -> Table<L>
|
}
|
{
Table { tables: L::new() }
}
|
identifier_body
|
paging.rs
|
//! Definitions for paging structures
use ::core::mem::size_of;
use arch::x86_64::x86::paging;
pub trait Level {
type Table;
fn new() -> Self::Table;
}
trait ParentLevel: Level {
type Child;
}
pub enum PML4Table {}
pub enum PDPTTable {}
pub enum PDTable {}
pub enum PTTable {}
impl Level for PML4Table {
type Table = paging::PML4;
fn
|
() -> paging::PML4 {
[paging::PML4Entry::empty(); 512]
}
}
impl Level for PDPTTable {
type Table = paging::PDPT;
fn new() -> paging::PDPT {
[paging::PDPTEntry::empty(); 512]
}
}
impl Level for PDTable {
type Table = paging::PD;
fn new() -> paging::PD {
[paging::PDEntry::empty(); 512]
}
}
impl Level for PTTable {
type Table = paging::PT;
fn new() -> paging::PT {
[paging::PTEntry::empty(); 512]
}
}
pub struct Table<L: Level> {
tables: L::Table,
}
pub type PML4 = Table<PML4Table>;
pub type PDPT = Table<PDPTTable>;
pub type PD = Table<PDTable>;
pub type PT = Table<PTTable>;
impl<L: Level> Table<L> {
pub fn mem_align() -> usize {
size_of::<L::Table>()
}
}
impl<L: Level> Default for Table<L> {
fn default() -> Table<L> {
Table { tables: L::new() }
}
}
|
new
|
identifier_name
|
border.rs
|
// Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib::translate::*;
use std::fmt;
use std::ops;
glib_wrapper! {
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Border(Boxed<ffi::GtkBorder>);
match fn {
copy => |ptr| ffi::gtk_border_copy(mut_override(ptr)),
free => |ptr| ffi::gtk_border_free(ptr),
get_type => || ffi::gtk_border_get_type(),
}
}
impl ops::Deref for Border {
type Target = ffi::GtkBorder;
fn deref(&self) -> &Self::Target {
&(*self.0)
}
}
impl ops::DerefMut for Border {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut (*self.0)
}
}
impl Border {
pub fn
|
() -> Border {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_border_new())
}
}
}
impl Default for Border {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Border {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.debug_struct("Border")
.field("left", &self.left)
.field("right", &self.right)
.field("top", &self.top)
.field("bottom", &self.bottom)
.finish()
}
}
|
new
|
identifier_name
|
border.rs
|
// Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib::translate::*;
use std::fmt;
use std::ops;
glib_wrapper! {
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Border(Boxed<ffi::GtkBorder>);
match fn {
copy => |ptr| ffi::gtk_border_copy(mut_override(ptr)),
free => |ptr| ffi::gtk_border_free(ptr),
get_type => || ffi::gtk_border_get_type(),
}
}
impl ops::Deref for Border {
type Target = ffi::GtkBorder;
fn deref(&self) -> &Self::Target {
&(*self.0)
}
}
|
fn deref_mut(&mut self) -> &mut Self::Target {
&mut (*self.0)
}
}
impl Border {
pub fn new() -> Border {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_border_new())
}
}
}
impl Default for Border {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Border {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.debug_struct("Border")
.field("left", &self.left)
.field("right", &self.right)
.field("top", &self.top)
.field("bottom", &self.bottom)
.finish()
}
}
|
impl ops::DerefMut for Border {
|
random_line_split
|
border.rs
|
// Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib::translate::*;
use std::fmt;
use std::ops;
glib_wrapper! {
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Border(Boxed<ffi::GtkBorder>);
match fn {
copy => |ptr| ffi::gtk_border_copy(mut_override(ptr)),
free => |ptr| ffi::gtk_border_free(ptr),
get_type => || ffi::gtk_border_get_type(),
}
}
impl ops::Deref for Border {
type Target = ffi::GtkBorder;
fn deref(&self) -> &Self::Target {
&(*self.0)
}
}
impl ops::DerefMut for Border {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut (*self.0)
}
}
impl Border {
pub fn new() -> Border {
assert_initialized_main_thread!();
unsafe {
from_glib_full(ffi::gtk_border_new())
}
}
}
impl Default for Border {
fn default() -> Self
|
}
impl fmt::Debug for Border {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.debug_struct("Border")
.field("left", &self.left)
.field("right", &self.right)
.field("top", &self.top)
.field("bottom", &self.bottom)
.finish()
}
}
|
{
Self::new()
}
|
identifier_body
|
index.rs
|
use super::asc::Asc;
|
use super::desc::Desc;
use crate::cmd;
use crate::proto::{Command, Query};
use serde::Serialize;
#[derive(Debug, Clone)]
pub struct Index(pub(crate) Command);
#[derive(Serialize)]
struct Inner<'a> {
index: Query<'a>,
}
pub trait Arg {
fn arg(self) -> cmd::Arg<()>;
}
impl<T> Arg for T
where
T: Into<String>,
{
fn arg(self) -> cmd::Arg<()> {
let cmd = Command::from_json(self.into());
Command::from_json(Inner { index: Query(&cmd) }).into_arg()
}
}
impl Arg for Asc {
fn arg(self) -> cmd::Arg<()> {
let Asc(index) = self;
Command::from_json(Inner {
index: Query(&index),
})
.into_arg()
}
}
impl Arg for Desc {
fn arg(self) -> cmd::Arg<()> {
let Desc(index) = self;
Command::from_json(Inner {
index: Query(&index),
})
.into_arg()
}
}
|
random_line_split
|
|
index.rs
|
use super::asc::Asc;
use super::desc::Desc;
use crate::cmd;
use crate::proto::{Command, Query};
use serde::Serialize;
#[derive(Debug, Clone)]
pub struct Index(pub(crate) Command);
#[derive(Serialize)]
struct Inner<'a> {
index: Query<'a>,
}
pub trait Arg {
fn arg(self) -> cmd::Arg<()>;
}
impl<T> Arg for T
where
T: Into<String>,
{
fn arg(self) -> cmd::Arg<()> {
let cmd = Command::from_json(self.into());
Command::from_json(Inner { index: Query(&cmd) }).into_arg()
}
}
impl Arg for Asc {
fn
|
(self) -> cmd::Arg<()> {
let Asc(index) = self;
Command::from_json(Inner {
index: Query(&index),
})
.into_arg()
}
}
impl Arg for Desc {
fn arg(self) -> cmd::Arg<()> {
let Desc(index) = self;
Command::from_json(Inner {
index: Query(&index),
})
.into_arg()
}
}
|
arg
|
identifier_name
|
adding_prob_src.rs
|
extern crate rand;
use rand::distributions::{Range, IndependentSample};
use af;
use af::{Array, Dim4, MatProp, DType};
use std::cell::{RefCell, Cell};
use initializations::uniform;
use utils;
use data::{Data, DataSource, DataParams, Normalize, Shuffle};
pub struct AddingProblemSource {
pub params: DataParams,
pub iter: Cell<u64>,
pub offset: Cell<f32>,
pub bptt_unroll : u64,
}
impl AddingProblemSource {
pub fn new(batch_size: u64, bptt_unroll: u64, dtype: DType, max_samples: u64) -> AddingProblemSource
{
assert!(bptt_unroll % 4 == 0, "The number of time steps has to be divisible by 4 for the adding problem");
let input_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let target_dims = Dim4::new(&[batch_size, 1, bptt_unroll, 1]);
let train_samples = 0.7 * max_samples as f32;
let test_samples = 0.2 * max_samples as f32;
let validation_samples = 0.1 * max_samples as f32;
AddingProblemSource {
params : DataParams {
input_dims: input_dims,
target_dims: target_dims,
dtype: dtype,
normalize: false,
shuffle: false,
current_epoch: Cell::new(0),
num_samples: max_samples,
num_train: train_samples as u64,
num_test: test_samples as u64,
num_validation: Some(validation_samples as u64),
},
iter: Cell::new(0),
offset: Cell::new(0.0f32),
bptt_unroll: bptt_unroll,
}
}
fn generate_input(&self, batch_size: u64, bptt_unroll: u64) -> Array {
let dim1 = Dim4::new(&[batch_size, 1, bptt_unroll/2, 1]);
let ar1 = uniform::<f32>(dim1,-1.0, 1.0);
let between1 = Range::new(0, bptt_unroll/4);
let between2 = Range::new(bptt_unroll/4, bptt_unroll/2);
let mut rng1 = rand::thread_rng();
let mut rng2 = rand::thread_rng();
let mut vec_total = Vec::with_capacity((batch_size*bptt_unroll) as usize);
let vec_zeros = vec!(0f32; (bptt_unroll/2) as usize);
for _ in 0..batch_size {
let index1 = between1.ind_sample(&mut rng1) as usize;
let index2 = between2.ind_sample(&mut rng2) as usize;
let mut vec_temp = vec_zeros.clone();
vec_temp[index1] = 1f32;
vec_temp[index2] = 1f32;
vec_total.extend(vec_temp);
}
let dim2 = Dim4::new(&[bptt_unroll/2, batch_size, 1, 1]);
let ar2 = af::moddims(&af::transpose(&utils::vec_to_array::<f32>(vec_total, dim2), false), dim1);
af::join(2, &ar1, &ar2)
}
fn generate_target(&self, input: &Array, batch_size: u64, bptt_unroll: u64) -> Array {
let first = af::slices(&input, 0, bptt_unroll/2-1);
let second = af::slices(&input, bptt_unroll/2, bptt_unroll-1);
let ar = af::mul(&first, &second, false);
let zeros = af::constant(0f32, Dim4::new(&[batch_size, 1, bptt_unroll, 1]));
af::add(&af::sum(&ar, 2), &zeros, true)
}
}
impl DataSource for AddingProblemSource {
fn get_train_iter(&self, num_batch: u64) -> Data {
let inp = self.generate_input(num_batch
, self.params.input_dims[2]);
let tar = self.generate_target(&inp
, num_batch
, self.params.input_dims[2]);
let batch = Data {
input: RefCell::new(Box::new(inp.clone())),
target: RefCell::new(Box::new(tar.clone())),
};
|
self.iter.set(self.iter.get() + 1);
batch
}
fn info(&self) -> DataParams {
self.params.clone()
}
fn get_test_iter(&self, num_batch: u64) -> Data {
self.get_train_iter(num_batch)
}
fn get_validation_iter(&self, num_batch: u64) -> Option<Data> {
Some( self.get_train_iter(num_batch))
}
}
|
let current_iter = self.params.current_epoch.get();
if self.iter.get() == self.params.num_samples as u64/ num_batch as u64 {
self.params.current_epoch.set(current_iter + 1);
self.iter.set(0);
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.