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 |
---|---|---|---|---|
p074.rs | //! [Problem 74](https://projecteuler.net/problem=74) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use std::collections::HashMap;
#[derive(Clone)]
enum Length {
Loop(usize),
Chain(usize),
Unknown,
}
fn fact_sum(mut n: u32, fs: &[u32; 10]) -> u32 {
if n == 0 {
return 1;
}
let mut sum = 0;
while n > 0 {
sum += fs[(n % 10) as usize];
n /= 10;
}
sum
}
fn get_chain_len(n: u32, map: &mut [Length], fs: &[u32; 10]) -> usize {
let mut chain_map = HashMap::new();
let mut idx = n;
let mut chain_len = 0;
let mut loop_len = 0;
loop {
match map[idx as usize] {
Length::Loop(c) => {
loop_len += c;
break;
}
Length::Chain(c) => {
chain_len += c;
break;
}
Length::Unknown => match chain_map.get(&idx) {
Some(&chain_idx) => {
loop_len = chain_len - chain_idx;
chain_len = chain_idx;
break;
}
None => {
let _ = chain_map.insert(idx, chain_len);
idx = fact_sum(idx, fs);
chain_len += 1;
}
},
}
}
for (&key, &idx) in &chain_map {
if idx >= chain_len {
map[key as usize] = Length::Loop(loop_len);
} else |
}
chain_len + loop_len
}
fn solve() -> String {
let limit = 1000000;
let factorial = {
let mut val = [1; 10];
for i in 1..10 {
val[i] = val[i - 1] * (i as u32);
}
val
};
let mut map = vec![Length::Unknown; (factorial[9] * 6 + 1) as usize];
let mut cnt = 0;
for n in 1..(limit + 1) {
let len = get_chain_len(n, &mut map, &factorial);
if len == 60 {
cnt += 1;
}
}
cnt.to_string()
}
common::problem!("402", solve);
#[cfg(test)]
mod tests {
use std::iter;
#[test]
fn len() {
let factorial = {
let mut val = [1; 10];
for i in 1..10 {
val[i] = val[i - 1] * (i as u32);
}
val
};
let mut map = iter::repeat(super::Length::Unknown)
.take((factorial[9] * 6 + 1) as usize)
.collect::<Vec<_>>();
assert_eq!(3, super::get_chain_len(169, &mut map, &factorial));
assert_eq!(2, super::get_chain_len(871, &mut map, &factorial));
assert_eq!(2, super::get_chain_len(872, &mut map, &factorial));
assert_eq!(5, super::get_chain_len(69, &mut map, &factorial));
assert_eq!(4, super::get_chain_len(78, &mut map, &factorial));
assert_eq!(2, super::get_chain_len(540, &mut map, &factorial));
}
}
| {
map[key as usize] = Length::Chain(loop_len + chain_len - idx);
} | conditional_block |
lib.rs | // Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use std::process;
use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: PathBuf) |
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn copyright(prog: &str, vers: &str, yr: &str, auth: Vec<&str>) {
print!("{} (core-utils) {}\n\
Copyright (C) {} core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n", prog, vers, yr);
print!("Written by ");
for pers in auth.iter() {
print!("{} ", pers);
}
print!("\n");
}
pub fn prog_try(prog: &str) {
println!("{}: Missing arguments\n\
Try '{} --help' for more information", prog, prog);
set_exit_status(Status::ArgError);
}
pub trait PathMod {
fn last_component(&self) -> PathBuf;
fn first_component(&self) -> PathBuf;
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf;
}
impl PathMod for PathBuf {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
impl PathMod for Path {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
| {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
} | identifier_body |
lib.rs | // Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use std::process;
use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: PathBuf) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => | ,
};
}
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn copyright(prog: &str, vers: &str, yr: &str, auth: Vec<&str>) {
print!("{} (core-utils) {}\n\
Copyright (C) {} core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n", prog, vers, yr);
print!("Written by ");
for pers in auth.iter() {
print!("{} ", pers);
}
print!("\n");
}
pub fn prog_try(prog: &str) {
println!("{}: Missing arguments\n\
Try '{} --help' for more information", prog, prog);
set_exit_status(Status::ArgError);
}
pub trait PathMod {
fn last_component(&self) -> PathBuf;
fn first_component(&self) -> PathBuf;
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf;
}
impl PathMod for PathBuf {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
impl PathMod for Path {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
| {} | conditional_block |
lib.rs | // Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use std::process; | use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: PathBuf) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn copyright(prog: &str, vers: &str, yr: &str, auth: Vec<&str>) {
print!("{} (core-utils) {}\n\
Copyright (C) {} core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n", prog, vers, yr);
print!("Written by ");
for pers in auth.iter() {
print!("{} ", pers);
}
print!("\n");
}
pub fn prog_try(prog: &str) {
println!("{}: Missing arguments\n\
Try '{} --help' for more information", prog, prog);
set_exit_status(Status::ArgError);
}
pub trait PathMod {
fn last_component(&self) -> PathBuf;
fn first_component(&self) -> PathBuf;
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf;
}
impl PathMod for PathBuf {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
impl PathMod for Path {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
} | random_line_split |
|
lib.rs | // Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use std::process;
use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: PathBuf) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn copyright(prog: &str, vers: &str, yr: &str, auth: Vec<&str>) {
print!("{} (core-utils) {}\n\
Copyright (C) {} core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n", prog, vers, yr);
print!("Written by ");
for pers in auth.iter() {
print!("{} ", pers);
}
print!("\n");
}
pub fn prog_try(prog: &str) {
println!("{}: Missing arguments\n\
Try '{} --help' for more information", prog, prog);
set_exit_status(Status::ArgError);
}
pub trait PathMod {
fn last_component(&self) -> PathBuf;
fn first_component(&self) -> PathBuf;
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf;
}
impl PathMod for PathBuf {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
impl PathMod for Path {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn | (&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
| rel_to | identifier_name |
configurable_validator_signer.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{Error, PersistentSafetyStorage};
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
};
use diem_global_constants::CONSENSUS_KEY;
use diem_types::{account_address::AccountAddress, validator_signer::ValidatorSigner};
use serde::Serialize;
/// A ConfigurableValidatorSigner is a ValidatorSigner wrapper that offers either
/// a ValidatorSigner instance or a ValidatorHandle instance, depending on the
/// configuration chosen. This abstracts away the complexities of handling either
/// instance, while offering the same API as a ValidatorSigner.
pub enum ConfigurableValidatorSigner {
Signer(ValidatorSigner),
Handle(ValidatorHandle),
}
impl ConfigurableValidatorSigner {
/// Returns a new ValidatorSigner instance
pub fn new_signer(author: AccountAddress, consensus_key: Ed25519PrivateKey) -> Self {
let signer = ValidatorSigner::new(author, consensus_key);
ConfigurableValidatorSigner::Signer(signer)
}
/// Returns a new ValidatorHandle instance
pub fn new_handle(author: AccountAddress, key_version: Ed25519PublicKey) -> Self {
let handle = ValidatorHandle::new(author, key_version);
ConfigurableValidatorSigner::Handle(handle)
}
/// Returns the author associated with the signer configuration.
pub fn author(&self) -> AccountAddress {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.author(),
ConfigurableValidatorSigner::Handle(handle) => handle.author(),
}
}
/// Returns the public key associated with the signer configuration.
pub fn public_key(&self) -> Ed25519PublicKey {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.public_key(),
ConfigurableValidatorSigner::Handle(handle) => handle.key_version(),
}
}
/// Signs a given message using the signer configuration.
pub fn | <T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
match self {
ConfigurableValidatorSigner::Signer(signer) => Ok(signer.sign(message)),
ConfigurableValidatorSigner::Handle(handle) => handle.sign(message, storage),
}
}
}
/// A ValidatorHandle associates a validator with a consensus key version held in storage.
/// In contrast to a ValidatorSigner, ValidatorHandle does not hold the private
/// key directly but rather holds a reference to that private key which should be
/// accessed using the handle and the secure storage backend.
pub struct ValidatorHandle {
author: AccountAddress,
key_version: Ed25519PublicKey,
}
impl ValidatorHandle {
pub fn new(author: AccountAddress, key_version: Ed25519PublicKey) -> Self {
ValidatorHandle {
author,
key_version,
}
}
/// Returns the author associated with this handle.
pub fn author(&self) -> AccountAddress {
self.author
}
/// Returns the public key version associated with this handle.
pub fn key_version(&self) -> Ed25519PublicKey {
self.key_version.clone()
}
/// Signs a given message using this handle and a given secure storage backend.
pub fn sign<T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
storage.sign(CONSENSUS_KEY.into(), self.key_version(), message)
}
}
| sign | identifier_name |
configurable_validator_signer.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{Error, PersistentSafetyStorage};
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
};
use diem_global_constants::CONSENSUS_KEY;
use diem_types::{account_address::AccountAddress, validator_signer::ValidatorSigner};
use serde::Serialize;
/// A ConfigurableValidatorSigner is a ValidatorSigner wrapper that offers either
/// a ValidatorSigner instance or a ValidatorHandle instance, depending on the
/// configuration chosen. This abstracts away the complexities of handling either
/// instance, while offering the same API as a ValidatorSigner.
pub enum ConfigurableValidatorSigner {
Signer(ValidatorSigner),
Handle(ValidatorHandle),
}
impl ConfigurableValidatorSigner {
/// Returns a new ValidatorSigner instance
pub fn new_signer(author: AccountAddress, consensus_key: Ed25519PrivateKey) -> Self {
let signer = ValidatorSigner::new(author, consensus_key);
ConfigurableValidatorSigner::Signer(signer)
}
/// Returns a new ValidatorHandle instance
pub fn new_handle(author: AccountAddress, key_version: Ed25519PublicKey) -> Self {
let handle = ValidatorHandle::new(author, key_version);
ConfigurableValidatorSigner::Handle(handle)
}
/// Returns the author associated with the signer configuration.
pub fn author(&self) -> AccountAddress {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.author(),
ConfigurableValidatorSigner::Handle(handle) => handle.author(),
}
}
/// Returns the public key associated with the signer configuration.
pub fn public_key(&self) -> Ed25519PublicKey {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.public_key(),
ConfigurableValidatorSigner::Handle(handle) => handle.key_version(),
}
}
/// Signs a given message using the signer configuration.
pub fn sign<T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
match self {
ConfigurableValidatorSigner::Signer(signer) => Ok(signer.sign(message)),
ConfigurableValidatorSigner::Handle(handle) => handle.sign(message, storage),
}
}
}
/// A ValidatorHandle associates a validator with a consensus key version held in storage.
/// In contrast to a ValidatorSigner, ValidatorHandle does not hold the private
/// key directly but rather holds a reference to that private key which should be
/// accessed using the handle and the secure storage backend.
pub struct ValidatorHandle {
author: AccountAddress,
key_version: Ed25519PublicKey,
}
impl ValidatorHandle {
pub fn new(author: AccountAddress, key_version: Ed25519PublicKey) -> Self |
/// Returns the author associated with this handle.
pub fn author(&self) -> AccountAddress {
self.author
}
/// Returns the public key version associated with this handle.
pub fn key_version(&self) -> Ed25519PublicKey {
self.key_version.clone()
}
/// Signs a given message using this handle and a given secure storage backend.
pub fn sign<T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
storage.sign(CONSENSUS_KEY.into(), self.key_version(), message)
}
}
| {
ValidatorHandle {
author,
key_version,
}
} | identifier_body |
configurable_validator_signer.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{Error, PersistentSafetyStorage};
use diem_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
};
use diem_global_constants::CONSENSUS_KEY;
use diem_types::{account_address::AccountAddress, validator_signer::ValidatorSigner};
use serde::Serialize;
/// A ConfigurableValidatorSigner is a ValidatorSigner wrapper that offers either
/// a ValidatorSigner instance or a ValidatorHandle instance, depending on the
/// configuration chosen. This abstracts away the complexities of handling either
/// instance, while offering the same API as a ValidatorSigner.
pub enum ConfigurableValidatorSigner {
Signer(ValidatorSigner),
Handle(ValidatorHandle),
}
impl ConfigurableValidatorSigner {
/// Returns a new ValidatorSigner instance
pub fn new_signer(author: AccountAddress, consensus_key: Ed25519PrivateKey) -> Self {
let signer = ValidatorSigner::new(author, consensus_key);
ConfigurableValidatorSigner::Signer(signer)
}
/// Returns a new ValidatorHandle instance
pub fn new_handle(author: AccountAddress, key_version: Ed25519PublicKey) -> Self {
let handle = ValidatorHandle::new(author, key_version);
ConfigurableValidatorSigner::Handle(handle)
}
/// Returns the author associated with the signer configuration.
pub fn author(&self) -> AccountAddress {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.author(),
ConfigurableValidatorSigner::Handle(handle) => handle.author(),
}
}
/// Returns the public key associated with the signer configuration.
pub fn public_key(&self) -> Ed25519PublicKey {
match self {
ConfigurableValidatorSigner::Signer(signer) => signer.public_key(),
ConfigurableValidatorSigner::Handle(handle) => handle.key_version(),
}
}
/// Signs a given message using the signer configuration.
pub fn sign<T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
match self {
ConfigurableValidatorSigner::Signer(signer) => Ok(signer.sign(message)),
ConfigurableValidatorSigner::Handle(handle) => handle.sign(message, storage),
}
}
}
/// A ValidatorHandle associates a validator with a consensus key version held in storage.
/// In contrast to a ValidatorSigner, ValidatorHandle does not hold the private
/// key directly but rather holds a reference to that private key which should be
/// accessed using the handle and the secure storage backend.
pub struct ValidatorHandle {
author: AccountAddress,
key_version: Ed25519PublicKey,
}
impl ValidatorHandle {
pub fn new(author: AccountAddress, key_version: Ed25519PublicKey) -> Self {
ValidatorHandle {
author,
key_version,
} | }
/// Returns the public key version associated with this handle.
pub fn key_version(&self) -> Ed25519PublicKey {
self.key_version.clone()
}
/// Signs a given message using this handle and a given secure storage backend.
pub fn sign<T: Serialize + CryptoHash>(
&self,
message: &T,
storage: &PersistentSafetyStorage,
) -> Result<Ed25519Signature, Error> {
storage.sign(CONSENSUS_KEY.into(), self.key_version(), message)
}
} | }
/// Returns the author associated with this handle.
pub fn author(&self) -> AccountAddress {
self.author | random_line_split |
bfi.rs | use crate::core::bits::Bits;
use crate::core::instruction::{BfiParams, Instruction};
use crate::core::register::Reg;
#[allow(non_snake_case)]
pub fn decode_BFI_t1(opcode: u32) -> Instruction {
let rn: u8 = opcode.get_bits(16..20) as u8;
let rd: u8 = opcode.get_bits(8..12) as u8;
let imm3: u8 = opcode.get_bits(12..15) as u8; |
// msbit = lsbit + width -1 <=>
// width = msbit - lsbit + 1
let width = msbit - lsbit + 1;
Instruction::BFI {
params: BfiParams {
rd: Reg::from(rd),
rn: Reg::from(rn),
lsbit: lsbit as usize,
width: width as usize,
},
}
} | let imm2: u8 = opcode.get_bits(6..8) as u8;
let lsbit = u32::from((imm3 << 2) + imm2);
let msbit = opcode.get_bits(0..5); | random_line_split |
bfi.rs | use crate::core::bits::Bits;
use crate::core::instruction::{BfiParams, Instruction};
use crate::core::register::Reg;
#[allow(non_snake_case)]
pub fn decode_BFI_t1(opcode: u32) -> Instruction | },
}
}
| {
let rn: u8 = opcode.get_bits(16..20) as u8;
let rd: u8 = opcode.get_bits(8..12) as u8;
let imm3: u8 = opcode.get_bits(12..15) as u8;
let imm2: u8 = opcode.get_bits(6..8) as u8;
let lsbit = u32::from((imm3 << 2) + imm2);
let msbit = opcode.get_bits(0..5);
// msbit = lsbit + width -1 <=>
// width = msbit - lsbit + 1
let width = msbit - lsbit + 1;
Instruction::BFI {
params: BfiParams {
rd: Reg::from(rd),
rn: Reg::from(rn),
lsbit: lsbit as usize,
width: width as usize, | identifier_body |
bfi.rs | use crate::core::bits::Bits;
use crate::core::instruction::{BfiParams, Instruction};
use crate::core::register::Reg;
#[allow(non_snake_case)]
pub fn | (opcode: u32) -> Instruction {
let rn: u8 = opcode.get_bits(16..20) as u8;
let rd: u8 = opcode.get_bits(8..12) as u8;
let imm3: u8 = opcode.get_bits(12..15) as u8;
let imm2: u8 = opcode.get_bits(6..8) as u8;
let lsbit = u32::from((imm3 << 2) + imm2);
let msbit = opcode.get_bits(0..5);
// msbit = lsbit + width -1 <=>
// width = msbit - lsbit + 1
let width = msbit - lsbit + 1;
Instruction::BFI {
params: BfiParams {
rd: Reg::from(rd),
rn: Reg::from(rn),
lsbit: lsbit as usize,
width: width as usize,
},
}
}
| decode_BFI_t1 | identifier_name |
helpers.rs |
use errors::*;
use crypto::digest::Digest;
use crypto::blake2b::Blake2b;
/// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned
/// array will also be 32 bytes long.
///
/// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string
/// "hypercore" (with no trailing null byte).
pub fn | (key: &[u8]) -> Vec<u8> {
let mut discovery_key = [0; 32];
let mut hash = Blake2b::new_keyed(32, key);
hash.input(&"hypercore".as_bytes());
hash.result(&mut discovery_key);
discovery_key.to_vec()
}
/// Helper to parse a dat address (aka, public key) in string format.
///
/// Address can start with 'dat://'. It should contain 64 hexadecimal characters.
pub fn parse_dat_address(input: &str) -> Result<Vec<u8>> {
let raw_key = if input.starts_with("dat://") {
&input[6..]
} else {
input
};
if raw_key.len()!= 32 * 2 {
bail!("dat key not correct length");
}
let mut key_bytes = vec![];
for i in 0..32 {
let r = u8::from_str_radix(&raw_key[2 * i..2 * i + 2], 16);
match r {
Ok(b) => key_bytes.push(b),
Err(e) => bail!("Problem with hex: {}", e),
};
}
Ok(key_bytes)
}
#[test]
fn test_parse_dat_address() {
assert!(parse_dat_address(
"c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"c7638882870ab").is_err());
assert!(parse_dat_address(
"g7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d5970").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d59").is_err());
}
| make_discovery_key | identifier_name |
helpers.rs | use errors::*;
use crypto::digest::Digest;
use crypto::blake2b::Blake2b;
/// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned
/// array will also be 32 bytes long.
///
/// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string
/// "hypercore" (with no trailing null byte).
pub fn make_discovery_key(key: &[u8]) -> Vec<u8> {
let mut discovery_key = [0; 32];
let mut hash = Blake2b::new_keyed(32, key);
hash.input(&"hypercore".as_bytes());
hash.result(&mut discovery_key);
discovery_key.to_vec()
}
/// Helper to parse a dat address (aka, public key) in string format.
///
/// Address can start with 'dat://'. It should contain 64 hexadecimal characters.
pub fn parse_dat_address(input: &str) -> Result<Vec<u8>> {
let raw_key = if input.starts_with("dat://") {
&input[6..]
} else {
input
};
if raw_key.len()!= 32 * 2 {
bail!("dat key not correct length");
}
let mut key_bytes = vec![];
for i in 0..32 {
let r = u8::from_str_radix(&raw_key[2 * i..2 * i + 2], 16);
match r {
Ok(b) => key_bytes.push(b),
Err(e) => bail!("Problem with hex: {}", e),
};
} | Ok(key_bytes)
}
#[test]
fn test_parse_dat_address() {
assert!(parse_dat_address(
"c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"c7638882870ab").is_err());
assert!(parse_dat_address(
"g7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d5970").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d59").is_err());
} | random_line_split |
|
helpers.rs |
use errors::*;
use crypto::digest::Digest;
use crypto::blake2b::Blake2b;
/// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned
/// array will also be 32 bytes long.
///
/// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string
/// "hypercore" (with no trailing null byte).
pub fn make_discovery_key(key: &[u8]) -> Vec<u8> {
let mut discovery_key = [0; 32];
let mut hash = Blake2b::new_keyed(32, key);
hash.input(&"hypercore".as_bytes());
hash.result(&mut discovery_key);
discovery_key.to_vec()
}
/// Helper to parse a dat address (aka, public key) in string format.
///
/// Address can start with 'dat://'. It should contain 64 hexadecimal characters.
pub fn parse_dat_address(input: &str) -> Result<Vec<u8>> |
#[test]
fn test_parse_dat_address() {
assert!(parse_dat_address(
"c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok());
assert!(parse_dat_address(
"c7638882870ab").is_err());
assert!(parse_dat_address(
"g7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d5970").is_err());
assert!(parse_dat_address(
"dat://c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d59").is_err());
}
| {
let raw_key = if input.starts_with("dat://") {
&input[6..]
} else {
input
};
if raw_key.len() != 32 * 2 {
bail!("dat key not correct length");
}
let mut key_bytes = vec![];
for i in 0..32 {
let r = u8::from_str_radix(&raw_key[2 * i..2 * i + 2], 16);
match r {
Ok(b) => key_bytes.push(b),
Err(e) => bail!("Problem with hex: {}", e),
};
}
Ok(key_bytes)
} | identifier_body |
img.rs | use std::iter::Iterator;
use std::path;
use image;
use image::{DynamicImage, GenericImageView};
pub struct Image {
pub width: u32,
pub height: u32,
img_buf: DynamicImage,
}
impl Image {
pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image {
let img_buf = image::open(&path).unwrap();
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
pub fn | (img_buf: DynamicImage) -> Image {
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
#[cfg(feature = "qrcode_builder")]
pub fn from_qr(code: &str, width: u32) -> Image {
use image::ImageBuffer;
use qrcode::QrCode;
let code = QrCode::new(code.as_bytes()).unwrap();
let code_width = code.width() as u32;
let point_width = width / (code_width + 2);
// QR code quite zone width
let quite_width = (width % (code_width + 2)) / 2 + point_width;
#[allow(clippy::many_single_char_names)]
let img_buf = ImageBuffer::from_fn(width, width, |x, y| {
let is_white = x < quite_width
|| y < quite_width
|| x >= (width - quite_width)
|| y >= (width - quite_width)
||!code[(
((x - quite_width) / point_width) as usize,
((y - quite_width) / point_width) as usize,
)];
if is_white {
image::Rgb([0xFF, 0xFF, 0xFF])
} else {
image::Rgb([0, 0, 0])
}
});
Image {
width,
height: width,
img_buf: DynamicImage::ImageRgb8(img_buf),
}
}
pub fn is_blank_pixel(&self, x: u32, y: u32) -> bool {
let pixel = self.img_buf.get_pixel(x, y);
// full transprant OR is white
pixel[3] == 0 || (pixel[0] & pixel[1] & pixel[2]) == 0xFF
}
pub fn bitimage_lines(&self, density: u32) -> BitimageLines {
BitimageLines {
line: 0,
density,
image: self,
}
}
#[allow(clippy::many_single_char_names)]
fn get_line(&self, num: u32, density: u32) -> Option<Box<[u8]>> {
let n = self.height as u32 / density;
let y = num - 1;
if y >= n {
return None;
}
let c = density / 8;
let mut data: Vec<u8> = vec![0; (self.width * c) as usize];
// println!(">>> num={}, density={}, n={}, y={}, c={}, data.len()={}",
// num, density, n, y, c, data.len());
for x in 0..self.width {
for b in 0..density {
let i = x * c + (b >> 3);
// println!("x={}, b={}, i={}, b>>8={}", x, b, i, b>>3);
let l = y * density + b;
if l < self.height &&!self.is_blank_pixel(x, l) {
data[i as usize] += 0x80 >> (b & 0x07);
}
}
}
Some(data.into_boxed_slice())
}
#[allow(clippy::many_single_char_names)]
pub fn get_raster(&self) -> Box<[u8]> {
let n = (self.width + 7) / 8; // Number of bytes per line
let mut data: Vec<u8> = vec![0; (n * self.height) as usize];
for y in 0..self.height {
for x in 0..n {
for b in 0..8 {
let i = x * 8 + b;
if i < self.width &&!self.is_blank_pixel(i, y) {
data[(y * n + x) as usize] += 0x80 >> (b & 0x7);
}
}
}
}
data.into_boxed_slice()
}
}
pub struct BitimageLines<'a> {
line: u32,
density: u32,
image: &'a Image,
}
impl<'a> Iterator for BitimageLines<'a> {
type Item = Box<[u8]>;
fn next(&mut self) -> Option<Box<[u8]>> {
self.line += 1;
self.image.get_line(self.line, self.density)
}
}
| from | identifier_name |
img.rs | use std::iter::Iterator;
use std::path;
use image;
use image::{DynamicImage, GenericImageView};
pub struct Image {
pub width: u32,
pub height: u32,
img_buf: DynamicImage,
}
impl Image {
pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image {
let img_buf = image::open(&path).unwrap();
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
pub fn from(img_buf: DynamicImage) -> Image {
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
#[cfg(feature = "qrcode_builder")]
pub fn from_qr(code: &str, width: u32) -> Image {
use image::ImageBuffer;
use qrcode::QrCode;
let code = QrCode::new(code.as_bytes()).unwrap();
let code_width = code.width() as u32;
let point_width = width / (code_width + 2);
// QR code quite zone width
let quite_width = (width % (code_width + 2)) / 2 + point_width;
#[allow(clippy::many_single_char_names)]
let img_buf = ImageBuffer::from_fn(width, width, |x, y| {
let is_white = x < quite_width
|| y < quite_width
|| x >= (width - quite_width)
|| y >= (width - quite_width)
||!code[(
((x - quite_width) / point_width) as usize,
((y - quite_width) / point_width) as usize,
)];
if is_white | else {
image::Rgb([0, 0, 0])
}
});
Image {
width,
height: width,
img_buf: DynamicImage::ImageRgb8(img_buf),
}
}
pub fn is_blank_pixel(&self, x: u32, y: u32) -> bool {
let pixel = self.img_buf.get_pixel(x, y);
// full transprant OR is white
pixel[3] == 0 || (pixel[0] & pixel[1] & pixel[2]) == 0xFF
}
pub fn bitimage_lines(&self, density: u32) -> BitimageLines {
BitimageLines {
line: 0,
density,
image: self,
}
}
#[allow(clippy::many_single_char_names)]
fn get_line(&self, num: u32, density: u32) -> Option<Box<[u8]>> {
let n = self.height as u32 / density;
let y = num - 1;
if y >= n {
return None;
}
let c = density / 8;
let mut data: Vec<u8> = vec![0; (self.width * c) as usize];
// println!(">>> num={}, density={}, n={}, y={}, c={}, data.len()={}",
// num, density, n, y, c, data.len());
for x in 0..self.width {
for b in 0..density {
let i = x * c + (b >> 3);
// println!("x={}, b={}, i={}, b>>8={}", x, b, i, b>>3);
let l = y * density + b;
if l < self.height &&!self.is_blank_pixel(x, l) {
data[i as usize] += 0x80 >> (b & 0x07);
}
}
}
Some(data.into_boxed_slice())
}
#[allow(clippy::many_single_char_names)]
pub fn get_raster(&self) -> Box<[u8]> {
let n = (self.width + 7) / 8; // Number of bytes per line
let mut data: Vec<u8> = vec![0; (n * self.height) as usize];
for y in 0..self.height {
for x in 0..n {
for b in 0..8 {
let i = x * 8 + b;
if i < self.width &&!self.is_blank_pixel(i, y) {
data[(y * n + x) as usize] += 0x80 >> (b & 0x7);
}
}
}
}
data.into_boxed_slice()
}
}
pub struct BitimageLines<'a> {
line: u32,
density: u32,
image: &'a Image,
}
impl<'a> Iterator for BitimageLines<'a> {
type Item = Box<[u8]>;
fn next(&mut self) -> Option<Box<[u8]>> {
self.line += 1;
self.image.get_line(self.line, self.density)
}
}
| {
image::Rgb([0xFF, 0xFF, 0xFF])
} | conditional_block |
img.rs | use std::iter::Iterator;
use std::path;
use image;
use image::{DynamicImage, GenericImageView};
pub struct Image {
pub width: u32,
pub height: u32,
img_buf: DynamicImage,
}
impl Image {
pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image {
let img_buf = image::open(&path).unwrap();
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
pub fn from(img_buf: DynamicImage) -> Image {
let (width, height) = img_buf.dimensions();
Image {
width,
height,
img_buf,
}
}
#[cfg(feature = "qrcode_builder")]
pub fn from_qr(code: &str, width: u32) -> Image {
use image::ImageBuffer;
use qrcode::QrCode;
let code = QrCode::new(code.as_bytes()).unwrap();
let code_width = code.width() as u32;
let point_width = width / (code_width + 2);
// QR code quite zone width
let quite_width = (width % (code_width + 2)) / 2 + point_width;
#[allow(clippy::many_single_char_names)]
let img_buf = ImageBuffer::from_fn(width, width, |x, y| {
let is_white = x < quite_width
|| y < quite_width
|| x >= (width - quite_width)
|| y >= (width - quite_width)
||!code[(
((x - quite_width) / point_width) as usize,
((y - quite_width) / point_width) as usize,
)];
if is_white {
image::Rgb([0xFF, 0xFF, 0xFF])
} else {
image::Rgb([0, 0, 0])
}
});
Image {
width,
height: width,
img_buf: DynamicImage::ImageRgb8(img_buf),
}
}
pub fn is_blank_pixel(&self, x: u32, y: u32) -> bool {
let pixel = self.img_buf.get_pixel(x, y);
// full transprant OR is white
pixel[3] == 0 || (pixel[0] & pixel[1] & pixel[2]) == 0xFF
}
pub fn bitimage_lines(&self, density: u32) -> BitimageLines {
BitimageLines {
line: 0,
density,
image: self,
}
}
#[allow(clippy::many_single_char_names)]
fn get_line(&self, num: u32, density: u32) -> Option<Box<[u8]>> {
let n = self.height as u32 / density;
let y = num - 1;
if y >= n {
return None;
}
let c = density / 8;
let mut data: Vec<u8> = vec![0; (self.width * c) as usize];
// println!(">>> num={}, density={}, n={}, y={}, c={}, data.len()={}",
// num, density, n, y, c, data.len());
for x in 0..self.width {
for b in 0..density {
let i = x * c + (b >> 3);
// println!("x={}, b={}, i={}, b>>8={}", x, b, i, b>>3);
let l = y * density + b;
if l < self.height &&!self.is_blank_pixel(x, l) {
data[i as usize] += 0x80 >> (b & 0x07);
}
}
}
Some(data.into_boxed_slice())
}
#[allow(clippy::many_single_char_names)]
pub fn get_raster(&self) -> Box<[u8]> {
let n = (self.width + 7) / 8; // Number of bytes per line
let mut data: Vec<u8> = vec![0; (n * self.height) as usize];
for y in 0..self.height {
for x in 0..n {
for b in 0..8 {
let i = x * 8 + b;
if i < self.width &&!self.is_blank_pixel(i, y) {
data[(y * n + x) as usize] += 0x80 >> (b & 0x7);
}
}
}
}
data.into_boxed_slice()
}
}
pub struct BitimageLines<'a> {
line: u32,
density: u32,
image: &'a Image,
}
impl<'a> Iterator for BitimageLines<'a> {
type Item = Box<[u8]>;
fn next(&mut self) -> Option<Box<[u8]>> {
self.line += 1;
self.image.get_line(self.line, self.density)
} | } | random_line_split |
|
chrome_loader.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 net::chrome_loader::resolve_chrome_url;
use url::Url;
#[test]
fn test_relative() {
let url = Url::parse("chrome://../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_relative_2() {
let url = Url::parse("chrome://subdir/../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(not(target_os = "windows"))]
fn test_absolute() {
let url = Url::parse("chrome:///etc/passwd").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
| fn test_absolute_2() {
let url = Url::parse("chrome://C:\\Windows").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(target_os = "windows")]
fn test_absolute_3() {
let url = Url::parse("chrome://\\\\server/C$").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_valid() {
let url = Url::parse("chrome://badcert.jpg").unwrap();
let resolved = resolve_chrome_url(&url).unwrap();
assert_eq!(resolved.scheme, "file");
} | #[test]
#[cfg(target_os = "windows")] | random_line_split |
chrome_loader.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 net::chrome_loader::resolve_chrome_url;
use url::Url;
#[test]
fn test_relative() {
let url = Url::parse("chrome://../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_relative_2() {
let url = Url::parse("chrome://subdir/../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(not(target_os = "windows"))]
fn test_absolute() {
let url = Url::parse("chrome:///etc/passwd").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(target_os = "windows")]
fn test_absolute_2() |
#[test]
#[cfg(target_os = "windows")]
fn test_absolute_3() {
let url = Url::parse("chrome://\\\\server/C$").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_valid() {
let url = Url::parse("chrome://badcert.jpg").unwrap();
let resolved = resolve_chrome_url(&url).unwrap();
assert_eq!(resolved.scheme, "file");
}
| {
let url = Url::parse("chrome://C:\\Windows").unwrap();
assert!(resolve_chrome_url(&url).is_err());
} | identifier_body |
chrome_loader.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 net::chrome_loader::resolve_chrome_url;
use url::Url;
#[test]
fn test_relative() {
let url = Url::parse("chrome://../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_relative_2() {
let url = Url::parse("chrome://subdir/../something").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(not(target_os = "windows"))]
fn | () {
let url = Url::parse("chrome:///etc/passwd").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(target_os = "windows")]
fn test_absolute_2() {
let url = Url::parse("chrome://C:\\Windows").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
#[cfg(target_os = "windows")]
fn test_absolute_3() {
let url = Url::parse("chrome://\\\\server/C$").unwrap();
assert!(resolve_chrome_url(&url).is_err());
}
#[test]
fn test_valid() {
let url = Url::parse("chrome://badcert.jpg").unwrap();
let resolved = resolve_chrome_url(&url).unwrap();
assert_eq!(resolved.scheme, "file");
}
| test_absolute | identifier_name |
main.rs | #![feature(slice_position_elem, iter_arith)]
#[macro_use] extern crate libeuler;
/// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
///
/// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
fn main() {
solutions!{
inputs: (max_factor: i64 = 20)
sol naive {
let primes = prime_factors_less_than(&max_factor);
let mut needed_factors = Vec::new();
for factors in primes.iter() {
let mut f = needed_factors.clone();
let still_needed: Vec<&i64> = factors.iter()
.filter(|&fac| {
if f.contains(fac) {
let pos = f.position_elem(fac).unwrap();
f.swap_remove(pos);
false
} else {
true
}
}).collect();
for v in still_needed {
needed_factors.push(v.clone());
}
}
needed_factors.iter().map(|&i| i).product::<i64>()
}
};
}
fn factors(value: &i64) -> Vec<i64> {
let mut factor = 2;
let mut v = value.clone();
let mut retval = Vec::new();
while v > 1 {
if v % factor == 0 | else {
factor += 1;
}
}
retval
}
fn prime_factors_less_than(max: &i64) -> Vec<Vec<i64>> {
let mut retval = Vec::new();
for i in 1..*max {
retval.push(factors(&i));
}
retval
}
| {
retval.push(factor);
v /= factor;
} | conditional_block |
main.rs | #![feature(slice_position_elem, iter_arith)]
#[macro_use] extern crate libeuler;
/// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
///
/// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
fn main() |
for v in still_needed {
needed_factors.push(v.clone());
}
}
needed_factors.iter().map(|&i| i).product::<i64>()
}
};
}
fn factors(value: &i64) -> Vec<i64> {
let mut factor = 2;
let mut v = value.clone();
let mut retval = Vec::new();
while v > 1 {
if v % factor == 0 {
retval.push(factor);
v /= factor;
} else {
factor += 1;
}
}
retval
}
fn prime_factors_less_than(max: &i64) -> Vec<Vec<i64>> {
let mut retval = Vec::new();
for i in 1..*max {
retval.push(factors(&i));
}
retval
}
| {
solutions!{
inputs: (max_factor: i64 = 20)
sol naive {
let primes = prime_factors_less_than(&max_factor);
let mut needed_factors = Vec::new();
for factors in primes.iter() {
let mut f = needed_factors.clone();
let still_needed: Vec<&i64> = factors.iter()
.filter(|&fac| {
if f.contains(fac) {
let pos = f.position_elem(fac).unwrap();
f.swap_remove(pos);
false
} else {
true
}
}).collect(); | identifier_body |
main.rs | #![feature(slice_position_elem, iter_arith)]
#[macro_use] extern crate libeuler;
/// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
///
/// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
fn main() {
solutions!{
inputs: (max_factor: i64 = 20)
sol naive {
let primes = prime_factors_less_than(&max_factor);
let mut needed_factors = Vec::new();
for factors in primes.iter() {
let mut f = needed_factors.clone();
let still_needed: Vec<&i64> = factors.iter()
.filter(|&fac| {
if f.contains(fac) {
let pos = f.position_elem(fac).unwrap();
f.swap_remove(pos);
false
} else {
true
}
}).collect();
for v in still_needed {
needed_factors.push(v.clone());
}
}
needed_factors.iter().map(|&i| i).product::<i64>()
}
};
}
fn | (value: &i64) -> Vec<i64> {
let mut factor = 2;
let mut v = value.clone();
let mut retval = Vec::new();
while v > 1 {
if v % factor == 0 {
retval.push(factor);
v /= factor;
} else {
factor += 1;
}
}
retval
}
fn prime_factors_less_than(max: &i64) -> Vec<Vec<i64>> {
let mut retval = Vec::new();
for i in 1..*max {
retval.push(factors(&i));
}
retval
}
| factors | identifier_name |
main.rs | #![feature(slice_position_elem, iter_arith)]
#[macro_use] extern crate libeuler;
/// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
///
/// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
fn main() {
solutions!{
inputs: (max_factor: i64 = 20)
sol naive {
let primes = prime_factors_less_than(&max_factor);
let mut needed_factors = Vec::new();
for factors in primes.iter() {
let mut f = needed_factors.clone();
let still_needed: Vec<&i64> = factors.iter()
.filter(|&fac| {
if f.contains(fac) {
let pos = f.position_elem(fac).unwrap();
f.swap_remove(pos);
false
} else {
true
}
}).collect();
for v in still_needed { |
needed_factors.iter().map(|&i| i).product::<i64>()
}
};
}
fn factors(value: &i64) -> Vec<i64> {
let mut factor = 2;
let mut v = value.clone();
let mut retval = Vec::new();
while v > 1 {
if v % factor == 0 {
retval.push(factor);
v /= factor;
} else {
factor += 1;
}
}
retval
}
fn prime_factors_less_than(max: &i64) -> Vec<Vec<i64>> {
let mut retval = Vec::new();
for i in 1..*max {
retval.push(factors(&i));
}
retval
} | needed_factors.push(v.clone());
}
} | random_line_split |
lib.rs | #[macro_use]
extern crate bitflags;
extern crate nix;
extern crate libc;
mod itimer_spec;
mod sys;
use std::mem;
use std::ptr;
use std::os::unix::io::{RawFd, AsRawFd};
use nix::{Errno, Error};
use nix::unistd;
use libc::{c_int, clockid_t};
pub use self::itimer_spec::*;
#[doc(hidden)]
const TIMERFD_DATA_SIZE: usize = 8;
bitflags! {
/// Flags for TimerFd
#[derive(Default)]
pub struct TFDFlags: c_int {
/// Set close-on-exec on TimerFd
const TFD_CLOSEXEC = 524288;
/// Set TimerFd to non-block mode
const TFD_NONBLOCK = 2048;
}
}
bitflags! {
/// Flags for TimerFd::set_time
#[derive(Default)]
pub struct TFDTimerFlags: c_int {
/// Set an absolute timer
const TFD_TIMER_ABSTIME = 1;
}
}
#[inline]
pub fn timerfd_create(clock_id: clockid_t, flags: TFDFlags) -> nix::Result<RawFd> {
unsafe { Errno::result(sys::timerfd_create(clock_id, flags.bits())) }
}
#[inline]
pub fn timerfd_settime(
fd: RawFd,
flags: TFDTimerFlags,
utmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
let res = unsafe {
sys::timerfd_settime(
fd,
flags.bits(),
utmr as *const ITimerSpec,
otmr.map(|x| x as *mut ITimerSpec)
.unwrap_or(ptr::null_mut()),
)
};
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[inline]
pub fn timerfd_gettime(fd: RawFd, otmr: &mut ITimerSpec) -> nix::Result<()> {
let res = unsafe { sys::timerfd_gettime(fd, otmr as *mut ITimerSpec) };
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum ClockId {
/// A settable system-wide clock
Realtime = CLOCK_REALTIME,
/// A nonsettable clock which is not affected discontinuous changes in the system clock
Monotonic = CLOCK_MONOTONIC,
}
/// A helper struct for creating, reading, and closing a `timerfd` instance.
///
/// ## Example
///
/// ```
/// use timerfd::{TimerFd, ClockId, ITimerSpec};
///
/// let mut timerfd = TimerFd::new(ClockId::Monotonic).unwrap();
///
/// // Set timer
/// timerfd.set_time(&ITimerSpec::seconds(3), None).unwrap();
///
/// match timerfd.read_time() {
/// // Timer is expired
/// Ok(Some(expirations)) => {},
/// // There is no expired timer. (Only happend when TFD_NONBLOCK set)
/// Ok(None) => {},
/// Err(err) => {}, // Some error happend
/// }
/// ```
#[derive(Debug)]
pub struct TimerFd(RawFd);
impl TimerFd {
/// Create a new TimerFd
pub fn new(clock_id: ClockId) -> nix::Result<TimerFd> {
Self::with_flags(clock_id, Default::default())
}
/// Create a new TimerFd with flags
pub fn with_flags(clock_id: ClockId, flags: TFDFlags) -> nix::Result<TimerFd> {
Ok(TimerFd(timerfd_create(clock_id as clockid_t, flags)?))
}
/// Start or stop a timer
pub fn set_time(
&mut self,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
self.set_time_with_flags(Default::default(), itmr, otmr)
}
/// Return current timer
pub fn get_time(&self, otmr: &mut ITimerSpec) -> nix::Result<()> {
timerfd_gettime(self.0, otmr)
}
/// Set a timer with flags
pub fn set_time_with_flags(
&mut self,
flags: TFDTimerFlags,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
timerfd_settime(self.0, flags, itmr, otmr)
}
pub fn read_time(&mut self) -> nix::Result<Option<u64>> {
let mut buf: [u8; TIMERFD_DATA_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buf) {
Ok(TIMERFD_DATA_SIZE) => Ok(Some(unsafe { mem::transmute(buf) })),
Ok(_) => unreachable!("partial read of timerfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(err) => Err(err),
}
}
}
impl Iterator for TimerFd {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
self.read_time().unwrap_or(None)
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for TimerFd {
fn | (&mut self) {
let _ = unistd::close(self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{time, thread};
use nix::sys::time::{TimeSpec, TimeValLike};
#[test]
fn test_read_timerfd() {
let mut timer =
TimerFd::with_flags(ClockId::Monotonic, TFD_NONBLOCK).expect("Fail to create timerfd");
assert_eq!(timer.read_time(), Ok(None));
timer
.set_time(
&ITimerSpec {
it_value: TimeSpec::seconds(3),
it_interval: TimeSpec::seconds(0),
},
None,
)
.expect("Fail to set time");
assert_eq!(timer.read_time(), Ok(None));
thread::sleep(time::Duration::from_secs(3));
assert!(timer.read_time().unwrap().is_some());
}
}
| drop | identifier_name |
lib.rs | #[macro_use]
extern crate bitflags;
extern crate nix;
extern crate libc;
mod itimer_spec;
mod sys;
use std::mem;
use std::ptr;
use std::os::unix::io::{RawFd, AsRawFd};
use nix::{Errno, Error};
use nix::unistd;
use libc::{c_int, clockid_t};
pub use self::itimer_spec::*;
#[doc(hidden)]
const TIMERFD_DATA_SIZE: usize = 8;
bitflags! {
/// Flags for TimerFd
#[derive(Default)]
pub struct TFDFlags: c_int {
/// Set close-on-exec on TimerFd
const TFD_CLOSEXEC = 524288;
/// Set TimerFd to non-block mode
const TFD_NONBLOCK = 2048;
}
}
bitflags! {
/// Flags for TimerFd::set_time
#[derive(Default)]
pub struct TFDTimerFlags: c_int {
/// Set an absolute timer
const TFD_TIMER_ABSTIME = 1;
}
}
#[inline]
pub fn timerfd_create(clock_id: clockid_t, flags: TFDFlags) -> nix::Result<RawFd> |
#[inline]
pub fn timerfd_settime(
fd: RawFd,
flags: TFDTimerFlags,
utmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
let res = unsafe {
sys::timerfd_settime(
fd,
flags.bits(),
utmr as *const ITimerSpec,
otmr.map(|x| x as *mut ITimerSpec)
.unwrap_or(ptr::null_mut()),
)
};
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[inline]
pub fn timerfd_gettime(fd: RawFd, otmr: &mut ITimerSpec) -> nix::Result<()> {
let res = unsafe { sys::timerfd_gettime(fd, otmr as *mut ITimerSpec) };
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum ClockId {
/// A settable system-wide clock
Realtime = CLOCK_REALTIME,
/// A nonsettable clock which is not affected discontinuous changes in the system clock
Monotonic = CLOCK_MONOTONIC,
}
/// A helper struct for creating, reading, and closing a `timerfd` instance.
///
/// ## Example
///
/// ```
/// use timerfd::{TimerFd, ClockId, ITimerSpec};
///
/// let mut timerfd = TimerFd::new(ClockId::Monotonic).unwrap();
///
/// // Set timer
/// timerfd.set_time(&ITimerSpec::seconds(3), None).unwrap();
///
/// match timerfd.read_time() {
/// // Timer is expired
/// Ok(Some(expirations)) => {},
/// // There is no expired timer. (Only happend when TFD_NONBLOCK set)
/// Ok(None) => {},
/// Err(err) => {}, // Some error happend
/// }
/// ```
#[derive(Debug)]
pub struct TimerFd(RawFd);
impl TimerFd {
/// Create a new TimerFd
pub fn new(clock_id: ClockId) -> nix::Result<TimerFd> {
Self::with_flags(clock_id, Default::default())
}
/// Create a new TimerFd with flags
pub fn with_flags(clock_id: ClockId, flags: TFDFlags) -> nix::Result<TimerFd> {
Ok(TimerFd(timerfd_create(clock_id as clockid_t, flags)?))
}
/// Start or stop a timer
pub fn set_time(
&mut self,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
self.set_time_with_flags(Default::default(), itmr, otmr)
}
/// Return current timer
pub fn get_time(&self, otmr: &mut ITimerSpec) -> nix::Result<()> {
timerfd_gettime(self.0, otmr)
}
/// Set a timer with flags
pub fn set_time_with_flags(
&mut self,
flags: TFDTimerFlags,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
timerfd_settime(self.0, flags, itmr, otmr)
}
pub fn read_time(&mut self) -> nix::Result<Option<u64>> {
let mut buf: [u8; TIMERFD_DATA_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buf) {
Ok(TIMERFD_DATA_SIZE) => Ok(Some(unsafe { mem::transmute(buf) })),
Ok(_) => unreachable!("partial read of timerfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(err) => Err(err),
}
}
}
impl Iterator for TimerFd {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
self.read_time().unwrap_or(None)
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for TimerFd {
fn drop(&mut self) {
let _ = unistd::close(self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{time, thread};
use nix::sys::time::{TimeSpec, TimeValLike};
#[test]
fn test_read_timerfd() {
let mut timer =
TimerFd::with_flags(ClockId::Monotonic, TFD_NONBLOCK).expect("Fail to create timerfd");
assert_eq!(timer.read_time(), Ok(None));
timer
.set_time(
&ITimerSpec {
it_value: TimeSpec::seconds(3),
it_interval: TimeSpec::seconds(0),
},
None,
)
.expect("Fail to set time");
assert_eq!(timer.read_time(), Ok(None));
thread::sleep(time::Duration::from_secs(3));
assert!(timer.read_time().unwrap().is_some());
}
}
| {
unsafe { Errno::result(sys::timerfd_create(clock_id, flags.bits())) }
} | identifier_body |
lib.rs | #[macro_use]
extern crate bitflags;
extern crate nix;
extern crate libc;
mod itimer_spec;
mod sys;
use std::mem;
use std::ptr;
use std::os::unix::io::{RawFd, AsRawFd};
use nix::{Errno, Error};
use nix::unistd;
use libc::{c_int, clockid_t};
pub use self::itimer_spec::*;
#[doc(hidden)]
const TIMERFD_DATA_SIZE: usize = 8;
bitflags! {
/// Flags for TimerFd
#[derive(Default)]
pub struct TFDFlags: c_int {
/// Set close-on-exec on TimerFd
const TFD_CLOSEXEC = 524288;
/// Set TimerFd to non-block mode
const TFD_NONBLOCK = 2048;
}
}
bitflags! {
/// Flags for TimerFd::set_time
#[derive(Default)]
pub struct TFDTimerFlags: c_int {
/// Set an absolute timer
const TFD_TIMER_ABSTIME = 1;
}
}
#[inline]
pub fn timerfd_create(clock_id: clockid_t, flags: TFDFlags) -> nix::Result<RawFd> {
unsafe { Errno::result(sys::timerfd_create(clock_id, flags.bits())) }
}
#[inline]
pub fn timerfd_settime(
fd: RawFd,
flags: TFDTimerFlags,
utmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
let res = unsafe {
sys::timerfd_settime(
fd,
flags.bits(),
utmr as *const ITimerSpec,
otmr.map(|x| x as *mut ITimerSpec)
.unwrap_or(ptr::null_mut()),
)
};
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[inline]
pub fn timerfd_gettime(fd: RawFd, otmr: &mut ITimerSpec) -> nix::Result<()> {
let res = unsafe { sys::timerfd_gettime(fd, otmr as *mut ITimerSpec) };
if res == -1 {
return Err(Error::last());
}
Ok(())
}
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum ClockId {
/// A settable system-wide clock
Realtime = CLOCK_REALTIME,
/// A nonsettable clock which is not affected discontinuous changes in the system clock
Monotonic = CLOCK_MONOTONIC,
}
/// A helper struct for creating, reading, and closing a `timerfd` instance.
///
/// ## Example
///
/// ```
/// use timerfd::{TimerFd, ClockId, ITimerSpec};
///
/// let mut timerfd = TimerFd::new(ClockId::Monotonic).unwrap();
///
/// // Set timer
/// timerfd.set_time(&ITimerSpec::seconds(3), None).unwrap();
///
/// match timerfd.read_time() {
/// // Timer is expired
/// Ok(Some(expirations)) => {},
/// // There is no expired timer. (Only happend when TFD_NONBLOCK set)
/// Ok(None) => {},
/// Err(err) => {}, // Some error happend
/// }
/// ```
#[derive(Debug)]
pub struct TimerFd(RawFd);
impl TimerFd {
/// Create a new TimerFd
pub fn new(clock_id: ClockId) -> nix::Result<TimerFd> {
Self::with_flags(clock_id, Default::default())
}
/// Create a new TimerFd with flags
pub fn with_flags(clock_id: ClockId, flags: TFDFlags) -> nix::Result<TimerFd> {
Ok(TimerFd(timerfd_create(clock_id as clockid_t, flags)?))
}
/// Start or stop a timer
pub fn set_time(
&mut self,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
self.set_time_with_flags(Default::default(), itmr, otmr)
}
/// Return current timer
pub fn get_time(&self, otmr: &mut ITimerSpec) -> nix::Result<()> {
timerfd_gettime(self.0, otmr)
}
/// Set a timer with flags
pub fn set_time_with_flags(
&mut self,
flags: TFDTimerFlags,
itmr: &ITimerSpec,
otmr: Option<&mut ITimerSpec>,
) -> nix::Result<()> {
timerfd_settime(self.0, flags, itmr, otmr)
}
pub fn read_time(&mut self) -> nix::Result<Option<u64>> {
let mut buf: [u8; TIMERFD_DATA_SIZE] = unsafe { mem::uninitialized() };
match unistd::read(self.0, &mut buf) {
Ok(TIMERFD_DATA_SIZE) => Ok(Some(unsafe { mem::transmute(buf) })),
Ok(_) => unreachable!("partial read of timerfd"),
Err(Error::Sys(Errno::EAGAIN)) => Ok(None),
Err(err) => Err(err),
}
}
}
impl Iterator for TimerFd {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
self.read_time().unwrap_or(None)
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for TimerFd {
fn drop(&mut self) {
let _ = unistd::close(self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{time, thread};
use nix::sys::time::{TimeSpec, TimeValLike};
#[test]
fn test_read_timerfd() {
let mut timer =
TimerFd::with_flags(ClockId::Monotonic, TFD_NONBLOCK).expect("Fail to create timerfd");
assert_eq!(timer.read_time(), Ok(None));
timer
.set_time(
&ITimerSpec {
it_value: TimeSpec::seconds(3),
it_interval: TimeSpec::seconds(0),
},
None,
)
.expect("Fail to set time");
assert_eq!(timer.read_time(), Ok(None));
thread::sleep(time::Duration::from_secs(3)); | assert!(timer.read_time().unwrap().is_some());
}
} | random_line_split |
|
opening.rs | use std::io::prelude::*;
use std::path::Path;
use std::fs::File;
use std::io::Result;
use bitboard::Board;
use bitboard::Move;
use bitboard::Turn;
///
///Opening book file format:
///(16 bytes: hash table array size (n))
///n * (20 bytes: (1 byte used)(16 bytes: board position, normalized)(1 byte: white best move)(1 byte: black best move))
///
struct OpeningNode {
hash_val_1 : u32,
hash_val_2 : u32,
black_minimax : i16,
white_minimax : i16,
best_alt_move : u16,
alt_score : i16,
flags : u16,
}
pub struct | {
file : File,
}
impl Opening {
pub fn new(filename : String) -> Result<Opening> {
let open_file = File::open(&filename)?;
Ok(Opening {
file : open_file,
})
}
pub fn get_move(&mut self, bb : Board, t : Turn) -> Result<Move> {
Ok(Move::null())
}
}
| Opening | identifier_name |
opening.rs | use std::io::prelude::*;
use std::path::Path;
use std::fs::File;
use std::io::Result;
use bitboard::Board;
use bitboard::Move;
use bitboard::Turn;
/// | ///
struct OpeningNode {
hash_val_1 : u32,
hash_val_2 : u32,
black_minimax : i16,
white_minimax : i16,
best_alt_move : u16,
alt_score : i16,
flags : u16,
}
pub struct Opening {
file : File,
}
impl Opening {
pub fn new(filename : String) -> Result<Opening> {
let open_file = File::open(&filename)?;
Ok(Opening {
file : open_file,
})
}
pub fn get_move(&mut self, bb : Board, t : Turn) -> Result<Move> {
Ok(Move::null())
}
} | ///Opening book file format:
///(16 bytes: hash table array size (n))
///n * (20 bytes: (1 byte used)(16 bytes: board position, normalized)(1 byte: white best move)(1 byte: black best move)) | random_line_split |
regions-free-region-ordering-callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that callees correctly infer an ordering between free regions
// that appear in their parameter list. See also
// regions-free-region-ordering-caller.rs
fn ordering1<'a, 'b>(x: &'a &'b uint) -> &'a uint {
// It is safe to assume that 'a <= 'b due to the type of x
let y: &'b uint = &**x;
return y;
}
fn ordering2<'a, 'b>(x: &'a &'b uint, y: &'a uint) -> &'b uint {
// However, it is not safe to assume that 'b <= 'a
&*y //~ ERROR cannot infer
}
fn ordering3<'a, 'b>(x: &'a uint, y: &'b uint) -> &'a &'b uint {
// Do not infer an ordering from the return value.
let z: &'b uint = &*x;
//~^ ERROR cannot infer
fail!();
} |
fn ordering4<'a, 'b>(a: &'a uint, b: &'b uint, x: |&'a &'b uint|) {
// Do not infer ordering from closure argument types.
let z: Option<&'a &'b uint> = None;
//~^ ERROR reference has a longer lifetime than the data it references
}
fn ordering5<'a, 'b>(a: &'a uint, b: &'b uint, x: Option<&'a &'b uint>) {
let z: Option<&'a &'b uint> = None;
}
fn main() {} | random_line_split |
|
regions-free-region-ordering-callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that callees correctly infer an ordering between free regions
// that appear in their parameter list. See also
// regions-free-region-ordering-caller.rs
fn | <'a, 'b>(x: &'a &'b uint) -> &'a uint {
// It is safe to assume that 'a <= 'b due to the type of x
let y: &'b uint = &**x;
return y;
}
fn ordering2<'a, 'b>(x: &'a &'b uint, y: &'a uint) -> &'b uint {
// However, it is not safe to assume that 'b <= 'a
&*y //~ ERROR cannot infer
}
fn ordering3<'a, 'b>(x: &'a uint, y: &'b uint) -> &'a &'b uint {
// Do not infer an ordering from the return value.
let z: &'b uint = &*x;
//~^ ERROR cannot infer
fail!();
}
fn ordering4<'a, 'b>(a: &'a uint, b: &'b uint, x: |&'a &'b uint|) {
// Do not infer ordering from closure argument types.
let z: Option<&'a &'b uint> = None;
//~^ ERROR reference has a longer lifetime than the data it references
}
fn ordering5<'a, 'b>(a: &'a uint, b: &'b uint, x: Option<&'a &'b uint>) {
let z: Option<&'a &'b uint> = None;
}
fn main() {}
| ordering1 | identifier_name |
regions-free-region-ordering-callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that callees correctly infer an ordering between free regions
// that appear in their parameter list. See also
// regions-free-region-ordering-caller.rs
fn ordering1<'a, 'b>(x: &'a &'b uint) -> &'a uint {
// It is safe to assume that 'a <= 'b due to the type of x
let y: &'b uint = &**x;
return y;
}
fn ordering2<'a, 'b>(x: &'a &'b uint, y: &'a uint) -> &'b uint {
// However, it is not safe to assume that 'b <= 'a
&*y //~ ERROR cannot infer
}
fn ordering3<'a, 'b>(x: &'a uint, y: &'b uint) -> &'a &'b uint {
// Do not infer an ordering from the return value.
let z: &'b uint = &*x;
//~^ ERROR cannot infer
fail!();
}
fn ordering4<'a, 'b>(a: &'a uint, b: &'b uint, x: |&'a &'b uint|) |
fn ordering5<'a, 'b>(a: &'a uint, b: &'b uint, x: Option<&'a &'b uint>) {
let z: Option<&'a &'b uint> = None;
}
fn main() {}
| {
// Do not infer ordering from closure argument types.
let z: Option<&'a &'b uint> = None;
//~^ ERROR reference has a longer lifetime than the data it references
} | identifier_body |
error.rs | use crate::asm::Token;
use std::fmt;
#[derive(Debug, Clone)]
pub enum Error {
ParseError { error: String },
NoSectionDecl,
MissingSection,
StringConstantWithoutLabel { instr: String },
SymbolAlreadyDeclared { name: String },
InvalidDirectiveName { instr: String },
UnknownDirective { name: String },
UnknownSection { name: String },
UnknownLabel { name: String },
UnexpectedToken { token: Token },
NotAnOpcode,
EmptyString,
UnlabeledString,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ParseError { ref error } => f.write_str(&format!("Parse error: {}", error)),
Error::NoSectionDecl => f.write_str("No section declared"),
Error::MissingSection => f.write_str("Missing section"),
Error::StringConstantWithoutLabel { ref instr } => f.write_str(&format!(
"String constant declared without label: {}",
instr | f.write_str(&format!("Invalid directive name: {}", instr))
}
Error::UnknownDirective { ref name } => {
f.write_str(&format!("Unknown directive: {}", name))
}
Error::UnknownSection { ref name } => {
f.write_str(&format!("Unknown section: {}", name))
}
Error::UnknownLabel { ref name } => f.write_str(&format!("Unknown label: {}", name)),
Error::UnexpectedToken { ref token } => {
f.write_str(&format!("Unexpected token {:?} in the bagging area", token))
}
Error::NotAnOpcode => f.write_str("Non-opcode found in opcode field"),
Error::EmptyString => f.write_str("Empty string provided"),
Error::UnlabeledString => f.write_str("Unlabeled string cannot be referenced"),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match self {
Error::ParseError {.. } => "There was an error parsing the code",
Error::NoSectionDecl => "No section declared",
Error::MissingSection => "Missing section",
Error::StringConstantWithoutLabel {.. } => "String constant declared without label",
Error::SymbolAlreadyDeclared {.. } => "Symbol declared multiple times",
Error::InvalidDirectiveName {.. } => "Invalid directive name",
Error::UnknownDirective {.. } => "Unknown directive",
Error::UnknownSection {.. } => "Unknown section",
Error::UnknownLabel {.. } => "Unknown label",
Error::UnexpectedToken {.. } => "Unexpected token",
Error::NotAnOpcode {.. } => "Not an opcode",
Error::EmptyString {.. } => "Empty string",
Error::UnlabeledString {.. } => "Unlabeled string",
}
}
} | )),
Error::SymbolAlreadyDeclared { ref name } => {
f.write_str(&format!("Symbol {:?} declared multiple times", name))
}
Error::InvalidDirectiveName { ref instr } => { | random_line_split |
error.rs | use crate::asm::Token;
use std::fmt;
#[derive(Debug, Clone)]
pub enum Error {
ParseError { error: String },
NoSectionDecl,
MissingSection,
StringConstantWithoutLabel { instr: String },
SymbolAlreadyDeclared { name: String },
InvalidDirectiveName { instr: String },
UnknownDirective { name: String },
UnknownSection { name: String },
UnknownLabel { name: String },
UnexpectedToken { token: Token },
NotAnOpcode,
EmptyString,
UnlabeledString,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ParseError { ref error } => f.write_str(&format!("Parse error: {}", error)),
Error::NoSectionDecl => f.write_str("No section declared"),
Error::MissingSection => f.write_str("Missing section"),
Error::StringConstantWithoutLabel { ref instr } => f.write_str(&format!(
"String constant declared without label: {}",
instr
)),
Error::SymbolAlreadyDeclared { ref name } => |
Error::InvalidDirectiveName { ref instr } => {
f.write_str(&format!("Invalid directive name: {}", instr))
}
Error::UnknownDirective { ref name } => {
f.write_str(&format!("Unknown directive: {}", name))
}
Error::UnknownSection { ref name } => {
f.write_str(&format!("Unknown section: {}", name))
}
Error::UnknownLabel { ref name } => f.write_str(&format!("Unknown label: {}", name)),
Error::UnexpectedToken { ref token } => {
f.write_str(&format!("Unexpected token {:?} in the bagging area", token))
}
Error::NotAnOpcode => f.write_str("Non-opcode found in opcode field"),
Error::EmptyString => f.write_str("Empty string provided"),
Error::UnlabeledString => f.write_str("Unlabeled string cannot be referenced"),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match self {
Error::ParseError {.. } => "There was an error parsing the code",
Error::NoSectionDecl => "No section declared",
Error::MissingSection => "Missing section",
Error::StringConstantWithoutLabel {.. } => "String constant declared without label",
Error::SymbolAlreadyDeclared {.. } => "Symbol declared multiple times",
Error::InvalidDirectiveName {.. } => "Invalid directive name",
Error::UnknownDirective {.. } => "Unknown directive",
Error::UnknownSection {.. } => "Unknown section",
Error::UnknownLabel {.. } => "Unknown label",
Error::UnexpectedToken {.. } => "Unexpected token",
Error::NotAnOpcode {.. } => "Not an opcode",
Error::EmptyString {.. } => "Empty string",
Error::UnlabeledString {.. } => "Unlabeled string",
}
}
}
| {
f.write_str(&format!("Symbol {:?} declared multiple times", name))
} | conditional_block |
error.rs | use crate::asm::Token;
use std::fmt;
#[derive(Debug, Clone)]
pub enum | {
ParseError { error: String },
NoSectionDecl,
MissingSection,
StringConstantWithoutLabel { instr: String },
SymbolAlreadyDeclared { name: String },
InvalidDirectiveName { instr: String },
UnknownDirective { name: String },
UnknownSection { name: String },
UnknownLabel { name: String },
UnexpectedToken { token: Token },
NotAnOpcode,
EmptyString,
UnlabeledString,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ParseError { ref error } => f.write_str(&format!("Parse error: {}", error)),
Error::NoSectionDecl => f.write_str("No section declared"),
Error::MissingSection => f.write_str("Missing section"),
Error::StringConstantWithoutLabel { ref instr } => f.write_str(&format!(
"String constant declared without label: {}",
instr
)),
Error::SymbolAlreadyDeclared { ref name } => {
f.write_str(&format!("Symbol {:?} declared multiple times", name))
}
Error::InvalidDirectiveName { ref instr } => {
f.write_str(&format!("Invalid directive name: {}", instr))
}
Error::UnknownDirective { ref name } => {
f.write_str(&format!("Unknown directive: {}", name))
}
Error::UnknownSection { ref name } => {
f.write_str(&format!("Unknown section: {}", name))
}
Error::UnknownLabel { ref name } => f.write_str(&format!("Unknown label: {}", name)),
Error::UnexpectedToken { ref token } => {
f.write_str(&format!("Unexpected token {:?} in the bagging area", token))
}
Error::NotAnOpcode => f.write_str("Non-opcode found in opcode field"),
Error::EmptyString => f.write_str("Empty string provided"),
Error::UnlabeledString => f.write_str("Unlabeled string cannot be referenced"),
}
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match self {
Error::ParseError {.. } => "There was an error parsing the code",
Error::NoSectionDecl => "No section declared",
Error::MissingSection => "Missing section",
Error::StringConstantWithoutLabel {.. } => "String constant declared without label",
Error::SymbolAlreadyDeclared {.. } => "Symbol declared multiple times",
Error::InvalidDirectiveName {.. } => "Invalid directive name",
Error::UnknownDirective {.. } => "Unknown directive",
Error::UnknownSection {.. } => "Unknown section",
Error::UnknownLabel {.. } => "Unknown label",
Error::UnexpectedToken {.. } => "Unexpected token",
Error::NotAnOpcode {.. } => "Not an opcode",
Error::EmptyString {.. } => "Empty string",
Error::UnlabeledString {.. } => "Unlabeled string",
}
}
}
| Error | identifier_name |
dis.rs | mode(zydis::DecoderMode::MINIMAL, false)?;
decoder.enable_mode(zydis::DecoderMode::KNC, false)?;
decoder.enable_mode(zydis::DecoderMode::MPX, false)?;
decoder.enable_mode(zydis::DecoderMode::CET, false)?;
decoder.enable_mode(zydis::DecoderMode::LZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::TZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::WBNOINVD, false)?;
decoder.enable_mode(zydis::DecoderMode::CLDEMOTE, false)?;
Ok(decoder)
}
pub fn linear_disassemble<'a>(
decoder: &'a zydis::Decoder,
buf: &'a [u8],
) -> Box<dyn Iterator<Item = (usize, zydis::Result<Option<zydis::DecodedInstruction>>)> + 'a> {
let mut offset = 0usize;
let mut insn_count = 0usize;
let iter = std::iter::from_fn(move || {
if offset >= buf.len() {
debug!("decoded {} instructions", insn_count);
return None;
}
let insn_offset = offset;
let insn_buf = &buf[insn_offset..];
let insn = decoder.decode(insn_buf);
if let Ok(Some(insn)) = &insn {
// see discussion of linear vs thorough disassemble in this module doc for
// call_targets. thorough is 4x more expensive, with limited
// results.
// linear disassembly:
offset += insn.length as usize;
// thorough disassembly:
// offset += 1;
insn_count += 1;
} else {
offset += 1;
}
Some((insn_offset, insn))
});
Box::new(iter)
}
/// Does the given instruction have a fallthrough flow?
pub fn does_insn_fallthrough(insn: &zydis::DecodedInstruction) -> bool {
match insn.mnemonic {
zydis::Mnemonic::JMP => false,
zydis::Mnemonic::RET => false,
zydis::Mnemonic::IRET => false,
zydis::Mnemonic::IRETD => false,
zydis::Mnemonic::IRETQ => false,
// we consider an INT3 (breakpoint) to not flow through.
// we rely on this to deal with non-ret functions, as some
// compilers may insert a CC byte following the call.
//
// really, we'd want to do a real non-ret analysis.
// but thats still a TODO.
//
// see aadtb.dll:0x180001940 for an example.
zydis::Mnemonic::INT3 => false,
zydis::Mnemonic::INT => {
match insn.operands[0].imm.value {
// handled by nt!KiFastFailDispatch on Win8+
// see: https://doar-e.github.io/blog/2013/10/12/having-a-look-at-the-windows-userkernel-exceptions-dispatcher/
0x29 => false,
// handled by nt!KiRaiseAssertion
// see: http://www.osronline.com/article.cfm%5Earticle=474.htm
0x2C => false,
// probably indicates bad code,
// but this hasn't be thoroughly vetted yet.
_ => {
debug!("{:#x?}", insn);
true
}
}
}
// TODO: call may not fallthrough if function is noret.
// will need another pass to clean this up.
zydis::Mnemonic::CALL => true,
_ => true,
}
}
fn print_op(_op: &zydis::DecodedOperand) {
/*
if cfg!(feature = "dump_serde") {
use serde_json;
let s = serde_json::to_string(op).unwrap();
println!("op: {}", s);
} else {
*/
println!("op: TODO(print_op)");
//}
}
/// zydis supports implicit operands,
/// which we don't currently use in our analysis.
/// so, fetch the first explicit operand to an instruction.
pub fn get_first_operand(insn: &zydis::DecodedInstruction) -> Option<&zydis::DecodedOperand> {
insn.operands
.iter()
.find(|op| op.visibility == zydis::OperandVisibility::EXPLICIT)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
// if direct, the address of the destination.
Direct(VA),
// if indirect, the VA is the address of the pointer.
// e.g. 0x401000 in call [0x401000]
// this may very well be zero or other junk.
// this value might be useful to lookup against:
// - imports
// - jump tables
Indirect(VA),
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch the pointer, rather than the dest,
// so like `0x401000`.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_ptr(
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.mem.base == zydis::Register::NONE
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// the operand is a deref of a memory address.
// for example: JMP [0x0]
// this means: read the ptr from 0x0, and then jump to it.
//
// we'll have to make some assumptions here:
// - the ptr doesn't change (can detect via mem segment perms)
// - the ptr is fixed up (TODO)
//
// see doctest: [test simple memory ptr operand]()
if op.mem.disp.displacement < 0 {
Ok(None)
} else {
Ok(Some(op.mem.disp.displacement as VA))
}
} else if op.mem.base == zydis::Register::RIP
// only valid on x64
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// this is RIP-relative addressing.
// it works like a relative immediate,
// that is: dst = *(rva + displacement + instruction len)
match util::va_add_signed(va + insn.length as u64, op.mem.disp.displacement as i64) {
None => Ok(None),
Some(ptr) => Ok(Some(ptr)),
}
} else if op.mem.base!= zydis::Register::NONE {
// this is something like `CALL [eax+4]`
// can't resolve without emulation
// TODO: add test
Ok(None)
} else if op.mem.scale > 0 {
// this is something like `JMP [0x1000+eax*4]` (32-bit)
Ok(None)
} else {
println!("{:#x}: get mem op xref", va);
print_op(op);
panic!("not supported");
}
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch what the pointer points to,
// which is *not* `0x401000` in this example.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if let Some(ptr) = get_memory_operand_ptr(va, insn, op)? {
let dst = match module.read_va_at_va(ptr) {
Ok(dst) => dst,
Err(_) => return Ok(None),
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
// this is the happy path!
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
Ok(None)
}
}
pub fn get_pointer_operand_xref(op: &zydis::DecodedOperand) -> Result<Option<VA>> {
// ref: https://c9x.me/x86/html/file_module_x86_id_147.html
//
// > Far Jumps in Real-Address or Virtual-8086 Mode.
// > When executing a far jump in real address or virtual-8086 mode,
// > the processor jumps to the code segment and offset specified with the
// > target operand. Here the target operand specifies an absolute far
// > address either directly with a pointer (ptr16:16 or ptr16:32) or
// > indirectly with a memory location (m16:16 or m16:32). With the
// > pointer method, the segment and address of the called procedure is
// > encoded in the instruction, using a 4-byte (16-bit operand size) or
// > 6-byte (32-bit operand size) far address immediate.
// TODO: do something intelligent with the segment.
Ok(Some(op.ptr.offset as u64))
}
pub fn get_immediate_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.imm.is_relative {
// the operand is an immediate constant relative to $PC.
// destination = $pc + immediate + insn.len
//
// see doctest: [test relative immediate operand]()
let imm = if op.imm.is_signed {
util::u64_i64(op.imm.value)
} else {
op.imm.value as i64
};
let dst = match util::va_add_signed(va + insn.length as u64, imm) {
None => return Ok(None),
Some(dst) => dst,
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
// the operand is an immediate absolute address.
let dst = if op.imm.is_signed {
let imm = util::u64_i64(op.imm.value);
if imm < 0 {
// obviously this isn't an address if negative.
return Ok(None);
}
imm as u64
} else {
op.imm.value
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
}
}
pub fn get_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<Target>> {
match op.ty {
// like:.text:0000000180001041 FF 15 D1 78 07 00 call cs:__imp_RtlVirtualUnwind_0
// 0x0000000000001041: call [0x0000000000079980]
zydis::OperandType::MEMORY => match get_memory_operand_ptr(va, insn, op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: EA 33 D2 B9 60 80 40 jmp far ptr 4080h:60B9D233h
// "ptr": {
// "segment": 16512,
// "offset": 1622790707
// },
zydis::OperandType::POINTER => match get_pointer_operand_xref(op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
zydis::OperandType::IMMEDIATE => match get_immediate_operand_xref(module, va, insn, op) {
Ok(Some(va)) => Ok(Some(Target::Direct(va))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: CALL [rax]
// which cannot be resolved without emulation.
zydis::OperandType::REGISTER => Ok(Some(Target::Indirect(0x0))),
zydis::OperandType::UNUSED => Ok(None),
}
}
#[cfg(test)]
mod tests {
use crate::{analysis::dis::*, rsrc::*, test::*};
#[test]
fn test_get_memory_operand_ptr() {
//```
//.text:00000001800134D4 call cs:KernelBaseGetGlobalData
//```
//
// this should result in a call flow to IAT entry 0x1800773F0
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let insn = read_insn(&pe.module, 0x1800134D4);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_ptr(0x1800134D4, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x1800773F0);
}
#[test]
fn test_get_memory_operand_xref_simple() {
// 0: ff 25 06 00 00 00 +-> jmp DWORD PTR ds:0x6
// 6: 00 00 00 00 +-- dw 0x0
let module = load_shellcode32(b"\xFF\x25\x06\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_memory_operand_xref_rip_relative() {
// FF 15 00 00 00 00 CALL $+5
// 00 00 00 00 00 00 00 00 dq 0x0
let module = load_shellcode64(b"\xFF\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_pointer_operand_xref() {
// this is a far ptr jump from addr 0x0 to itmodule:
// JMP FAR PTR 0:00000000
// [ EA ] [ 00 00 00 00 ] [ 00 00 ]
// opcode ptr segment
let module = load_shellcode32(b"\xEA\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_pointer_operand_xref(&op).unwrap();
assert_eq!(xref.is_some(), true, "has pointer operand xref");
assert_eq!(xref.unwrap(), 0x0, "correct pointer operand xref");
}
#[test]
fn test_get_immediate_operand_xref() |
#[test]
fn test_format_insn() {
use crate::analysis::dis::zydis;
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let mut formatter = zydis::Formatter::new(zydis::FormatterStyle::INTEL).unwrap();
struct UserData {
names: std::collections::BTreeMap<VA, String>,
orig_print_address_abs: Option<zydis::Hook>,
}
let mut userdata = Box::new(UserData {
names: Default::default(),
orig_print_address_abs: None,
});
let orig = formatter
.set_print_address_abs(Box::new(
|formatter: &zydis::Formatter,
buf: &mut zydis::FormatterBuffer,
ctx: &mut zydis::FormatterContext,
userdata: Option<&mut dyn core::any::Any>|
-> zydis::Result<()> {
// programming error: userdata must be provided.
// TODO: enforce via types.
let userdata = userdata.expect("no userdata");
// programming error: userdata must be a Box<UserData>.
// TODO: enforce via types.
let userdata = userdata.downcast_ref::<Box<UserData>>().expect("incorrect userdata");
let absolute_address = unsafe {
// safety: the insn and operands come from zydis, so we assume they contain
// valid data.
let insn: &zydis::DecodedInstruction = &*ctx.instruction;
let op: &zydis::DecodedOperand = &*ctx.operand;
insn.calc_absolute_address(ctx.runtime_address, op)
.expect("failed to calculate absolute address")
};
if let Some(name) = userdata.names.get(&absolute_address) {
// name is found in map, use that.
return buf.get_string()?.append(name);
} else {
// name is not found, use original formatter.
// programming error: the original hook must be recorded.
// TODO: enforce via types.
let orig = userdata.orig_print_address_abs.as_ref().expect("no original hook");
if let zydis::Hook::PrintAddressAbs(Some(f)) = orig {
// safety: zydis::Formatter <-> zydis::ffi::ZydisFormatter is safe according to
// here: https://docs.rs/zydis/3.1.2/src/zydis/formatter.rs.html#306
let status =
unsafe { f(formatter as *const _ as *const zydis::ffi::ZydisFormatter, buf, ctx) };
if status.is_error() {
return Err(status);
} else {
return Ok(());
}
} else {
// I'm not sure how this could ever be the case, as zydis initializes the hook
// with a default. I suppose if you explicitly set
// the callback to NULL/None? Which we don't do here.
panic!("unexpected original hook");
}
}
},
))
.unwrap();
userdata.orig_print | {
// this is a jump from addr 0x0 to itmodule:
// JMP $+0;
let module = load_shellcode32(b"\xEB\xFE");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true, "has immediate operand");
assert_eq!(xref.unwrap(), 0x0, "correct immediate operand");
// this is a jump from addr 0x0 to -1, which is unmapped
// JMP $-1;
let module = load_shellcode32(b"\xEB\xFD");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), false, "does not have immediate operand");
} | identifier_body |
dis.rs | _mode(zydis::DecoderMode::MINIMAL, false)?;
decoder.enable_mode(zydis::DecoderMode::KNC, false)?;
decoder.enable_mode(zydis::DecoderMode::MPX, false)?;
decoder.enable_mode(zydis::DecoderMode::CET, false)?;
decoder.enable_mode(zydis::DecoderMode::LZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::TZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::WBNOINVD, false)?;
decoder.enable_mode(zydis::DecoderMode::CLDEMOTE, false)?;
Ok(decoder)
}
pub fn linear_disassemble<'a>(
decoder: &'a zydis::Decoder,
buf: &'a [u8],
) -> Box<dyn Iterator<Item = (usize, zydis::Result<Option<zydis::DecodedInstruction>>)> + 'a> {
let mut offset = 0usize;
let mut insn_count = 0usize;
let iter = std::iter::from_fn(move || {
if offset >= buf.len() {
debug!("decoded {} instructions", insn_count);
return None;
}
let insn_offset = offset;
let insn_buf = &buf[insn_offset..];
let insn = decoder.decode(insn_buf);
if let Ok(Some(insn)) = &insn {
// see discussion of linear vs thorough disassemble in this module doc for
// call_targets. thorough is 4x more expensive, with limited
// results.
// linear disassembly:
offset += insn.length as usize;
// thorough disassembly:
// offset += 1;
insn_count += 1;
} else {
offset += 1;
}
Some((insn_offset, insn))
});
Box::new(iter)
}
/// Does the given instruction have a fallthrough flow?
pub fn does_insn_fallthrough(insn: &zydis::DecodedInstruction) -> bool {
match insn.mnemonic {
zydis::Mnemonic::JMP => false,
zydis::Mnemonic::RET => false,
zydis::Mnemonic::IRET => false,
zydis::Mnemonic::IRETD => false,
zydis::Mnemonic::IRETQ => false,
// we consider an INT3 (breakpoint) to not flow through.
// we rely on this to deal with non-ret functions, as some
// compilers may insert a CC byte following the call.
//
// really, we'd want to do a real non-ret analysis.
// but thats still a TODO.
//
// see aadtb.dll:0x180001940 for an example.
zydis::Mnemonic::INT3 => false,
zydis::Mnemonic::INT => {
match insn.operands[0].imm.value {
// handled by nt!KiFastFailDispatch on Win8+
// see: https://doar-e.github.io/blog/2013/10/12/having-a-look-at-the-windows-userkernel-exceptions-dispatcher/
0x29 => false,
// handled by nt!KiRaiseAssertion
// see: http://www.osronline.com/article.cfm%5Earticle=474.htm
0x2C => false,
// probably indicates bad code,
// but this hasn't be thoroughly vetted yet.
_ => {
debug!("{:#x?}", insn);
true
}
}
}
// TODO: call may not fallthrough if function is noret.
// will need another pass to clean this up.
zydis::Mnemonic::CALL => true,
_ => true,
}
}
fn print_op(_op: &zydis::DecodedOperand) {
/*
if cfg!(feature = "dump_serde") {
use serde_json;
let s = serde_json::to_string(op).unwrap();
println!("op: {}", s);
} else {
*/
println!("op: TODO(print_op)");
//}
}
/// zydis supports implicit operands,
/// which we don't currently use in our analysis.
/// so, fetch the first explicit operand to an instruction.
pub fn get_first_operand(insn: &zydis::DecodedInstruction) -> Option<&zydis::DecodedOperand> {
insn.operands
.iter()
.find(|op| op.visibility == zydis::OperandVisibility::EXPLICIT)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
// if direct, the address of the destination.
Direct(VA),
// if indirect, the VA is the address of the pointer.
// e.g. 0x401000 in call [0x401000]
// this may very well be zero or other junk.
// this value might be useful to lookup against:
// - imports
// - jump tables
Indirect(VA),
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch the pointer, rather than the dest,
// so like `0x401000`.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_ptr(
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.mem.base == zydis::Register::NONE
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// the operand is a deref of a memory address.
// for example: JMP [0x0]
// this means: read the ptr from 0x0, and then jump to it.
//
// we'll have to make some assumptions here:
// - the ptr doesn't change (can detect via mem segment perms)
// - the ptr is fixed up (TODO)
//
// see doctest: [test simple memory ptr operand]()
if op.mem.disp.displacement < 0 {
Ok(None)
} else {
Ok(Some(op.mem.disp.displacement as VA))
}
} else if op.mem.base == zydis::Register::RIP
// only valid on x64
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// this is RIP-relative addressing.
// it works like a relative immediate,
// that is: dst = *(rva + displacement + instruction len)
match util::va_add_signed(va + insn.length as u64, op.mem.disp.displacement as i64) {
None => Ok(None),
Some(ptr) => Ok(Some(ptr)),
}
} else if op.mem.base!= zydis::Register::NONE {
// this is something like `CALL [eax+4]`
// can't resolve without emulation
// TODO: add test
Ok(None)
} else if op.mem.scale > 0 {
// this is something like `JMP [0x1000+eax*4]` (32-bit)
Ok(None)
} else {
println!("{:#x}: get mem op xref", va);
print_op(op);
panic!("not supported");
}
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch what the pointer points to,
// which is *not* `0x401000` in this example.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if let Some(ptr) = get_memory_operand_ptr(va, insn, op)? {
let dst = match module.read_va_at_va(ptr) {
Ok(dst) => dst,
Err(_) => return Ok(None),
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
// this is the happy path!
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
Ok(None)
}
}
pub fn get_pointer_operand_xref(op: &zydis::DecodedOperand) -> Result<Option<VA>> {
// ref: https://c9x.me/x86/html/file_module_x86_id_147.html
//
// > Far Jumps in Real-Address or Virtual-8086 Mode.
// > When executing a far jump in real address or virtual-8086 mode,
// > the processor jumps to the code segment and offset specified with the
// > target operand. Here the target operand specifies an absolute far
// > address either directly with a pointer (ptr16:16 or ptr16:32) or
// > indirectly with a memory location (m16:16 or m16:32). With the
// > pointer method, the segment and address of the called procedure is
// > encoded in the instruction, using a 4-byte (16-bit operand size) or
// > 6-byte (32-bit operand size) far address immediate.
// TODO: do something intelligent with the segment.
Ok(Some(op.ptr.offset as u64))
}
pub fn get_immediate_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.imm.is_relative {
// the operand is an immediate constant relative to $PC.
// destination = $pc + immediate + insn.len
//
// see doctest: [test relative immediate operand]()
let imm = if op.imm.is_signed {
util::u64_i64(op.imm.value)
} else {
op.imm.value as i64
};
let dst = match util::va_add_signed(va + insn.length as u64, imm) {
None => return Ok(None),
Some(dst) => dst,
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
// the operand is an immediate absolute address.
let dst = if op.imm.is_signed {
let imm = util::u64_i64(op.imm.value);
if imm < 0 {
// obviously this isn't an address if negative.
return Ok(None);
}
imm as u64
} else {
op.imm.value
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
}
}
pub fn get_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<Target>> {
match op.ty {
// like:.text:0000000180001041 FF 15 D1 78 07 00 call cs:__imp_RtlVirtualUnwind_0
// 0x0000000000001041: call [0x0000000000079980]
zydis::OperandType::MEMORY => match get_memory_operand_ptr(va, insn, op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: EA 33 D2 B9 60 80 40 jmp far ptr 4080h:60B9D233h
// "ptr": {
// "segment": 16512,
// "offset": 1622790707
// },
zydis::OperandType::POINTER => match get_pointer_operand_xref(op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
zydis::OperandType::IMMEDIATE => match get_immediate_operand_xref(module, va, insn, op) {
Ok(Some(va)) => Ok(Some(Target::Direct(va))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: CALL [rax]
// which cannot be resolved without emulation.
zydis::OperandType::REGISTER => Ok(Some(Target::Indirect(0x0))),
zydis::OperandType::UNUSED => Ok(None),
}
}
#[cfg(test)]
mod tests {
use crate::{analysis::dis::*, rsrc::*, test::*};
#[test]
fn test_get_memory_operand_ptr() {
//```
//.text:00000001800134D4 call cs:KernelBaseGetGlobalData
//```
//
// this should result in a call flow to IAT entry 0x1800773F0
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let insn = read_insn(&pe.module, 0x1800134D4);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_ptr(0x1800134D4, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x1800773F0);
}
#[test]
fn test_get_memory_operand_xref_simple() {
// 0: ff 25 06 00 00 00 +-> jmp DWORD PTR ds:0x6
// 6: 00 00 00 00 +-- dw 0x0
let module = load_shellcode32(b"\xFF\x25\x06\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_memory_operand_xref_rip_relative() {
// FF 15 00 00 00 00 CALL $+5
// 00 00 00 00 00 00 00 00 dq 0x0
let module = load_shellcode64(b"\xFF\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_pointer_operand_xref() {
// this is a far ptr jump from addr 0x0 to itmodule:
// JMP FAR PTR 0:00000000
// [ EA ] [ 00 00 00 00 ] [ 00 00 ]
// opcode ptr segment
let module = load_shellcode32(b"\xEA\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_pointer_operand_xref(&op).unwrap();
assert_eq!(xref.is_some(), true, "has pointer operand xref");
assert_eq!(xref.unwrap(), 0x0, "correct pointer operand xref");
}
#[test]
fn test_get_immediate_operand_xref() {
// this is a jump from addr 0x0 to itmodule:
// JMP $+0;
let module = load_shellcode32(b"\xEB\xFE");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true, "has immediate operand");
assert_eq!(xref.unwrap(), 0x0, "correct immediate operand");
// this is a jump from addr 0x0 to -1, which is unmapped
// JMP $-1;
let module = load_shellcode32(b"\xEB\xFD");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), false, "does not have immediate operand");
}
#[test]
fn test_format_insn() {
use crate::analysis::dis::zydis;
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let mut formatter = zydis::Formatter::new(zydis::FormatterStyle::INTEL).unwrap();
struct UserData {
names: std::collections::BTreeMap<VA, String>,
orig_print_address_abs: Option<zydis::Hook>,
}
let mut userdata = Box::new(UserData {
names: Default::default(),
orig_print_address_abs: None,
});
let orig = formatter
.set_print_address_abs(Box::new(
|formatter: &zydis::Formatter,
buf: &mut zydis::FormatterBuffer,
ctx: &mut zydis::FormatterContext,
userdata: Option<&mut dyn core::any::Any>|
-> zydis::Result<()> {
// programming error: userdata must be provided.
// TODO: enforce via types.
let userdata = userdata.expect("no userdata");
// programming error: userdata must be a Box<UserData>.
// TODO: enforce via types.
let userdata = userdata.downcast_ref::<Box<UserData>>().expect("incorrect userdata"); | let op: &zydis::DecodedOperand = &*ctx.operand;
insn.calc_absolute_address(ctx.runtime_address, op)
.expect("failed to calculate absolute address")
};
if let Some(name) = userdata.names.get(&absolute_address) {
// name is found in map, use that.
return buf.get_string()?.append(name);
} else {
// name is not found, use original formatter.
// programming error: the original hook must be recorded.
// TODO: enforce via types.
let orig = userdata.orig_print_address_abs.as_ref().expect("no original hook");
if let zydis::Hook::PrintAddressAbs(Some(f)) = orig {
// safety: zydis::Formatter <-> zydis::ffi::ZydisFormatter is safe according to
// here: https://docs.rs/zydis/3.1.2/src/zydis/formatter.rs.html#306
let status =
unsafe { f(formatter as *const _ as *const zydis::ffi::ZydisFormatter, buf, ctx) };
if status.is_error() {
return Err(status);
} else {
return Ok(());
}
} else {
// I'm not sure how this could ever be the case, as zydis initializes the hook
// with a default. I suppose if you explicitly set
// the callback to NULL/None? Which we don't do here.
panic!("unexpected original hook");
}
}
},
))
.unwrap();
userdata.orig_print_address |
let absolute_address = unsafe {
// safety: the insn and operands come from zydis, so we assume they contain
// valid data.
let insn: &zydis::DecodedInstruction = &*ctx.instruction; | random_line_split |
dis.rs | mode(zydis::DecoderMode::MINIMAL, false)?;
decoder.enable_mode(zydis::DecoderMode::KNC, false)?;
decoder.enable_mode(zydis::DecoderMode::MPX, false)?;
decoder.enable_mode(zydis::DecoderMode::CET, false)?;
decoder.enable_mode(zydis::DecoderMode::LZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::TZCNT, false)?;
decoder.enable_mode(zydis::DecoderMode::WBNOINVD, false)?;
decoder.enable_mode(zydis::DecoderMode::CLDEMOTE, false)?;
Ok(decoder)
}
pub fn linear_disassemble<'a>(
decoder: &'a zydis::Decoder,
buf: &'a [u8],
) -> Box<dyn Iterator<Item = (usize, zydis::Result<Option<zydis::DecodedInstruction>>)> + 'a> {
let mut offset = 0usize;
let mut insn_count = 0usize;
let iter = std::iter::from_fn(move || {
if offset >= buf.len() {
debug!("decoded {} instructions", insn_count);
return None;
}
let insn_offset = offset;
let insn_buf = &buf[insn_offset..];
let insn = decoder.decode(insn_buf);
if let Ok(Some(insn)) = &insn {
// see discussion of linear vs thorough disassemble in this module doc for
// call_targets. thorough is 4x more expensive, with limited
// results.
// linear disassembly:
offset += insn.length as usize;
// thorough disassembly:
// offset += 1;
insn_count += 1;
} else {
offset += 1;
}
Some((insn_offset, insn))
});
Box::new(iter)
}
/// Does the given instruction have a fallthrough flow?
pub fn does_insn_fallthrough(insn: &zydis::DecodedInstruction) -> bool {
match insn.mnemonic {
zydis::Mnemonic::JMP => false,
zydis::Mnemonic::RET => false,
zydis::Mnemonic::IRET => false,
zydis::Mnemonic::IRETD => false,
zydis::Mnemonic::IRETQ => false,
// we consider an INT3 (breakpoint) to not flow through.
// we rely on this to deal with non-ret functions, as some
// compilers may insert a CC byte following the call.
//
// really, we'd want to do a real non-ret analysis.
// but thats still a TODO.
//
// see aadtb.dll:0x180001940 for an example.
zydis::Mnemonic::INT3 => false,
zydis::Mnemonic::INT => {
match insn.operands[0].imm.value {
// handled by nt!KiFastFailDispatch on Win8+
// see: https://doar-e.github.io/blog/2013/10/12/having-a-look-at-the-windows-userkernel-exceptions-dispatcher/
0x29 => false,
// handled by nt!KiRaiseAssertion
// see: http://www.osronline.com/article.cfm%5Earticle=474.htm
0x2C => false,
// probably indicates bad code,
// but this hasn't be thoroughly vetted yet.
_ => {
debug!("{:#x?}", insn);
true
}
}
}
// TODO: call may not fallthrough if function is noret.
// will need another pass to clean this up.
zydis::Mnemonic::CALL => true,
_ => true,
}
}
fn print_op(_op: &zydis::DecodedOperand) {
/*
if cfg!(feature = "dump_serde") {
use serde_json;
let s = serde_json::to_string(op).unwrap();
println!("op: {}", s);
} else {
*/
println!("op: TODO(print_op)");
//}
}
/// zydis supports implicit operands,
/// which we don't currently use in our analysis.
/// so, fetch the first explicit operand to an instruction.
pub fn get_first_operand(insn: &zydis::DecodedInstruction) -> Option<&zydis::DecodedOperand> {
insn.operands
.iter()
.find(|op| op.visibility == zydis::OperandVisibility::EXPLICIT)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
// if direct, the address of the destination.
Direct(VA),
// if indirect, the VA is the address of the pointer.
// e.g. 0x401000 in call [0x401000]
// this may very well be zero or other junk.
// this value might be useful to lookup against:
// - imports
// - jump tables
Indirect(VA),
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch the pointer, rather than the dest,
// so like `0x401000`.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_ptr(
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.mem.base == zydis::Register::NONE
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// the operand is a deref of a memory address.
// for example: JMP [0x0]
// this means: read the ptr from 0x0, and then jump to it.
//
// we'll have to make some assumptions here:
// - the ptr doesn't change (can detect via mem segment perms)
// - the ptr is fixed up (TODO)
//
// see doctest: [test simple memory ptr operand]()
if op.mem.disp.displacement < 0 {
Ok(None)
} else {
Ok(Some(op.mem.disp.displacement as VA))
}
} else if op.mem.base == zydis::Register::RIP
// only valid on x64
&& op.mem.index == zydis::Register::NONE
&& op.mem.scale == 0
&& op.mem.disp.has_displacement
{
// this is RIP-relative addressing.
// it works like a relative immediate,
// that is: dst = *(rva + displacement + instruction len)
match util::va_add_signed(va + insn.length as u64, op.mem.disp.displacement as i64) {
None => Ok(None),
Some(ptr) => Ok(Some(ptr)),
}
} else if op.mem.base!= zydis::Register::NONE {
// this is something like `CALL [eax+4]`
// can't resolve without emulation
// TODO: add test
Ok(None)
} else if op.mem.scale > 0 {
// this is something like `JMP [0x1000+eax*4]` (32-bit)
Ok(None)
} else {
println!("{:#x}: get mem op xref", va);
print_op(op);
panic!("not supported");
}
}
// for a memory operand, like `mov eax, [0x401000]`
// fetch what the pointer points to,
// which is *not* `0x401000` in this example.
#[allow(clippy::if_same_then_else)]
pub fn get_memory_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if let Some(ptr) = get_memory_operand_ptr(va, insn, op)? {
let dst = match module.read_va_at_va(ptr) {
Ok(dst) => dst,
Err(_) => return Ok(None),
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
// this is the happy path!
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
Ok(None)
}
}
pub fn get_pointer_operand_xref(op: &zydis::DecodedOperand) -> Result<Option<VA>> {
// ref: https://c9x.me/x86/html/file_module_x86_id_147.html
//
// > Far Jumps in Real-Address or Virtual-8086 Mode.
// > When executing a far jump in real address or virtual-8086 mode,
// > the processor jumps to the code segment and offset specified with the
// > target operand. Here the target operand specifies an absolute far
// > address either directly with a pointer (ptr16:16 or ptr16:32) or
// > indirectly with a memory location (m16:16 or m16:32). With the
// > pointer method, the segment and address of the called procedure is
// > encoded in the instruction, using a 4-byte (16-bit operand size) or
// > 6-byte (32-bit operand size) far address immediate.
// TODO: do something intelligent with the segment.
Ok(Some(op.ptr.offset as u64))
}
pub fn get_immediate_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<VA>> {
if op.imm.is_relative {
// the operand is an immediate constant relative to $PC.
// destination = $pc + immediate + insn.len
//
// see doctest: [test relative immediate operand]()
let imm = if op.imm.is_signed {
util::u64_i64(op.imm.value)
} else {
op.imm.value as i64
};
let dst = match util::va_add_signed(va + insn.length as u64, imm) {
None => return Ok(None),
Some(dst) => dst,
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
} else {
// the operand is an immediate absolute address.
let dst = if op.imm.is_signed {
let imm = util::u64_i64(op.imm.value);
if imm < 0 {
// obviously this isn't an address if negative.
return Ok(None);
}
imm as u64
} else {
op.imm.value
};
// must be mapped
if module.probe_va(dst, Permissions::RWX) {
Ok(Some(dst))
} else {
// invalid address
Ok(None)
}
}
}
pub fn get_operand_xref(
module: &Module,
va: VA,
insn: &zydis::DecodedInstruction,
op: &zydis::DecodedOperand,
) -> Result<Option<Target>> {
match op.ty {
// like:.text:0000000180001041 FF 15 D1 78 07 00 call cs:__imp_RtlVirtualUnwind_0
// 0x0000000000001041: call [0x0000000000079980]
zydis::OperandType::MEMORY => match get_memory_operand_ptr(va, insn, op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: EA 33 D2 B9 60 80 40 jmp far ptr 4080h:60B9D233h
// "ptr": {
// "segment": 16512,
// "offset": 1622790707
// },
zydis::OperandType::POINTER => match get_pointer_operand_xref(op) {
Ok(Some(ptr)) => Ok(Some(Target::Indirect(ptr))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
zydis::OperandType::IMMEDIATE => match get_immediate_operand_xref(module, va, insn, op) {
Ok(Some(va)) => Ok(Some(Target::Direct(va))),
Ok(None) => Ok(None),
Err(e) => Err(e),
},
// like: CALL [rax]
// which cannot be resolved without emulation.
zydis::OperandType::REGISTER => Ok(Some(Target::Indirect(0x0))),
zydis::OperandType::UNUSED => Ok(None),
}
}
#[cfg(test)]
mod tests {
use crate::{analysis::dis::*, rsrc::*, test::*};
#[test]
fn test_get_memory_operand_ptr() {
//```
//.text:00000001800134D4 call cs:KernelBaseGetGlobalData
//```
//
// this should result in a call flow to IAT entry 0x1800773F0
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let insn = read_insn(&pe.module, 0x1800134D4);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_ptr(0x1800134D4, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x1800773F0);
}
#[test]
fn | () {
// 0: ff 25 06 00 00 00 +-> jmp DWORD PTR ds:0x6
// 6: 00 00 00 00 +-- dw 0x0
let module = load_shellcode32(b"\xFF\x25\x06\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_memory_operand_xref_rip_relative() {
// FF 15 00 00 00 00 CALL $+5
// 00 00 00 00 00 00 00 00 dq 0x0
let module = load_shellcode64(b"\xFF\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_memory_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true);
assert_eq!(xref.unwrap(), 0x0);
}
#[test]
fn test_get_pointer_operand_xref() {
// this is a far ptr jump from addr 0x0 to itmodule:
// JMP FAR PTR 0:00000000
// [ EA ] [ 00 00 00 00 ] [ 00 00 ]
// opcode ptr segment
let module = load_shellcode32(b"\xEA\x00\x00\x00\x00\x00\x00");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_pointer_operand_xref(&op).unwrap();
assert_eq!(xref.is_some(), true, "has pointer operand xref");
assert_eq!(xref.unwrap(), 0x0, "correct pointer operand xref");
}
#[test]
fn test_get_immediate_operand_xref() {
// this is a jump from addr 0x0 to itmodule:
// JMP $+0;
let module = load_shellcode32(b"\xEB\xFE");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), true, "has immediate operand");
assert_eq!(xref.unwrap(), 0x0, "correct immediate operand");
// this is a jump from addr 0x0 to -1, which is unmapped
// JMP $-1;
let module = load_shellcode32(b"\xEB\xFD");
let insn = read_insn(&module, 0x0);
let op = get_first_operand(&insn).unwrap();
let xref = get_immediate_operand_xref(&module, 0x0, &insn, &op).unwrap();
assert_eq!(xref.is_some(), false, "does not have immediate operand");
}
#[test]
fn test_format_insn() {
use crate::analysis::dis::zydis;
let buf = get_buf(Rsrc::K32);
let pe = crate::loader::pe::PE::from_bytes(&buf).unwrap();
let mut formatter = zydis::Formatter::new(zydis::FormatterStyle::INTEL).unwrap();
struct UserData {
names: std::collections::BTreeMap<VA, String>,
orig_print_address_abs: Option<zydis::Hook>,
}
let mut userdata = Box::new(UserData {
names: Default::default(),
orig_print_address_abs: None,
});
let orig = formatter
.set_print_address_abs(Box::new(
|formatter: &zydis::Formatter,
buf: &mut zydis::FormatterBuffer,
ctx: &mut zydis::FormatterContext,
userdata: Option<&mut dyn core::any::Any>|
-> zydis::Result<()> {
// programming error: userdata must be provided.
// TODO: enforce via types.
let userdata = userdata.expect("no userdata");
// programming error: userdata must be a Box<UserData>.
// TODO: enforce via types.
let userdata = userdata.downcast_ref::<Box<UserData>>().expect("incorrect userdata");
let absolute_address = unsafe {
// safety: the insn and operands come from zydis, so we assume they contain
// valid data.
let insn: &zydis::DecodedInstruction = &*ctx.instruction;
let op: &zydis::DecodedOperand = &*ctx.operand;
insn.calc_absolute_address(ctx.runtime_address, op)
.expect("failed to calculate absolute address")
};
if let Some(name) = userdata.names.get(&absolute_address) {
// name is found in map, use that.
return buf.get_string()?.append(name);
} else {
// name is not found, use original formatter.
// programming error: the original hook must be recorded.
// TODO: enforce via types.
let orig = userdata.orig_print_address_abs.as_ref().expect("no original hook");
if let zydis::Hook::PrintAddressAbs(Some(f)) = orig {
// safety: zydis::Formatter <-> zydis::ffi::ZydisFormatter is safe according to
// here: https://docs.rs/zydis/3.1.2/src/zydis/formatter.rs.html#306
let status =
unsafe { f(formatter as *const _ as *const zydis::ffi::ZydisFormatter, buf, ctx) };
if status.is_error() {
return Err(status);
} else {
return Ok(());
}
} else {
// I'm not sure how this could ever be the case, as zydis initializes the hook
// with a default. I suppose if you explicitly set
// the callback to NULL/None? Which we don't do here.
panic!("unexpected original hook");
}
}
},
))
.unwrap();
userdata.orig_print_ | test_get_memory_operand_xref_simple | identifier_name |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn malloc_size_of_persistent_local_context(ops: &mut MallocSizeOfOps) -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.size_of(ops)
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if!thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn | (&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| shared_context | identifier_name |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn malloc_size_of_persistent_local_context(ops: &mut MallocSizeOfOps) -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.size_of(ops)
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info. | pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if!thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
} | pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets | random_line_split |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn malloc_size_of_persistent_local_context(ops: &mut MallocSizeOfOps) -> usize |
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if!thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.size_of(ops)
} else {
0
}
})
} | identifier_body |
context.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/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn malloc_size_of_persistent_local_context(ops: &mut MallocSizeOfOps) -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() | else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if!thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| {
context.size_of(ops)
} | conditional_block |
pretty.rs | use chrono::*;
pub use super::split;
pub fn pretty_short(dur: Duration) -> String {
let components = split::split_duration(dur).as_vec();
let mut components_iter = components.iter().skip_while(|a| a.val() == 0);
let first_component = components_iter.next();
let second_component = components_iter.next();
let final_str = match first_component {
Some(x) => {
match second_component.and_then(has_second) {
Some(y) => {format!("{} and {}", x.to_string(), y.to_string())},
None => {x.to_string()}
}
},
// The duration is 0
None => {split::TimePeriod::Millisecond(0).to_string()},
};
fn | (val: &split::TimePeriod) -> Option<&split::TimePeriod> {
if val.val() == 0 {return None};
return Some(val);
}
return final_str;
}
pub fn pretty_full(dur: Duration) -> String {
let components = split::split_duration(dur);
let mut final_str = String::new();
for (i, component) in components.as_vec().iter().enumerate() {
if i!= 0 {
final_str.push_str(", ");
}
final_str.push_str(&component.to_string());
}
return final_str;
}
#[test]
fn test_pretty_full_simple() {
let test_data = vec![
(Duration::days(365), "1 year, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(30), "0 years, 1 month, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::weeks(1), "0 years, 0 months, 1 week, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(1), "0 years, 0 months, 0 weeks, 1 day, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::hours(1), "0 years, 0 months, 0 weeks, 0 days, 1 hour, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::minutes(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 1 minute, 0 seconds, 0 milliseconds"),
(Duration::seconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 1 second, 0 milliseconds"),
(Duration::milliseconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 1 millisecond"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_full(dur), final_str);
}
}
#[test]
fn test_pretty_short() {
let test_data = vec![
(Duration::milliseconds(0), "0 milliseconds"),
(Duration::milliseconds(1), "1 millisecond"),
(-Duration::milliseconds(1), "1 millisecond"),
(Duration::milliseconds(200), "200 milliseconds"),
(Duration::seconds(1) + Duration::milliseconds(200), "1 second and 200 milliseconds"),
(Duration::days(1) + Duration::hours(2), "1 day and 2 hours"),
(Duration::days(1) + Duration::seconds(2), "1 day"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_short(dur), final_str);
}
}
| has_second | identifier_name |
pretty.rs | use chrono::*;
pub use super::split;
pub fn pretty_short(dur: Duration) -> String {
let components = split::split_duration(dur).as_vec();
let mut components_iter = components.iter().skip_while(|a| a.val() == 0);
let first_component = components_iter.next();
let second_component = components_iter.next();
let final_str = match first_component {
Some(x) => | ,
// The duration is 0
None => {split::TimePeriod::Millisecond(0).to_string()},
};
fn has_second(val: &split::TimePeriod) -> Option<&split::TimePeriod> {
if val.val() == 0 {return None};
return Some(val);
}
return final_str;
}
pub fn pretty_full(dur: Duration) -> String {
let components = split::split_duration(dur);
let mut final_str = String::new();
for (i, component) in components.as_vec().iter().enumerate() {
if i!= 0 {
final_str.push_str(", ");
}
final_str.push_str(&component.to_string());
}
return final_str;
}
#[test]
fn test_pretty_full_simple() {
let test_data = vec![
(Duration::days(365), "1 year, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(30), "0 years, 1 month, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::weeks(1), "0 years, 0 months, 1 week, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(1), "0 years, 0 months, 0 weeks, 1 day, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::hours(1), "0 years, 0 months, 0 weeks, 0 days, 1 hour, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::minutes(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 1 minute, 0 seconds, 0 milliseconds"),
(Duration::seconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 1 second, 0 milliseconds"),
(Duration::milliseconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 1 millisecond"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_full(dur), final_str);
}
}
#[test]
fn test_pretty_short() {
let test_data = vec![
(Duration::milliseconds(0), "0 milliseconds"),
(Duration::milliseconds(1), "1 millisecond"),
(-Duration::milliseconds(1), "1 millisecond"),
(Duration::milliseconds(200), "200 milliseconds"),
(Duration::seconds(1) + Duration::milliseconds(200), "1 second and 200 milliseconds"),
(Duration::days(1) + Duration::hours(2), "1 day and 2 hours"),
(Duration::days(1) + Duration::seconds(2), "1 day"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_short(dur), final_str);
}
}
| {
match second_component.and_then(has_second) {
Some(y) => {format!("{} and {}", x.to_string(), y.to_string())},
None => {x.to_string()}
}
} | conditional_block |
pretty.rs | use chrono::*;
pub use super::split;
pub fn pretty_short(dur: Duration) -> String {
let components = split::split_duration(dur).as_vec();
let mut components_iter = components.iter().skip_while(|a| a.val() == 0);
let first_component = components_iter.next();
let second_component = components_iter.next();
let final_str = match first_component {
Some(x) => {
match second_component.and_then(has_second) {
Some(y) => {format!("{} and {}", x.to_string(), y.to_string())},
None => {x.to_string()}
}
},
// The duration is 0
None => {split::TimePeriod::Millisecond(0).to_string()},
};
fn has_second(val: &split::TimePeriod) -> Option<&split::TimePeriod> {
if val.val() == 0 {return None};
return Some(val);
}
return final_str;
}
pub fn pretty_full(dur: Duration) -> String {
let components = split::split_duration(dur);
let mut final_str = String::new();
for (i, component) in components.as_vec().iter().enumerate() {
if i!= 0 {
final_str.push_str(", ");
}
final_str.push_str(&component.to_string());
}
return final_str;
}
#[test]
fn test_pretty_full_simple() {
let test_data = vec![
(Duration::days(365), "1 year, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(30), "0 years, 1 month, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::weeks(1), "0 years, 0 months, 1 week, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(1), "0 years, 0 months, 0 weeks, 1 day, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::hours(1), "0 years, 0 months, 0 weeks, 0 days, 1 hour, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::minutes(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 1 minute, 0 seconds, 0 milliseconds"),
(Duration::seconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 1 second, 0 milliseconds"),
(Duration::milliseconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 1 millisecond"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_full(dur), final_str);
}
}
#[test]
fn test_pretty_short() {
let test_data = vec![
(Duration::milliseconds(0), "0 milliseconds"),
(Duration::milliseconds(1), "1 millisecond"),
(-Duration::milliseconds(1), "1 millisecond"),
(Duration::milliseconds(200), "200 milliseconds"),
(Duration::seconds(1) + Duration::milliseconds(200), "1 second and 200 milliseconds"),
(Duration::days(1) + Duration::hours(2), "1 day and 2 hours"),
(Duration::days(1) + Duration::seconds(2), "1 day"),
];
for (dur, final_str) in test_data { | assert_eq!(pretty_short(dur), final_str);
}
} | random_line_split |
|
pretty.rs | use chrono::*;
pub use super::split;
pub fn pretty_short(dur: Duration) -> String {
let components = split::split_duration(dur).as_vec();
let mut components_iter = components.iter().skip_while(|a| a.val() == 0);
let first_component = components_iter.next();
let second_component = components_iter.next();
let final_str = match first_component {
Some(x) => {
match second_component.and_then(has_second) {
Some(y) => {format!("{} and {}", x.to_string(), y.to_string())},
None => {x.to_string()}
}
},
// The duration is 0
None => {split::TimePeriod::Millisecond(0).to_string()},
};
fn has_second(val: &split::TimePeriod) -> Option<&split::TimePeriod> {
if val.val() == 0 {return None};
return Some(val);
}
return final_str;
}
pub fn pretty_full(dur: Duration) -> String {
let components = split::split_duration(dur);
let mut final_str = String::new();
for (i, component) in components.as_vec().iter().enumerate() {
if i!= 0 {
final_str.push_str(", ");
}
final_str.push_str(&component.to_string());
}
return final_str;
}
#[test]
fn test_pretty_full_simple() {
let test_data = vec![
(Duration::days(365), "1 year, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(30), "0 years, 1 month, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::weeks(1), "0 years, 0 months, 1 week, 0 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::days(1), "0 years, 0 months, 0 weeks, 1 day, 0 hours, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::hours(1), "0 years, 0 months, 0 weeks, 0 days, 1 hour, 0 minutes, 0 seconds, 0 milliseconds"),
(Duration::minutes(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 1 minute, 0 seconds, 0 milliseconds"),
(Duration::seconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 1 second, 0 milliseconds"),
(Duration::milliseconds(1), "0 years, 0 months, 0 weeks, 0 days, 0 hours, 0 minutes, 0 seconds, 1 millisecond"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_full(dur), final_str);
}
}
#[test]
fn test_pretty_short() | {
let test_data = vec![
(Duration::milliseconds(0), "0 milliseconds"),
(Duration::milliseconds(1), "1 millisecond"),
(-Duration::milliseconds(1), "1 millisecond"),
(Duration::milliseconds(200), "200 milliseconds"),
(Duration::seconds(1) + Duration::milliseconds(200), "1 second and 200 milliseconds"),
(Duration::days(1) + Duration::hours(2), "1 day and 2 hours"),
(Duration::days(1) + Duration::seconds(2), "1 day"),
];
for (dur, final_str) in test_data {
assert_eq!(pretty_short(dur), final_str);
}
} | identifier_body |
|
build.rs | // Copyright (C) 2016 ParadoxSpiral
//
// This file is part of mpv-rs.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#[cfg(feature = "build_libmpv")]
use std::env;
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
use std::process::Command;
#[cfg(not(feature = "build_libmpv"))]
fn main() {}
#[cfg(all(feature = "build_libmpv", target_os = "windows"))]
fn main() { | let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
println!("cargo:rustc-link-search={}/64/", source);
} else {
println!("cargo:rustc-link-search={}/32/", source);
}
}
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
fn main() {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
let num_threads = env::var("NUM_JOBS").unwrap();
// `target` (in cfg) doesn't really mean target. It means target(host) of build script,
// which is a bit confusing because it means the actual `--target` everywhere else.
#[cfg(target_pointer_width = "64")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32" {
panic!("Cross-compiling to different arch not yet supported");
}
}
#[cfg(target_pointer_width = "32")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
panic!("Cross-compiling to different arch not yet supported");
}
}
// The mpv build script interprets the TARGET env var, which is set by cargo to e.g.
// x86_64-unknown-linux-gnu, thus the script can't find the compiler.
// TODO: When Cross-compiling to different archs is implemented, this has to be handled.
env::remove_var("TARGET");
let cmd = format!(
"cd {} && echo \"--enable-libmpv-shared\" > {0}/mpv_options \
&& {0}/build -j{}",
source, num_threads
);
Command::new("sh")
.arg("-c")
.arg(&cmd)
.spawn()
.expect("mpv-build build failed")
.wait()
.expect("mpv-build build failed");
println!("cargo:rustc-link-search={}/mpv/build/", source);
} | random_line_split |
|
build.rs | // Copyright (C) 2016 ParadoxSpiral
//
// This file is part of mpv-rs.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#[cfg(feature = "build_libmpv")]
use std::env;
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
use std::process::Command;
#[cfg(not(feature = "build_libmpv"))]
fn main() {}
#[cfg(all(feature = "build_libmpv", target_os = "windows"))]
fn | () {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
println!("cargo:rustc-link-search={}/64/", source);
} else {
println!("cargo:rustc-link-search={}/32/", source);
}
}
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
fn main() {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
let num_threads = env::var("NUM_JOBS").unwrap();
// `target` (in cfg) doesn't really mean target. It means target(host) of build script,
// which is a bit confusing because it means the actual `--target` everywhere else.
#[cfg(target_pointer_width = "64")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32" {
panic!("Cross-compiling to different arch not yet supported");
}
}
#[cfg(target_pointer_width = "32")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
panic!("Cross-compiling to different arch not yet supported");
}
}
// The mpv build script interprets the TARGET env var, which is set by cargo to e.g.
// x86_64-unknown-linux-gnu, thus the script can't find the compiler.
// TODO: When Cross-compiling to different archs is implemented, this has to be handled.
env::remove_var("TARGET");
let cmd = format!(
"cd {} && echo \"--enable-libmpv-shared\" > {0}/mpv_options \
&& {0}/build -j{}",
source, num_threads
);
Command::new("sh")
.arg("-c")
.arg(&cmd)
.spawn()
.expect("mpv-build build failed")
.wait()
.expect("mpv-build build failed");
println!("cargo:rustc-link-search={}/mpv/build/", source);
}
| main | identifier_name |
build.rs | // Copyright (C) 2016 ParadoxSpiral
//
// This file is part of mpv-rs.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#[cfg(feature = "build_libmpv")]
use std::env;
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
use std::process::Command;
#[cfg(not(feature = "build_libmpv"))]
fn main() {}
#[cfg(all(feature = "build_libmpv", target_os = "windows"))]
fn main() {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
println!("cargo:rustc-link-search={}/64/", source);
} else {
println!("cargo:rustc-link-search={}/32/", source);
}
}
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
fn main() | // x86_64-unknown-linux-gnu, thus the script can't find the compiler.
// TODO: When Cross-compiling to different archs is implemented, this has to be handled.
env::remove_var("TARGET");
let cmd = format!(
"cd {} && echo \"--enable-libmpv-shared\" > {0}/mpv_options \
&& {0}/build -j{}",
source, num_threads
);
Command::new("sh")
.arg("-c")
.arg(&cmd)
.spawn()
.expect("mpv-build build failed")
.wait()
.expect("mpv-build build failed");
println!("cargo:rustc-link-search={}/mpv/build/", source);
}
| {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
let num_threads = env::var("NUM_JOBS").unwrap();
// `target` (in cfg) doesn't really mean target. It means target(host) of build script,
// which is a bit confusing because it means the actual `--target` everywhere else.
#[cfg(target_pointer_width = "64")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32" {
panic!("Cross-compiling to different arch not yet supported");
}
}
#[cfg(target_pointer_width = "32")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
panic!("Cross-compiling to different arch not yet supported");
}
}
// The mpv build script interprets the TARGET env var, which is set by cargo to e.g. | identifier_body |
build.rs | // Copyright (C) 2016 ParadoxSpiral
//
// This file is part of mpv-rs.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#[cfg(feature = "build_libmpv")]
use std::env;
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
use std::process::Command;
#[cfg(not(feature = "build_libmpv"))]
fn main() {}
#[cfg(all(feature = "build_libmpv", target_os = "windows"))]
fn main() {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
println!("cargo:rustc-link-search={}/64/", source);
} else {
println!("cargo:rustc-link-search={}/32/", source);
}
}
#[cfg(all(feature = "build_libmpv", not(target_os = "windows")))]
fn main() {
let source = env::var("MPV_SOURCE").expect("env var `MPV_SOURCE` not set");
let num_threads = env::var("NUM_JOBS").unwrap();
// `target` (in cfg) doesn't really mean target. It means target(host) of build script,
// which is a bit confusing because it means the actual `--target` everywhere else.
#[cfg(target_pointer_width = "64")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "32" |
}
#[cfg(target_pointer_width = "32")]
{
if env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap() == "64" {
panic!("Cross-compiling to different arch not yet supported");
}
}
// The mpv build script interprets the TARGET env var, which is set by cargo to e.g.
// x86_64-unknown-linux-gnu, thus the script can't find the compiler.
// TODO: When Cross-compiling to different archs is implemented, this has to be handled.
env::remove_var("TARGET");
let cmd = format!(
"cd {} && echo \"--enable-libmpv-shared\" > {0}/mpv_options \
&& {0}/build -j{}",
source, num_threads
);
Command::new("sh")
.arg("-c")
.arg(&cmd)
.spawn()
.expect("mpv-build build failed")
.wait()
.expect("mpv-build build failed");
println!("cargo:rustc-link-search={}/mpv/build/", source);
}
| {
panic!("Cross-compiling to different arch not yet supported");
} | conditional_block |
expr-block-generic-box2.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.
#![feature(managed_boxes)]
type compare<'a, T> = |T, T|: 'a -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = { expected.clone() };
assert!((eq(expected, actual)));
}
fn test_vec() |
pub fn main() { test_vec(); }
| {
fn compare_vec(v1: @int, v2: @int) -> bool { return v1 == v2; }
test_generic::<@int>(@1, compare_vec);
} | identifier_body |
expr-block-generic-box2.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.
#![feature(managed_boxes)]
type compare<'a, T> = |T, T|: 'a -> bool;
fn | <T:Clone>(expected: T, eq: compare<T>) {
let actual: T = { expected.clone() };
assert!((eq(expected, actual)));
}
fn test_vec() {
fn compare_vec(v1: @int, v2: @int) -> bool { return v1 == v2; }
test_generic::<@int>(@1, compare_vec);
}
pub fn main() { test_vec(); }
| test_generic | identifier_name |
expr-block-generic-box2.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.
#![feature(managed_boxes)]
type compare<'a, T> = |T, T|: 'a -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = { expected.clone() };
assert!((eq(expected, actual)));
}
|
pub fn main() { test_vec(); } | fn test_vec() {
fn compare_vec(v1: @int, v2: @int) -> bool { return v1 == v2; }
test_generic::<@int>(@1, compare_vec);
} | random_line_split |
htmlbaseelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use url::{Url, UrlParser};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(""), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
let document = document_from_node(self);
let base = document.fallback_base_url();
let parsed = UrlParser::new().base_url(&base).parse(&href.value());
parsed.unwrap_or(base)
}
/// Update the cached base element in response to binding or unbinding from
/// a tree.
pub fn bind_unbind(&self, tree_in_doc: bool) |
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if *attr.local_name() == atom!(href) {
document_from_node(self).refresh_base_element();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().bind_to_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().unbind_from_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
}
| {
if !tree_in_doc {
return;
}
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
} | identifier_body |
htmlbaseelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use url::{Url, UrlParser};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(""), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
let document = document_from_node(self);
let base = document.fallback_base_url();
let parsed = UrlParser::new().base_url(&base).parse(&href.value());
parsed.unwrap_or(base)
}
/// Update the cached base element in response to binding or unbinding from
/// a tree.
pub fn bind_unbind(&self, tree_in_doc: bool) {
if!tree_in_doc {
return;
}
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
}
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if *attr.local_name() == atom!(href) {
document_from_node(self).refresh_base_element();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().bind_to_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().unbind_from_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
}
| new | identifier_name |
htmlbaseelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use url::{Url, UrlParser};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(""), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
let document = document_from_node(self);
let base = document.fallback_base_url();
let parsed = UrlParser::new().base_url(&base).parse(&href.value());
parsed.unwrap_or(base)
}
/// Update the cached base element in response to binding or unbinding from
/// a tree.
pub fn bind_unbind(&self, tree_in_doc: bool) {
if!tree_in_doc {
return;
}
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
}
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if *attr.local_name() == atom!(href) {
document_from_node(self).refresh_base_element();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().bind_to_tree(tree_in_doc);
self.bind_unbind(tree_in_doc); | fn unbind_from_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().unbind_from_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
} | }
| random_line_split |
htmlbaseelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use url::{Url, UrlParser};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBaseElement {
htmlelement: HTMLElement
}
impl HTMLBaseElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
/// https://html.spec.whatwg.org/multipage/#frozen-base-url
pub fn frozen_base_url(&self) -> Url {
let href = self.upcast::<Element>().get_attribute(&ns!(""), &atom!("href"))
.expect("The frozen base url is only defined for base elements \
that have a base url.");
let document = document_from_node(self);
let base = document.fallback_base_url();
let parsed = UrlParser::new().base_url(&base).parse(&href.value());
parsed.unwrap_or(base)
}
/// Update the cached base element in response to binding or unbinding from
/// a tree.
pub fn bind_unbind(&self, tree_in_doc: bool) {
if!tree_in_doc |
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
}
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if *attr.local_name() == atom!(href) {
document_from_node(self).refresh_base_element();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().bind_to_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().unbind_from_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
}
| {
return;
} | conditional_block |
rot.rs | pub struct Rot {
pub s: f32,
pub c: f32
}
impl Rot {
pub fn new() -> Rot {
Rot {
s: 0.0,
c: 1.0
}
}
/// Initialize from an angle in radians
pub fn new_angle(angle: f32) -> Rot {
Rot {
s: angle.sin(),
c: angle.cos()
}
}
pub fn set(&mut self, angle: f32) {
self.s = angle.sin();
self.c = angle.cos();
}
/// Set to the identity rotation
pub fn set_identity(&mut self) {
self.s = 0.0;
self.c = 1.0;
}
/// Get the angle in radians
pub fn get_angle(&mut self) -> f32 {
self.s.atan2(self.c)
}
/// Get the x-axis
pub fn get_x_axis(&mut self) -> Vec2 {
Vec2::new(self.c, self.s)
}
/// Get the u axis
pub fn get_y_axis(&mut self) -> Vec2 {
Vec2::new(-self.s, self.c)
}
} | use super::Vec2;
/// Rotation
#[derive(Copy, Clone)] | random_line_split |
|
rot.rs | use super::Vec2;
/// Rotation
#[derive(Copy, Clone)]
pub struct | {
pub s: f32,
pub c: f32
}
impl Rot {
pub fn new() -> Rot {
Rot {
s: 0.0,
c: 1.0
}
}
/// Initialize from an angle in radians
pub fn new_angle(angle: f32) -> Rot {
Rot {
s: angle.sin(),
c: angle.cos()
}
}
pub fn set(&mut self, angle: f32) {
self.s = angle.sin();
self.c = angle.cos();
}
/// Set to the identity rotation
pub fn set_identity(&mut self) {
self.s = 0.0;
self.c = 1.0;
}
/// Get the angle in radians
pub fn get_angle(&mut self) -> f32 {
self.s.atan2(self.c)
}
/// Get the x-axis
pub fn get_x_axis(&mut self) -> Vec2 {
Vec2::new(self.c, self.s)
}
/// Get the u axis
pub fn get_y_axis(&mut self) -> Vec2 {
Vec2::new(-self.s, self.c)
}
}
| Rot | identifier_name |
personal.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use std::str::FromStr;
use jsonrpc_core::{IoHandler, GenericIoHandler};
use util::{U256, Uint, Address};
use ethcore::account_provider::AccountProvider;
use v1::{PersonalClient, Personal};
use v1::tests::helpers::TestMinerService;
use ethcore::client::TestBlockChainClient;
use ethcore::transaction::{Action, Transaction};
struct PersonalTester {
accounts: Arc<AccountProvider>,
io: IoHandler,
miner: Arc<TestMinerService>,
// these unused fields are necessary to keep the data alive
// as the handler has only weak pointers.
_client: Arc<TestBlockChainClient>,
}
fn blockchain_client() -> Arc<TestBlockChainClient> {
let client = TestBlockChainClient::new();
Arc::new(client)
}
fn accounts_provider() -> Arc<AccountProvider> {
Arc::new(AccountProvider::transient_provider())
}
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
fn setup() -> PersonalTester {
let accounts = accounts_provider();
let client = blockchain_client();
let miner = miner_service();
let personal = PersonalClient::new(&accounts, &client, &miner, false);
let io = IoHandler::new();
io.add_delegate(personal.to_delegate());
let tester = PersonalTester {
accounts: accounts,
io: io,
miner: miner,
_client: client,
};
tester
}
#[test]
fn accounts() {
let tester = setup();
let address = tester.accounts.new_account("").unwrap();
let request = r#"{"jsonrpc": "2.0", "method": "personal_listAccounts", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:?}", address) + r#""],"id":1}"#;
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn new_account() {
let tester = setup();
let request = r#"{"jsonrpc": "2.0", "method": "personal_newAccount", "params": ["pass"], "id": 1}"#;
let res = tester.io.handle_request_sync(request);
let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"","id":1}"#;
assert_eq!(res, Some(response));
}
#[test]
fn sign_and_send_transaction_with_invalid_password() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_signAndSendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}, "password321"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32021,"message":"Account password is invalid or account does not exist.","data":"SStore(InvalidPassword)"},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response.into()));
}
#[test]
fn sign_and_send_transaction() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_signAndSendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}, "password123"],
"id": 1
}"#;
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
tester.accounts.unlock_account_temporarily(address, "password123".into()).unwrap();
let signature = tester.accounts.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response));
tester.miner.last_nonces.write().insert(address.clone(), U256::zero());
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
tester.accounts.unlock_account_temporarily(address, "password123".into()).unwrap();
let signature = tester.accounts.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response));
}
#[test]
fn should_unlock_account_temporarily() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_unlockAccount",
"params": [
""#.to_owned() + &format!("0x{:?}", address) + r#"",
"password123",
"0x100"
],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
}
#[test]
fn should_unlock_account_permanently() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_unlockAccount",
"params": [
""#.to_owned() + &format!("0x{:?}", address) + r#"",
"password123",
null
],
"id": 1 | let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
} | }"#; | random_line_split |
personal.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use std::str::FromStr;
use jsonrpc_core::{IoHandler, GenericIoHandler};
use util::{U256, Uint, Address};
use ethcore::account_provider::AccountProvider;
use v1::{PersonalClient, Personal};
use v1::tests::helpers::TestMinerService;
use ethcore::client::TestBlockChainClient;
use ethcore::transaction::{Action, Transaction};
struct PersonalTester {
accounts: Arc<AccountProvider>,
io: IoHandler,
miner: Arc<TestMinerService>,
// these unused fields are necessary to keep the data alive
// as the handler has only weak pointers.
_client: Arc<TestBlockChainClient>,
}
fn blockchain_client() -> Arc<TestBlockChainClient> {
let client = TestBlockChainClient::new();
Arc::new(client)
}
fn accounts_provider() -> Arc<AccountProvider> {
Arc::new(AccountProvider::transient_provider())
}
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
fn setup() -> PersonalTester {
let accounts = accounts_provider();
let client = blockchain_client();
let miner = miner_service();
let personal = PersonalClient::new(&accounts, &client, &miner, false);
let io = IoHandler::new();
io.add_delegate(personal.to_delegate());
let tester = PersonalTester {
accounts: accounts,
io: io,
miner: miner,
_client: client,
};
tester
}
#[test]
fn accounts() {
let tester = setup();
let address = tester.accounts.new_account("").unwrap();
let request = r#"{"jsonrpc": "2.0", "method": "personal_listAccounts", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:?}", address) + r#""],"id":1}"#;
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn new_account() {
let tester = setup();
let request = r#"{"jsonrpc": "2.0", "method": "personal_newAccount", "params": ["pass"], "id": 1}"#;
let res = tester.io.handle_request_sync(request);
let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts[0];
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"","id":1}"#;
assert_eq!(res, Some(response));
}
#[test]
fn sign_and_send_transaction_with_invalid_password() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_signAndSendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}, "password321"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32021,"message":"Account password is invalid or account does not exist.","data":"SStore(InvalidPassword)"},"id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response.into()));
}
#[test]
fn sign_and_send_transaction() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_signAndSendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}, "password123"],
"id": 1
}"#;
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
tester.accounts.unlock_account_temporarily(address, "password123".into()).unwrap();
let signature = tester.accounts.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response));
tester.miner.last_nonces.write().insert(address.clone(), U256::zero());
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
};
tester.accounts.unlock_account_temporarily(address, "password123".into()).unwrap();
let signature = tester.accounts.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request_sync(request.as_ref()), Some(response));
}
#[test]
fn | () {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_unlockAccount",
"params": [
""#.to_owned() + &format!("0x{:?}", address) + r#"",
"password123",
"0x100"
],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
}
#[test]
fn should_unlock_account_permanently() {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_unlockAccount",
"params": [
""#.to_owned() + &format!("0x{:?}", address) + r#"",
"password123",
null
],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
}
| should_unlock_account_temporarily | identifier_name |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32> |
/// Takes a vec and breaks it up to do calculations
pub fn do_calc(data: Vec<i32>)->Vec<i32>{
let mut package = vec![data];
let start = time::precise_time_ns();
for _ in 0..2 {
package = break_vec(package);
}
let stop = time::precise_time_ns();
println!("split time: {}", stop - start);
let count = package.len();
let (tx, rx) = mpsc::channel();
for vec in package {
let tx = tx.clone();
let data_t = vec;
thread::spawn(move || {
let mut ret = Vec::new();
for x in data_t {
ret.push(x * 7);
}
tx.send(ret);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..count {
let mut source = rx.recv().ok().expect("Could not receive answer");
ret.append(&mut source);
}
ret
}
/// Takes the vectors inside a vector and splits them in half
/// No checking is done to miss rounding errors
fn break_vec(data: Vec<Vec<i32>>)->Vec<Vec<i32>>{
let mut ret: Vec<Vec<i32>> = Vec::new();
for mut vec in data {
let size = vec.len()/2;
let vec1 = vec.split_off(size);
ret.push(vec);
ret.push(vec1);
}
ret
}
/// Takes some data makes four copies and modifies each copy in a thread
///
///# Examples
pub fn shared_data_example(){
//never do it this way thread::sleep is there to ensure all thread complete
//clearly not a good idea
let numbers: Vec<_> = (5..15i32).collect();
let shared_numbers = Arc::new(numbers);
for thread_no in 0..3 {
println!("threadno: {}", thread_no);
let child_numbers = shared_numbers.clone();
thread::spawn(move || {
let local_numbers = &child_numbers[..];
// Work with the local numbers
for x in local_numbers {
let x = x+1;
println!("threadno: {} mod data: {}", thread_no, x);
}
});
}
thread::sleep_ms(1000);
}
/// Simple example of multi provider single consumer
pub fn simple_mpsc()->Vec<i32>{
let (tx, rx) = mpsc::channel();
for _ in 0..10 {
let tx = tx.clone();
thread::spawn(move || {
let answer = 42;
tx.send(answer);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..10 {
ret.push(rx.recv().ok().expect("Could not receive answer"));
}
ret
}
/// Simple example of spawning a thread and rejoining
/// Also handles a panic during thread execution for graceful recovery
pub fn thread_handle(){
use std::thread;
let handle = thread::spawn(move || {
panic!("oops!");
});
let result = handle.join();
assert!(result.is_err());
}
| {
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
let mut ret = Vec::new();
for x in data {
ret.push(x * 7);
}
tx.send(ret);
});
rx.recv().ok().expect("Could not receive answer")
} | identifier_body |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32>{
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
let mut ret = Vec::new();
for x in data {
ret.push(x * 7);
}
tx.send(ret);
});
rx.recv().ok().expect("Could not receive answer")
}
/// Takes a vec and breaks it up to do calculations
pub fn do_calc(data: Vec<i32>)->Vec<i32>{
let mut package = vec![data];
let start = time::precise_time_ns();
for _ in 0..2 {
package = break_vec(package);
}
let stop = time::precise_time_ns();
println!("split time: {}", stop - start);
let count = package.len();
let (tx, rx) = mpsc::channel();
for vec in package {
let tx = tx.clone();
let data_t = vec;
thread::spawn(move || {
let mut ret = Vec::new();
for x in data_t {
ret.push(x * 7);
}
tx.send(ret);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..count {
let mut source = rx.recv().ok().expect("Could not receive answer");
ret.append(&mut source);
}
ret
}
/// Takes the vectors inside a vector and splits them in half
/// No checking is done to miss rounding errors
fn break_vec(data: Vec<Vec<i32>>)->Vec<Vec<i32>>{
let mut ret: Vec<Vec<i32>> = Vec::new();
for mut vec in data {
let size = vec.len()/2;
let vec1 = vec.split_off(size);
ret.push(vec);
ret.push(vec1);
}
ret
}
/// Takes some data makes four copies and modifies each copy in a thread
///
///# Examples
pub fn shared_data_example(){
//never do it this way thread::sleep is there to ensure all thread complete
//clearly not a good idea
let numbers: Vec<_> = (5..15i32).collect();
let shared_numbers = Arc::new(numbers);
for thread_no in 0..3 {
println!("threadno: {}", thread_no);
let child_numbers = shared_numbers.clone();
thread::spawn(move || {
let local_numbers = &child_numbers[..];
// Work with the local numbers
for x in local_numbers {
let x = x+1;
println!("threadno: {} mod data: {}", thread_no, x);
}
});
}
thread::sleep_ms(1000); | for _ in 0..10 {
let tx = tx.clone();
thread::spawn(move || {
let answer = 42;
tx.send(answer);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..10 {
ret.push(rx.recv().ok().expect("Could not receive answer"));
}
ret
}
/// Simple example of spawning a thread and rejoining
/// Also handles a panic during thread execution for graceful recovery
pub fn thread_handle(){
use std::thread;
let handle = thread::spawn(move || {
panic!("oops!");
});
let result = handle.join();
assert!(result.is_err());
} | }
/// Simple example of multi provider single consumer
pub fn simple_mpsc()->Vec<i32>{
let (tx, rx) = mpsc::channel(); | random_line_split |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32>{
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
let mut ret = Vec::new();
for x in data {
ret.push(x * 7);
}
tx.send(ret);
});
rx.recv().ok().expect("Could not receive answer")
}
/// Takes a vec and breaks it up to do calculations
pub fn do_calc(data: Vec<i32>)->Vec<i32>{
let mut package = vec![data];
let start = time::precise_time_ns();
for _ in 0..2 {
package = break_vec(package);
}
let stop = time::precise_time_ns();
println!("split time: {}", stop - start);
let count = package.len();
let (tx, rx) = mpsc::channel();
for vec in package {
let tx = tx.clone();
let data_t = vec;
thread::spawn(move || {
let mut ret = Vec::new();
for x in data_t {
ret.push(x * 7);
}
tx.send(ret);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..count {
let mut source = rx.recv().ok().expect("Could not receive answer");
ret.append(&mut source);
}
ret
}
/// Takes the vectors inside a vector and splits them in half
/// No checking is done to miss rounding errors
fn break_vec(data: Vec<Vec<i32>>)->Vec<Vec<i32>>{
let mut ret: Vec<Vec<i32>> = Vec::new();
for mut vec in data {
let size = vec.len()/2;
let vec1 = vec.split_off(size);
ret.push(vec);
ret.push(vec1);
}
ret
}
/// Takes some data makes four copies and modifies each copy in a thread
///
///# Examples
pub fn shared_data_example(){
//never do it this way thread::sleep is there to ensure all thread complete
//clearly not a good idea
let numbers: Vec<_> = (5..15i32).collect();
let shared_numbers = Arc::new(numbers);
for thread_no in 0..3 {
println!("threadno: {}", thread_no);
let child_numbers = shared_numbers.clone();
thread::spawn(move || {
let local_numbers = &child_numbers[..];
// Work with the local numbers
for x in local_numbers {
let x = x+1;
println!("threadno: {} mod data: {}", thread_no, x);
}
});
}
thread::sleep_ms(1000);
}
/// Simple example of multi provider single consumer
pub fn simple_mpsc()->Vec<i32>{
let (tx, rx) = mpsc::channel();
for _ in 0..10 {
let tx = tx.clone();
thread::spawn(move || {
let answer = 42;
tx.send(answer);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..10 {
ret.push(rx.recv().ok().expect("Could not receive answer"));
}
ret
}
/// Simple example of spawning a thread and rejoining
/// Also handles a panic during thread execution for graceful recovery
pub fn | (){
use std::thread;
let handle = thread::spawn(move || {
panic!("oops!");
});
let result = handle.join();
assert!(result.is_err());
}
| thread_handle | identifier_name |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() {
let mut an_option = Some(1);
let _ = mem::replace(&mut an_option, None);
let an_option = &mut Some(1);
let _ = mem::replace(an_option, None);
}
fn | () {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem::replace(&mut v, Vec::default());
let _ = std::mem::replace(&mut v, Default::default());
let _ = std::mem::replace(&mut v, Vec::new());
let _ = std::mem::replace(&mut v, vec![]);
let mut hash_map: HashMap<i32, i32> = HashMap::new();
let _ = std::mem::replace(&mut hash_map, HashMap::new());
let mut btree_map: BTreeMap<i32, i32> = BTreeMap::new();
let _ = std::mem::replace(&mut btree_map, BTreeMap::new());
let mut vd: VecDeque<i32> = VecDeque::new();
let _ = std::mem::replace(&mut vd, VecDeque::new());
let mut hash_set: HashSet<&str> = HashSet::new();
let _ = std::mem::replace(&mut hash_set, HashSet::new());
let mut btree_set: BTreeSet<&str> = BTreeSet::new();
let _ = std::mem::replace(&mut btree_set, BTreeSet::new());
let mut list: LinkedList<i32> = LinkedList::new();
let _ = std::mem::replace(&mut list, LinkedList::new());
let mut binary_heap: BinaryHeap<i32> = BinaryHeap::new();
let _ = std::mem::replace(&mut binary_heap, BinaryHeap::new());
let mut tuple = (vec![1, 2], BinaryHeap::<i32>::new());
let _ = std::mem::replace(&mut tuple, (vec![], BinaryHeap::new()));
let mut refstr = "hello";
let _ = std::mem::replace(&mut refstr, "");
let mut slice: &[i32] = &[1, 2, 3];
let _ = std::mem::replace(&mut slice, &[]);
}
// lint is disabled for primitives because in this case `take`
// has no clear benefit over `replace` and sometimes is harder to read
fn dont_lint_primitive() {
let mut pbool = true;
let _ = std::mem::replace(&mut pbool, false);
let mut pint = 5;
let _ = std::mem::replace(&mut pint, 0);
}
fn main() {
replace_option_with_none();
replace_with_default();
dont_lint_primitive();
}
| replace_with_default | identifier_name |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() |
fn replace_with_default() {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem::replace(&mut v, Vec::default());
let _ = std::mem::replace(&mut v, Default::default());
let _ = std::mem::replace(&mut v, Vec::new());
let _ = std::mem::replace(&mut v, vec![]);
let mut hash_map: HashMap<i32, i32> = HashMap::new();
let _ = std::mem::replace(&mut hash_map, HashMap::new());
let mut btree_map: BTreeMap<i32, i32> = BTreeMap::new();
let _ = std::mem::replace(&mut btree_map, BTreeMap::new());
let mut vd: VecDeque<i32> = VecDeque::new();
let _ = std::mem::replace(&mut vd, VecDeque::new());
let mut hash_set: HashSet<&str> = HashSet::new();
let _ = std::mem::replace(&mut hash_set, HashSet::new());
let mut btree_set: BTreeSet<&str> = BTreeSet::new();
let _ = std::mem::replace(&mut btree_set, BTreeSet::new());
let mut list: LinkedList<i32> = LinkedList::new();
let _ = std::mem::replace(&mut list, LinkedList::new());
let mut binary_heap: BinaryHeap<i32> = BinaryHeap::new();
let _ = std::mem::replace(&mut binary_heap, BinaryHeap::new());
let mut tuple = (vec![1, 2], BinaryHeap::<i32>::new());
let _ = std::mem::replace(&mut tuple, (vec![], BinaryHeap::new()));
let mut refstr = "hello";
let _ = std::mem::replace(&mut refstr, "");
let mut slice: &[i32] = &[1, 2, 3];
let _ = std::mem::replace(&mut slice, &[]);
}
// lint is disabled for primitives because in this case `take`
// has no clear benefit over `replace` and sometimes is harder to read
fn dont_lint_primitive() {
let mut pbool = true;
let _ = std::mem::replace(&mut pbool, false);
let mut pint = 5;
let _ = std::mem::replace(&mut pint, 0);
}
fn main() {
replace_option_with_none();
replace_with_default();
dont_lint_primitive();
}
| {
let mut an_option = Some(1);
let _ = mem::replace(&mut an_option, None);
let an_option = &mut Some(1);
let _ = mem::replace(an_option, None);
} | identifier_body |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() { |
fn replace_with_default() {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem::replace(&mut v, Vec::default());
let _ = std::mem::replace(&mut v, Default::default());
let _ = std::mem::replace(&mut v, Vec::new());
let _ = std::mem::replace(&mut v, vec![]);
let mut hash_map: HashMap<i32, i32> = HashMap::new();
let _ = std::mem::replace(&mut hash_map, HashMap::new());
let mut btree_map: BTreeMap<i32, i32> = BTreeMap::new();
let _ = std::mem::replace(&mut btree_map, BTreeMap::new());
let mut vd: VecDeque<i32> = VecDeque::new();
let _ = std::mem::replace(&mut vd, VecDeque::new());
let mut hash_set: HashSet<&str> = HashSet::new();
let _ = std::mem::replace(&mut hash_set, HashSet::new());
let mut btree_set: BTreeSet<&str> = BTreeSet::new();
let _ = std::mem::replace(&mut btree_set, BTreeSet::new());
let mut list: LinkedList<i32> = LinkedList::new();
let _ = std::mem::replace(&mut list, LinkedList::new());
let mut binary_heap: BinaryHeap<i32> = BinaryHeap::new();
let _ = std::mem::replace(&mut binary_heap, BinaryHeap::new());
let mut tuple = (vec![1, 2], BinaryHeap::<i32>::new());
let _ = std::mem::replace(&mut tuple, (vec![], BinaryHeap::new()));
let mut refstr = "hello";
let _ = std::mem::replace(&mut refstr, "");
let mut slice: &[i32] = &[1, 2, 3];
let _ = std::mem::replace(&mut slice, &[]);
}
// lint is disabled for primitives because in this case `take`
// has no clear benefit over `replace` and sometimes is harder to read
fn dont_lint_primitive() {
let mut pbool = true;
let _ = std::mem::replace(&mut pbool, false);
let mut pint = 5;
let _ = std::mem::replace(&mut pint, 0);
}
fn main() {
replace_option_with_none();
replace_with_default();
dont_lint_primitive();
} | let mut an_option = Some(1);
let _ = mem::replace(&mut an_option, None);
let an_option = &mut Some(1);
let _ = mem::replace(an_option, None);
} | 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/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "style_traits"]
#![crate_type = "rlib"]
#![feature(custom_derive)]
#![feature(plugin)]
#![plugin(serde_macros)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#[macro_use] | extern crate cssparser;
extern crate euclid;
extern crate rustc_serialize;
extern crate serde;
extern crate util;
#[macro_use]
pub mod values;
pub mod viewport;
use cssparser::{Parser, SourcePosition};
pub trait ParseErrorReporter {
fn report_error(&self, input: &mut Parser, position: SourcePosition, message: &str);
fn clone(&self) -> Box<ParseErrorReporter + Send + Sync>;
} | random_line_split |
|
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Link {
pub fn new(from: ID, to: ID, quality: u16) -> Self {
Self {from, to, quality, cost: 1}
}
pub fn cost(&self) -> u16 {
self.cost
}
pub fn bandwidth(&self) -> u16 {
1
}
pub fn quality(&self) -> u16 {
self.quality
}
fn cmp(&self, from: ID, to: ID) -> Ordering {
let i = ((self.from as u64) << 32) + (self.to as u64);
let j = ((from as u64) << 32) + (to as u64);
i.cmp(&j)
}
}
impl fmt::Debug for Link {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{} => {}}}", self.from, self.to)
}
}
/*
* This graph is designed for fast iteration and access of neighbors.
*/
#[derive(Clone)]
pub struct Graph {
pub links: Vec<Link>, // sorted link list
pub node_count: usize,
}
impl Graph {
pub fn new() -> Self {
Self {
links: vec![],
node_count: 0,
}
}
pub fn clear(&mut self) {
self.links.clear();
self.node_count = 0;
}
pub fn connect(&mut self, a: ID, b: ID) {
self.add_link(a, b, std::u16::MAX);
self.add_link(b, a, std::u16::MAX);
}
pub fn add_nodes(&mut self, count: u32) {
self.node_count += count as usize;
}
pub fn add_graph(&mut self, graph: Graph) {
let nlen = self.node_count as ID;
let llen = self.links.len();
self.node_count += graph.node_count;
self.links.extend(graph.links);
for link in &mut self.links[llen..] {
link.from += nlen;
link.to += nlen;
}
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn disconnect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.del_link(*a, *b);
}
}
}
pub fn connect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.connect(*a, *b);
}
}
}
// Check if all nodes have the same degree
pub fn is_regular(&self) -> bool {
let mut from = 0;
let mut n = 0;
let mut prev_n = 0;
for (i, link) in self.links.iter().enumerate() {
if from!= link.from {
from = link.from;
if i > 0 && prev_n!= n {
return false;
}
prev_n = n;
}
n += 1;
}
true
}
/*
//https://www.youtube.com/watch?v=YbCn8d4Enos
//rename node => vertex and link to edge?
// maximum of the minimal distances from id to any other node
pub fn get_node_eccentricity(&self, id: ID) -> f32 {
}
// minimum eccentricity of all vertices
pub fn get_radius(&self) -> f32 {
}
// maximum eccentricity of all vertices
pub fn get_diameter(&self) -> f32 {
}
pub fn get_peripheral_nodes(&self) -> Vec<ID> {
}
pub fn get_central_nodes(&self) -> Vec<ID> {
}
fn pos_distance(a: &[f32; 3], b: &[f32; 3]) -> f32 {
((a[0] - b[0]).powi(2)
+ (a[1] - b[2]).powi(2)
+ (a[2] - b[2]).powi(2)).sqrt()
}
pub fn get_mean_link_distance(&self) -> (f32, f32) {
let mut d = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
d += Self::pos_distance(&p1, &p2);
}
let mean = d / self.links.len() as f32;
let mut v = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
v += (Self::pos_distance(&p1, &p2) - mean).powi(2);
}
let variance = ((v as f32) / (self.links.len() as f32)).sqrt();
(mean, variance)
}
*/
pub fn get_node_degree(&self, id: ID) -> u32 {
self.get_neighbors(id).len() as u32
}
pub fn get_avg_node_degree(&self) -> f32 {
let mut n = 0;
for id in 0..self.node_count {
n += self.get_node_degree(id as u32);
}
(n as f32) / (self.node_count as f32)
}
pub fn get_mean_clustering_coefficient(&self) -> f32 {
let mut cc = 0.0f32;
for id in 0..self.node_count {
cc += self.get_local_clustering_coefficient(id as u32);
}
cc / (self.node_count as f32)
}
// Get neighbor count mean and variance
pub fn get_mean_link_count(&self) -> (f32, f32) {
let mut degrees = Vec::new();
let mut v = 0.0;
let mut c = 0;
let len = self.node_count as u32;
// calculate mean
for id in 0..len {
let degree = self.get_node_degree(id);
c += degree;
degrees.push(degree);
}
// calculate variance
let mean = c as f32 / len as f32;
for degree in degrees {
v += (degree as f32 - mean).powi(2);
}
let variance = ((v as f32) / (len as f32)).sqrt();
(mean, variance)
}
/*
pub fn link_distances(&self) -> (f32, f32, f32) {
let mut d2_min = infinity;
let mut d2_max = -infinity;
let mut d2_sum = 0.0;
for link in &self.links {
let to = self.nodes[link.to].gpos;
let from = self.nodes[link.from].gpos;
let d2 = from * to;
if d2 < d2_min {
d2_min = d2;
}
if d2 > d2_max {
d2_max = d2;
}
d2_sum += d2;
}
(d2_min.sqrt(), d2_mean.sqrt(), d2_max.sqrt())
}
//linear mapping
pub fn adjust_link_quality(&mut self, min: f32, max: f32) {
for link in &mut self.links {
let from = self.nodes[link.from as usize].pos;
let to = self.nodes[link.to as usize].pos;
let distance = Self::pos_distance(&from, &to);
if distance <= min {
link.quality = u16::MIN;
} else if distance >= max {
link.quality = u16::MAX;
} else {
link.quality = (u16::MAX as f32 * (distance - min) / (max - min)) as u16;
}
}
}
*/
pub fn has_link(&self, from: ID, to: ID) -> bool {
if let Some(_) = self.link_idx(from, to) {
true
} else {
false
}
}
fn has_any_link(&self, from: ID, to: ID) -> bool {
self.has_link(from, to) || self.has_link(to, from)
}
/*
* Calcualte connections between neighbors of a given node
* divided by maximim possible connections between those neihgbors.
* Method by Watts and Strogatz.
*/
pub fn get_local_clustering_coefficient(&self, id: ID) -> f32 {
//TODO: also count the connections from neighbors to node?
let ns = self.get_neighbors(id);
if ns.len() <= 1 {
0.0
} else {
// count number of connections between neighbors
let mut k = 0;
for a in ns {
for b in ns {
if a.to!= b.to {
k += self.has_link(a.to, b.to) as u32;
}
}
}
(k as f32) / (ns.len() * (ns.len() - 1)) as f32
}
}
fn del_link(&mut self, a: ID, b: ID) {
self.del_links(&vec![a, b]);
}
pub fn del_links(&mut self, links: &Vec<ID>) {
if (links.len() % 2)!= 0 {
panic!("del_links: Uneven elements for link list");
}
fn any(link: &Link, a: ID, b: ID) -> bool {
(link.from == a && link.to == b) || (link.from == b || link.to == a)
}
self.links.retain(|link| {
for s in links.chunks(2) {
if any(&link, s[0], s[1]) {
return false;
}
}
true
});
}
pub fn is_bidirectional(&self) -> bool {
for link in &self.links {
if!self.has_link(link.to, link.from) {
return false;
}
}
true
}
pub fn is_valid(&self) -> bool {
let len = self.node_count as ID;
for (i, link) in self.links.iter().enumerate() {
if link.to >= len || link.from >= len {
return false;
}
if i > 0 {
let prev = &self.links[i-1];
// check for order and duplicate links
if!(link.from > prev.from || (link.from == prev.from && link.to > prev.to)) {
return false;
}
}
}
true
}
pub fn remove_node(&mut self, id: ID) {
if self.node_count == 0 {
return;
}
self.node_count -= 1;
// adjust index
for link in &mut self.links {
if link.to > id {
link.to -= 1;
}
if link.from > id {
link.from -= 1;
}
}
// remove links
vec_filter(&mut self.links, |ref link| link.from!= id && link.to!= id);
// sort
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn remove_nodes(&mut self, nodes: &Vec<ID>) {
for id in nodes {
self.remove_node(*id);
}
}
fn link_idx(&self, from: ID, to: ID) -> Option<usize> {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
Some(idx)
},
Err(_) => {
None
}
}
}
pub fn get_link(&self, from: ID, to: ID) -> Option<Link> {
if let Some(idx) = self.link_idx(from, to) {
Some(self.links[idx].clone())
} else {
None
}
}
pub fn add_link(&mut self, from: ID, to: ID, tq: u16) {
if from!= to {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
self.links[idx].quality = tq;
},
Err(idx) => {
self.links.insert(idx, Link::new(from, to, tq));
}
}
}
}
pub fn get_neighbors(&self, id: ID) -> &[Link] {
match self.links.binary_search_by(|link| link.from.cmp(&id)) {
Ok(idx) => {
let mut start = idx;
let mut end = idx;
for i in (0..idx).rev() {
if self.links[i].from == id {
start = i;
}
}
for i in idx..self.links.len() {
if self.links[i].from == id {
end = i;
}
}
&self.links[start..end+1]
},
Err(idx) => {
&self.links[0..0]
}
}
}
pub fn clear_links(&mut self) {
self.links.clear();
}
pub fn is_directed(&self) -> bool {
for link in &self.links {
if self.link_idx(link.to, link.from).is_none() |
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_count as ID {
if self.get_node_degree(id) == 0 {
remove.push(id);
}
}
self.remove_nodes(&remove);
}
pub fn node_count(&self) -> usize {
self.node_count
}
pub fn link_count(&self) -> usize {
self.links.len()
}
pub fn link_cost_sum(&self) -> f32 {
self.links.iter().fold(0.0, |acc, link| acc + link.cost() as f32)
}
pub fn spanning_tree(&self) -> Graph {
Self::minimum_spanning_tree_impl(&self.links, self.node_count)
}
pub fn minimum_spanning_tree(&self) -> Graph {
// sort links by cost
let links = {
let mut links = self.links.clone();
links.sort_unstable_by(|a, b| a.cost().cmp(&b.cost()));
links
};
Self::minimum_spanning_tree_impl(&links, self.node_count)
}
// Implementation of the Kruskal minimum spanning tree algorithm
fn minimum_spanning_tree_impl(links: &[Link], node_count: usize) -> Graph {
let mut roots = Vec::with_capacity(node_count);
let mut mst = Vec::new();
// initial root of every node is itself
for i in 0..node_count {
roots.push(i as ID);
}
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize;
while roots[i]!= i as ID {
// Path halving optimization
let tmp = roots[roots[i] as usize];
roots[i] = tmp;
i = tmp as usize;
}
i
}
for link in links {
let x = root(&mut roots, link.from);
let y = root(&mut roots, link.to);
if x!= y {
mst.push(link.clone());
roots[x] = roots[y];
}
}
// count roots of all minimum spanning trees
let roots_count = roots.iter().enumerate().fold(0,
|acc, (i, j)| acc + ((i as u32) == *j) as usize
);
Graph{ node_count: (mst.len() + roots_count), links: mst }
}
}
| {
return false;
} | conditional_block |
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Link {
pub fn new(from: ID, to: ID, quality: u16) -> Self {
Self {from, to, quality, cost: 1}
}
pub fn cost(&self) -> u16 {
self.cost
}
pub fn bandwidth(&self) -> u16 {
1
}
pub fn quality(&self) -> u16 {
self.quality
}
fn cmp(&self, from: ID, to: ID) -> Ordering {
let i = ((self.from as u64) << 32) + (self.to as u64);
let j = ((from as u64) << 32) + (to as u64);
i.cmp(&j)
}
}
impl fmt::Debug for Link {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{} => {}}}", self.from, self.to)
}
}
/*
* This graph is designed for fast iteration and access of neighbors.
*/
#[derive(Clone)]
pub struct Graph {
pub links: Vec<Link>, // sorted link list
pub node_count: usize,
}
impl Graph {
pub fn new() -> Self {
Self {
links: vec![],
node_count: 0,
}
}
pub fn clear(&mut self) {
self.links.clear();
self.node_count = 0;
}
pub fn connect(&mut self, a: ID, b: ID) {
self.add_link(a, b, std::u16::MAX);
self.add_link(b, a, std::u16::MAX);
}
pub fn add_nodes(&mut self, count: u32) {
self.node_count += count as usize;
}
pub fn add_graph(&mut self, graph: Graph) {
let nlen = self.node_count as ID;
let llen = self.links.len();
self.node_count += graph.node_count;
self.links.extend(graph.links);
for link in &mut self.links[llen..] {
link.from += nlen;
link.to += nlen;
}
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn disconnect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.del_link(*a, *b);
}
}
}
pub fn connect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.connect(*a, *b);
}
}
}
// Check if all nodes have the same degree
pub fn is_regular(&self) -> bool {
let mut from = 0;
let mut n = 0;
let mut prev_n = 0;
for (i, link) in self.links.iter().enumerate() {
if from!= link.from {
from = link.from;
if i > 0 && prev_n!= n {
return false;
}
prev_n = n;
}
n += 1;
}
true
}
/*
//https://www.youtube.com/watch?v=YbCn8d4Enos
//rename node => vertex and link to edge?
// maximum of the minimal distances from id to any other node
pub fn get_node_eccentricity(&self, id: ID) -> f32 {
}
// minimum eccentricity of all vertices
pub fn get_radius(&self) -> f32 {
}
// maximum eccentricity of all vertices
pub fn get_diameter(&self) -> f32 {
}
pub fn get_peripheral_nodes(&self) -> Vec<ID> {
}
pub fn get_central_nodes(&self) -> Vec<ID> {
}
fn pos_distance(a: &[f32; 3], b: &[f32; 3]) -> f32 {
((a[0] - b[0]).powi(2)
+ (a[1] - b[2]).powi(2)
+ (a[2] - b[2]).powi(2)).sqrt()
}
pub fn get_mean_link_distance(&self) -> (f32, f32) {
let mut d = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
d += Self::pos_distance(&p1, &p2);
}
let mean = d / self.links.len() as f32;
let mut v = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
v += (Self::pos_distance(&p1, &p2) - mean).powi(2);
}
let variance = ((v as f32) / (self.links.len() as f32)).sqrt();
(mean, variance)
}
*/
pub fn get_node_degree(&self, id: ID) -> u32 {
self.get_neighbors(id).len() as u32
}
pub fn get_avg_node_degree(&self) -> f32 {
let mut n = 0;
for id in 0..self.node_count {
n += self.get_node_degree(id as u32);
}
(n as f32) / (self.node_count as f32)
}
pub fn get_mean_clustering_coefficient(&self) -> f32 {
let mut cc = 0.0f32;
for id in 0..self.node_count {
cc += self.get_local_clustering_coefficient(id as u32);
}
cc / (self.node_count as f32)
}
// Get neighbor count mean and variance
pub fn get_mean_link_count(&self) -> (f32, f32) {
let mut degrees = Vec::new();
let mut v = 0.0;
let mut c = 0;
let len = self.node_count as u32;
// calculate mean
for id in 0..len {
let degree = self.get_node_degree(id);
c += degree;
degrees.push(degree);
}
// calculate variance
let mean = c as f32 / len as f32;
for degree in degrees {
v += (degree as f32 - mean).powi(2);
}
let variance = ((v as f32) / (len as f32)).sqrt();
(mean, variance)
}
/*
pub fn link_distances(&self) -> (f32, f32, f32) {
let mut d2_min = infinity;
let mut d2_max = -infinity;
let mut d2_sum = 0.0;
for link in &self.links {
let to = self.nodes[link.to].gpos;
let from = self.nodes[link.from].gpos;
let d2 = from * to;
if d2 < d2_min {
d2_min = d2;
}
if d2 > d2_max {
d2_max = d2;
}
d2_sum += d2;
}
(d2_min.sqrt(), d2_mean.sqrt(), d2_max.sqrt())
}
//linear mapping
pub fn adjust_link_quality(&mut self, min: f32, max: f32) {
for link in &mut self.links {
let from = self.nodes[link.from as usize].pos;
let to = self.nodes[link.to as usize].pos;
let distance = Self::pos_distance(&from, &to);
if distance <= min {
link.quality = u16::MIN;
} else if distance >= max {
link.quality = u16::MAX;
} else {
link.quality = (u16::MAX as f32 * (distance - min) / (max - min)) as u16;
}
}
}
*/
pub fn has_link(&self, from: ID, to: ID) -> bool {
if let Some(_) = self.link_idx(from, to) {
true
} else {
false
}
}
fn has_any_link(&self, from: ID, to: ID) -> bool {
self.has_link(from, to) || self.has_link(to, from)
}
/*
* Calcualte connections between neighbors of a given node
* divided by maximim possible connections between those neihgbors.
* Method by Watts and Strogatz.
*/
pub fn get_local_clustering_coefficient(&self, id: ID) -> f32 {
//TODO: also count the connections from neighbors to node?
let ns = self.get_neighbors(id);
if ns.len() <= 1 {
0.0
} else {
// count number of connections between neighbors
let mut k = 0;
for a in ns {
for b in ns {
if a.to!= b.to {
k += self.has_link(a.to, b.to) as u32;
}
}
}
(k as f32) / (ns.len() * (ns.len() - 1)) as f32
}
}
fn del_link(&mut self, a: ID, b: ID) {
self.del_links(&vec![a, b]);
}
pub fn del_links(&mut self, links: &Vec<ID>) {
if (links.len() % 2)!= 0 {
panic!("del_links: Uneven elements for link list");
}
fn any(link: &Link, a: ID, b: ID) -> bool {
(link.from == a && link.to == b) || (link.from == b || link.to == a)
}
self.links.retain(|link| {
for s in links.chunks(2) {
if any(&link, s[0], s[1]) {
return false;
}
}
true
});
}
pub fn is_bidirectional(&self) -> bool {
for link in &self.links {
if!self.has_link(link.to, link.from) {
return false;
}
}
true
}
pub fn is_valid(&self) -> bool {
let len = self.node_count as ID;
for (i, link) in self.links.iter().enumerate() {
if link.to >= len || link.from >= len {
return false;
}
if i > 0 {
let prev = &self.links[i-1];
// check for order and duplicate links
if!(link.from > prev.from || (link.from == prev.from && link.to > prev.to)) {
return false;
}
}
}
true
}
pub fn remove_node(&mut self, id: ID) {
if self.node_count == 0 {
return;
}
self.node_count -= 1;
// adjust index
for link in &mut self.links {
if link.to > id {
link.to -= 1;
}
if link.from > id {
link.from -= 1;
}
}
// remove links
vec_filter(&mut self.links, |ref link| link.from!= id && link.to!= id);
// sort
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn remove_nodes(&mut self, nodes: &Vec<ID>) {
for id in nodes {
self.remove_node(*id);
}
}
fn link_idx(&self, from: ID, to: ID) -> Option<usize> {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
Some(idx)
},
Err(_) => {
None
}
}
}
pub fn get_link(&self, from: ID, to: ID) -> Option<Link> {
if let Some(idx) = self.link_idx(from, to) {
Some(self.links[idx].clone())
} else {
None
}
}
pub fn add_link(&mut self, from: ID, to: ID, tq: u16) {
if from!= to {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
self.links[idx].quality = tq;
},
Err(idx) => {
self.links.insert(idx, Link::new(from, to, tq));
}
}
}
}
pub fn get_neighbors(&self, id: ID) -> &[Link] {
match self.links.binary_search_by(|link| link.from.cmp(&id)) {
Ok(idx) => {
let mut start = idx;
let mut end = idx;
for i in (0..idx).rev() {
if self.links[i].from == id {
start = i;
}
}
for i in idx..self.links.len() {
if self.links[i].from == id {
end = i;
}
}
&self.links[start..end+1]
},
Err(idx) => {
&self.links[0..0]
}
}
}
pub fn clear_links(&mut self) {
self.links.clear();
}
pub fn is_directed(&self) -> bool {
for link in &self.links {
if self.link_idx(link.to, link.from).is_none() {
return false;
}
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_count as ID {
if self.get_node_degree(id) == 0 {
remove.push(id);
}
}
self.remove_nodes(&remove);
}
pub fn node_count(&self) -> usize {
self.node_count
}
pub fn link_count(&self) -> usize {
self.links.len()
}
pub fn link_cost_sum(&self) -> f32 {
self.links.iter().fold(0.0, |acc, link| acc + link.cost() as f32)
}
pub fn spanning_tree(&self) -> Graph {
Self::minimum_spanning_tree_impl(&self.links, self.node_count)
}
pub fn minimum_spanning_tree(&self) -> Graph {
// sort links by cost
let links = {
let mut links = self.links.clone();
links.sort_unstable_by(|a, b| a.cost().cmp(&b.cost()));
links
};
Self::minimum_spanning_tree_impl(&links, self.node_count)
}
// Implementation of the Kruskal minimum spanning tree algorithm
fn | (links: &[Link], node_count: usize) -> Graph {
let mut roots = Vec::with_capacity(node_count);
let mut mst = Vec::new();
// initial root of every node is itself
for i in 0..node_count {
roots.push(i as ID);
}
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize;
while roots[i]!= i as ID {
// Path halving optimization
let tmp = roots[roots[i] as usize];
roots[i] = tmp;
i = tmp as usize;
}
i
}
for link in links {
let x = root(&mut roots, link.from);
let y = root(&mut roots, link.to);
if x!= y {
mst.push(link.clone());
roots[x] = roots[y];
}
}
// count roots of all minimum spanning trees
let roots_count = roots.iter().enumerate().fold(0,
|acc, (i, j)| acc + ((i as u32) == *j) as usize
);
Graph{ node_count: (mst.len() + roots_count), links: mst }
}
}
| minimum_spanning_tree_impl | identifier_name |
graph.rs | use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Link {
pub fn new(from: ID, to: ID, quality: u16) -> Self {
Self {from, to, quality, cost: 1}
}
pub fn cost(&self) -> u16 {
self.cost
}
pub fn bandwidth(&self) -> u16 {
1
}
pub fn quality(&self) -> u16 {
self.quality
}
fn cmp(&self, from: ID, to: ID) -> Ordering {
let i = ((self.from as u64) << 32) + (self.to as u64);
let j = ((from as u64) << 32) + (to as u64);
i.cmp(&j)
}
}
impl fmt::Debug for Link {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{} => {}}}", self.from, self.to)
}
}
/*
* This graph is designed for fast iteration and access of neighbors.
*/
#[derive(Clone)]
pub struct Graph {
pub links: Vec<Link>, // sorted link list
pub node_count: usize,
}
impl Graph {
pub fn new() -> Self {
Self {
links: vec![],
node_count: 0,
}
}
pub fn clear(&mut self) {
self.links.clear();
self.node_count = 0;
}
pub fn connect(&mut self, a: ID, b: ID) {
self.add_link(a, b, std::u16::MAX);
self.add_link(b, a, std::u16::MAX);
}
pub fn add_nodes(&mut self, count: u32) {
self.node_count += count as usize;
}
pub fn add_graph(&mut self, graph: Graph) {
let nlen = self.node_count as ID;
let llen = self.links.len();
self.node_count += graph.node_count;
self.links.extend(graph.links);
for link in &mut self.links[llen..] {
link.from += nlen;
link.to += nlen;
}
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn disconnect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.del_link(*a, *b);
}
}
}
pub fn connect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.connect(*a, *b);
}
}
}
// Check if all nodes have the same degree
pub fn is_regular(&self) -> bool {
let mut from = 0;
let mut n = 0;
let mut prev_n = 0;
for (i, link) in self.links.iter().enumerate() {
if from!= link.from {
from = link.from;
if i > 0 && prev_n!= n {
return false;
}
prev_n = n;
}
n += 1;
}
true
}
/*
//https://www.youtube.com/watch?v=YbCn8d4Enos
//rename node => vertex and link to edge?
// maximum of the minimal distances from id to any other node
pub fn get_node_eccentricity(&self, id: ID) -> f32 {
}
// minimum eccentricity of all vertices
pub fn get_radius(&self) -> f32 {
}
// maximum eccentricity of all vertices
pub fn get_diameter(&self) -> f32 {
}
pub fn get_peripheral_nodes(&self) -> Vec<ID> {
}
pub fn get_central_nodes(&self) -> Vec<ID> {
}
fn pos_distance(a: &[f32; 3], b: &[f32; 3]) -> f32 {
((a[0] - b[0]).powi(2)
+ (a[1] - b[2]).powi(2)
+ (a[2] - b[2]).powi(2)).sqrt()
}
pub fn get_mean_link_distance(&self) -> (f32, f32) {
let mut d = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
d += Self::pos_distance(&p1, &p2);
}
let mean = d / self.links.len() as f32;
let mut v = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
v += (Self::pos_distance(&p1, &p2) - mean).powi(2);
}
let variance = ((v as f32) / (self.links.len() as f32)).sqrt();
(mean, variance)
}
*/
pub fn get_node_degree(&self, id: ID) -> u32 {
self.get_neighbors(id).len() as u32
}
pub fn get_avg_node_degree(&self) -> f32 {
let mut n = 0;
for id in 0..self.node_count {
n += self.get_node_degree(id as u32);
}
(n as f32) / (self.node_count as f32)
}
pub fn get_mean_clustering_coefficient(&self) -> f32 {
let mut cc = 0.0f32;
for id in 0..self.node_count {
cc += self.get_local_clustering_coefficient(id as u32);
}
cc / (self.node_count as f32)
}
// Get neighbor count mean and variance
pub fn get_mean_link_count(&self) -> (f32, f32) {
let mut degrees = Vec::new();
let mut v = 0.0;
let mut c = 0;
let len = self.node_count as u32;
// calculate mean
for id in 0..len {
let degree = self.get_node_degree(id);
c += degree;
degrees.push(degree);
}
// calculate variance
let mean = c as f32 / len as f32;
for degree in degrees {
v += (degree as f32 - mean).powi(2);
}
let variance = ((v as f32) / (len as f32)).sqrt();
(mean, variance)
}
/*
pub fn link_distances(&self) -> (f32, f32, f32) {
let mut d2_min = infinity;
let mut d2_max = -infinity;
let mut d2_sum = 0.0;
for link in &self.links {
let to = self.nodes[link.to].gpos;
let from = self.nodes[link.from].gpos;
let d2 = from * to;
if d2 < d2_min {
d2_min = d2;
}
if d2 > d2_max {
d2_max = d2;
}
d2_sum += d2;
}
(d2_min.sqrt(), d2_mean.sqrt(), d2_max.sqrt())
}
//linear mapping
pub fn adjust_link_quality(&mut self, min: f32, max: f32) {
for link in &mut self.links {
let from = self.nodes[link.from as usize].pos;
let to = self.nodes[link.to as usize].pos;
let distance = Self::pos_distance(&from, &to);
if distance <= min {
link.quality = u16::MIN;
} else if distance >= max {
link.quality = u16::MAX;
} else {
link.quality = (u16::MAX as f32 * (distance - min) / (max - min)) as u16;
}
}
}
*/
pub fn has_link(&self, from: ID, to: ID) -> bool {
if let Some(_) = self.link_idx(from, to) {
true
} else {
false
}
}
fn has_any_link(&self, from: ID, to: ID) -> bool {
self.has_link(from, to) || self.has_link(to, from)
}
/*
* Calcualte connections between neighbors of a given node
* divided by maximim possible connections between those neihgbors.
* Method by Watts and Strogatz.
*/
pub fn get_local_clustering_coefficient(&self, id: ID) -> f32 {
//TODO: also count the connections from neighbors to node?
let ns = self.get_neighbors(id);
if ns.len() <= 1 {
0.0
} else {
// count number of connections between neighbors
let mut k = 0;
for a in ns {
for b in ns {
if a.to!= b.to {
k += self.has_link(a.to, b.to) as u32;
}
}
}
(k as f32) / (ns.len() * (ns.len() - 1)) as f32
}
}
fn del_link(&mut self, a: ID, b: ID) {
self.del_links(&vec![a, b]);
}
pub fn del_links(&mut self, links: &Vec<ID>) {
if (links.len() % 2)!= 0 {
panic!("del_links: Uneven elements for link list");
}
fn any(link: &Link, a: ID, b: ID) -> bool {
(link.from == a && link.to == b) || (link.from == b || link.to == a)
}
self.links.retain(|link| {
for s in links.chunks(2) {
if any(&link, s[0], s[1]) {
return false;
}
}
true
});
}
pub fn is_bidirectional(&self) -> bool {
for link in &self.links {
if!self.has_link(link.to, link.from) {
return false;
}
}
true
}
pub fn is_valid(&self) -> bool {
let len = self.node_count as ID;
for (i, link) in self.links.iter().enumerate() {
if link.to >= len || link.from >= len {
return false;
}
if i > 0 {
let prev = &self.links[i-1];
// check for order and duplicate links
if!(link.from > prev.from || (link.from == prev.from && link.to > prev.to)) {
return false;
}
}
}
true
}
pub fn remove_node(&mut self, id: ID) {
if self.node_count == 0 {
return;
}
self.node_count -= 1;
// adjust index
for link in &mut self.links {
if link.to > id {
link.to -= 1;
}
if link.from > id {
link.from -= 1;
}
}
// remove links
vec_filter(&mut self.links, |ref link| link.from!= id && link.to!= id);
// sort
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn remove_nodes(&mut self, nodes: &Vec<ID>) {
for id in nodes {
self.remove_node(*id);
}
}
fn link_idx(&self, from: ID, to: ID) -> Option<usize> {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
Some(idx)
},
Err(_) => {
None
}
}
}
pub fn get_link(&self, from: ID, to: ID) -> Option<Link> {
if let Some(idx) = self.link_idx(from, to) {
Some(self.links[idx].clone())
} else {
None
}
}
pub fn add_link(&mut self, from: ID, to: ID, tq: u16) {
if from!= to {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
self.links[idx].quality = tq;
},
Err(idx) => {
self.links.insert(idx, Link::new(from, to, tq));
}
}
}
}
pub fn get_neighbors(&self, id: ID) -> &[Link] {
match self.links.binary_search_by(|link| link.from.cmp(&id)) {
Ok(idx) => {
let mut start = idx;
let mut end = idx;
for i in (0..idx).rev() {
if self.links[i].from == id {
start = i;
}
}
for i in idx..self.links.len() {
if self.links[i].from == id {
end = i;
}
}
&self.links[start..end+1]
},
Err(idx) => {
&self.links[0..0]
}
}
}
pub fn clear_links(&mut self) {
self.links.clear();
}
pub fn is_directed(&self) -> bool {
for link in &self.links {
if self.link_idx(link.to, link.from).is_none() {
return false;
}
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_count as ID {
if self.get_node_degree(id) == 0 {
remove.push(id);
}
}
self.remove_nodes(&remove);
}
pub fn node_count(&self) -> usize {
self.node_count
}
pub fn link_count(&self) -> usize {
self.links.len()
}
pub fn link_cost_sum(&self) -> f32 {
self.links.iter().fold(0.0, |acc, link| acc + link.cost() as f32)
}
pub fn spanning_tree(&self) -> Graph {
Self::minimum_spanning_tree_impl(&self.links, self.node_count)
}
pub fn minimum_spanning_tree(&self) -> Graph {
// sort links by cost
let links = {
let mut links = self.links.clone();
links.sort_unstable_by(|a, b| a.cost().cmp(&b.cost()));
links
};
Self::minimum_spanning_tree_impl(&links, self.node_count)
}
// Implementation of the Kruskal minimum spanning tree algorithm
fn minimum_spanning_tree_impl(links: &[Link], node_count: usize) -> Graph {
let mut roots = Vec::with_capacity(node_count);
let mut mst = Vec::new();
// initial root of every node is itself
for i in 0..node_count {
roots.push(i as ID);
} | while roots[i]!= i as ID {
// Path halving optimization
let tmp = roots[roots[i] as usize];
roots[i] = tmp;
i = tmp as usize;
}
i
}
for link in links {
let x = root(&mut roots, link.from);
let y = root(&mut roots, link.to);
if x!= y {
mst.push(link.clone());
roots[x] = roots[y];
}
}
// count roots of all minimum spanning trees
let roots_count = roots.iter().enumerate().fold(0,
|acc, (i, j)| acc + ((i as u32) == *j) as usize
);
Graph{ node_count: (mst.len() + roots_count), links: mst }
}
} |
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize; | random_line_split |
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Link {
pub fn new(from: ID, to: ID, quality: u16) -> Self {
Self {from, to, quality, cost: 1}
}
pub fn cost(&self) -> u16 {
self.cost
}
pub fn bandwidth(&self) -> u16 {
1
}
pub fn quality(&self) -> u16 {
self.quality
}
fn cmp(&self, from: ID, to: ID) -> Ordering {
let i = ((self.from as u64) << 32) + (self.to as u64);
let j = ((from as u64) << 32) + (to as u64);
i.cmp(&j)
}
}
impl fmt::Debug for Link {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{} => {}}}", self.from, self.to)
}
}
/*
* This graph is designed for fast iteration and access of neighbors.
*/
#[derive(Clone)]
pub struct Graph {
pub links: Vec<Link>, // sorted link list
pub node_count: usize,
}
impl Graph {
pub fn new() -> Self {
Self {
links: vec![],
node_count: 0,
}
}
pub fn clear(&mut self) {
self.links.clear();
self.node_count = 0;
}
pub fn connect(&mut self, a: ID, b: ID) {
self.add_link(a, b, std::u16::MAX);
self.add_link(b, a, std::u16::MAX);
}
pub fn add_nodes(&mut self, count: u32) {
self.node_count += count as usize;
}
pub fn add_graph(&mut self, graph: Graph) {
let nlen = self.node_count as ID;
let llen = self.links.len();
self.node_count += graph.node_count;
self.links.extend(graph.links);
for link in &mut self.links[llen..] {
link.from += nlen;
link.to += nlen;
}
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn disconnect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.del_link(*a, *b);
}
}
}
pub fn connect_nodes(&mut self, ids: &Vec<ID>) {
for a in ids {
for b in ids {
self.connect(*a, *b);
}
}
}
// Check if all nodes have the same degree
pub fn is_regular(&self) -> bool {
let mut from = 0;
let mut n = 0;
let mut prev_n = 0;
for (i, link) in self.links.iter().enumerate() {
if from!= link.from {
from = link.from;
if i > 0 && prev_n!= n {
return false;
}
prev_n = n;
}
n += 1;
}
true
}
/*
//https://www.youtube.com/watch?v=YbCn8d4Enos
//rename node => vertex and link to edge?
// maximum of the minimal distances from id to any other node
pub fn get_node_eccentricity(&self, id: ID) -> f32 {
}
// minimum eccentricity of all vertices
pub fn get_radius(&self) -> f32 {
}
// maximum eccentricity of all vertices
pub fn get_diameter(&self) -> f32 {
}
pub fn get_peripheral_nodes(&self) -> Vec<ID> {
}
pub fn get_central_nodes(&self) -> Vec<ID> {
}
fn pos_distance(a: &[f32; 3], b: &[f32; 3]) -> f32 {
((a[0] - b[0]).powi(2)
+ (a[1] - b[2]).powi(2)
+ (a[2] - b[2]).powi(2)).sqrt()
}
pub fn get_mean_link_distance(&self) -> (f32, f32) {
let mut d = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
d += Self::pos_distance(&p1, &p2);
}
let mean = d / self.links.len() as f32;
let mut v = 0.0;
for link in &self.links {
let p1 = self.nodes[link.from as usize].pos;
let p2 = self.nodes[link.to as usize].pos;
v += (Self::pos_distance(&p1, &p2) - mean).powi(2);
}
let variance = ((v as f32) / (self.links.len() as f32)).sqrt();
(mean, variance)
}
*/
pub fn get_node_degree(&self, id: ID) -> u32 {
self.get_neighbors(id).len() as u32
}
pub fn get_avg_node_degree(&self) -> f32 {
let mut n = 0;
for id in 0..self.node_count {
n += self.get_node_degree(id as u32);
}
(n as f32) / (self.node_count as f32)
}
pub fn get_mean_clustering_coefficient(&self) -> f32 {
let mut cc = 0.0f32;
for id in 0..self.node_count {
cc += self.get_local_clustering_coefficient(id as u32);
}
cc / (self.node_count as f32)
}
// Get neighbor count mean and variance
pub fn get_mean_link_count(&self) -> (f32, f32) {
let mut degrees = Vec::new();
let mut v = 0.0;
let mut c = 0;
let len = self.node_count as u32;
// calculate mean
for id in 0..len {
let degree = self.get_node_degree(id);
c += degree;
degrees.push(degree);
}
// calculate variance
let mean = c as f32 / len as f32;
for degree in degrees {
v += (degree as f32 - mean).powi(2);
}
let variance = ((v as f32) / (len as f32)).sqrt();
(mean, variance)
}
/*
pub fn link_distances(&self) -> (f32, f32, f32) {
let mut d2_min = infinity;
let mut d2_max = -infinity;
let mut d2_sum = 0.0;
for link in &self.links {
let to = self.nodes[link.to].gpos;
let from = self.nodes[link.from].gpos;
let d2 = from * to;
if d2 < d2_min {
d2_min = d2;
}
if d2 > d2_max {
d2_max = d2;
}
d2_sum += d2;
}
(d2_min.sqrt(), d2_mean.sqrt(), d2_max.sqrt())
}
//linear mapping
pub fn adjust_link_quality(&mut self, min: f32, max: f32) {
for link in &mut self.links {
let from = self.nodes[link.from as usize].pos;
let to = self.nodes[link.to as usize].pos;
let distance = Self::pos_distance(&from, &to);
if distance <= min {
link.quality = u16::MIN;
} else if distance >= max {
link.quality = u16::MAX;
} else {
link.quality = (u16::MAX as f32 * (distance - min) / (max - min)) as u16;
}
}
}
*/
pub fn has_link(&self, from: ID, to: ID) -> bool {
if let Some(_) = self.link_idx(from, to) {
true
} else {
false
}
}
fn has_any_link(&self, from: ID, to: ID) -> bool {
self.has_link(from, to) || self.has_link(to, from)
}
/*
* Calcualte connections between neighbors of a given node
* divided by maximim possible connections between those neihgbors.
* Method by Watts and Strogatz.
*/
pub fn get_local_clustering_coefficient(&self, id: ID) -> f32 {
//TODO: also count the connections from neighbors to node?
let ns = self.get_neighbors(id);
if ns.len() <= 1 {
0.0
} else {
// count number of connections between neighbors
let mut k = 0;
for a in ns {
for b in ns {
if a.to!= b.to {
k += self.has_link(a.to, b.to) as u32;
}
}
}
(k as f32) / (ns.len() * (ns.len() - 1)) as f32
}
}
fn del_link(&mut self, a: ID, b: ID) {
self.del_links(&vec![a, b]);
}
pub fn del_links(&mut self, links: &Vec<ID>) {
if (links.len() % 2)!= 0 {
panic!("del_links: Uneven elements for link list");
}
fn any(link: &Link, a: ID, b: ID) -> bool {
(link.from == a && link.to == b) || (link.from == b || link.to == a)
}
self.links.retain(|link| {
for s in links.chunks(2) {
if any(&link, s[0], s[1]) {
return false;
}
}
true
});
}
pub fn is_bidirectional(&self) -> bool {
for link in &self.links {
if!self.has_link(link.to, link.from) {
return false;
}
}
true
}
pub fn is_valid(&self) -> bool {
let len = self.node_count as ID;
for (i, link) in self.links.iter().enumerate() {
if link.to >= len || link.from >= len {
return false;
}
if i > 0 {
let prev = &self.links[i-1];
// check for order and duplicate links
if!(link.from > prev.from || (link.from == prev.from && link.to > prev.to)) {
return false;
}
}
}
true
}
pub fn remove_node(&mut self, id: ID) {
if self.node_count == 0 {
return;
}
self.node_count -= 1;
// adjust index
for link in &mut self.links {
if link.to > id {
link.to -= 1;
}
if link.from > id {
link.from -= 1;
}
}
// remove links
vec_filter(&mut self.links, |ref link| link.from!= id && link.to!= id);
// sort
self.links.sort_unstable_by(|a, b| a.cmp(b.from, b.to));
}
pub fn remove_nodes(&mut self, nodes: &Vec<ID>) {
for id in nodes {
self.remove_node(*id);
}
}
fn link_idx(&self, from: ID, to: ID) -> Option<usize> {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
Some(idx)
},
Err(_) => {
None
}
}
}
pub fn get_link(&self, from: ID, to: ID) -> Option<Link> {
if let Some(idx) = self.link_idx(from, to) {
Some(self.links[idx].clone())
} else {
None
}
}
pub fn add_link(&mut self, from: ID, to: ID, tq: u16) {
if from!= to {
match self.links.binary_search_by(|link| link.cmp(from, to)) {
Ok(idx) => {
self.links[idx].quality = tq;
},
Err(idx) => {
self.links.insert(idx, Link::new(from, to, tq));
}
}
}
}
pub fn get_neighbors(&self, id: ID) -> &[Link] | }
}
pub fn clear_links(&mut self) {
self.links.clear();
}
pub fn is_directed(&self) -> bool {
for link in &self.links {
if self.link_idx(link.to, link.from).is_none() {
return false;
}
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_count as ID {
if self.get_node_degree(id) == 0 {
remove.push(id);
}
}
self.remove_nodes(&remove);
}
pub fn node_count(&self) -> usize {
self.node_count
}
pub fn link_count(&self) -> usize {
self.links.len()
}
pub fn link_cost_sum(&self) -> f32 {
self.links.iter().fold(0.0, |acc, link| acc + link.cost() as f32)
}
pub fn spanning_tree(&self) -> Graph {
Self::minimum_spanning_tree_impl(&self.links, self.node_count)
}
pub fn minimum_spanning_tree(&self) -> Graph {
// sort links by cost
let links = {
let mut links = self.links.clone();
links.sort_unstable_by(|a, b| a.cost().cmp(&b.cost()));
links
};
Self::minimum_spanning_tree_impl(&links, self.node_count)
}
// Implementation of the Kruskal minimum spanning tree algorithm
fn minimum_spanning_tree_impl(links: &[Link], node_count: usize) -> Graph {
let mut roots = Vec::with_capacity(node_count);
let mut mst = Vec::new();
// initial root of every node is itself
for i in 0..node_count {
roots.push(i as ID);
}
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize;
while roots[i]!= i as ID {
// Path halving optimization
let tmp = roots[roots[i] as usize];
roots[i] = tmp;
i = tmp as usize;
}
i
}
for link in links {
let x = root(&mut roots, link.from);
let y = root(&mut roots, link.to);
if x!= y {
mst.push(link.clone());
roots[x] = roots[y];
}
}
// count roots of all minimum spanning trees
let roots_count = roots.iter().enumerate().fold(0,
|acc, (i, j)| acc + ((i as u32) == *j) as usize
);
Graph{ node_count: (mst.len() + roots_count), links: mst }
}
}
| {
match self.links.binary_search_by(|link| link.from.cmp(&id)) {
Ok(idx) => {
let mut start = idx;
let mut end = idx;
for i in (0..idx).rev() {
if self.links[i].from == id {
start = i;
}
}
for i in idx..self.links.len() {
if self.links[i].from == id {
end = i;
}
}
&self.links[start..end+1]
},
Err(idx) => {
&self.links[0..0]
} | identifier_body |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
extern crate extra;
extern crate png;
extern crate std;
extern crate test;
use std::io;
use std::io::{File, Reader, Process};
use std::io::process::ExitStatus;
use std::os;
use std::str;
use test::{DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn};
use test::run_tests_console;
fn main() {
let args = os::args();
let mut parts = args.tail().split(|e| "--" == e.as_slice());
let files = parts.next().unwrap(); //.split() is never empty
let servo_args = parts.next().unwrap_or(&[]);
if files.len() == 0 {
fail!("error: at least one reftest list must be given");
}
let tests = parse_lists(files, servo_args);
let test_opts = TestOpts {
filter: None,
run_ignored: false,
logfile: None,
run_tests: true,
run_benchmarks: false,
ratchet_noise_percent: None,
ratchet_metrics: None,
save_metrics: None,
test_shard: None,
};
match run_tests_console(&test_opts, tests) {
Ok(false) => os::set_exit_status(1), // tests failed
Err(_) => os::set_exit_status(2), // I/O-related failure
_ => (),
}
}
#[deriving(Eq)]
enum ReftestKind {
Same,
Different,
}
struct Reftest {
name: ~str,
kind: ReftestKind,
files: [~str,..2],
id: uint,
servo_args: ~[~str],
}
fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> ~[TestDescAndFn] {
let mut tests: ~[TestDescAndFn] = ~[];
let mut next_id = 0;
for file in filenames.iter() {
let file_path = Path::new(file.clone());
let contents = match File::open_mode(&file_path, io::Open, io::Read)
.and_then(|mut f| {
f.read_to_end()
}) {
Ok(s) => str::from_utf8_owned(s),
_ => fail!("Could not read file"),
};
for line in contents.unwrap().lines() {
// ignore comments |
let parts: ~[&str] = line.split(' ').filter(|p|!p.is_empty()).collect();
if parts.len()!= 3 {
fail!("reftest line: '{:s}' doesn't match 'KIND LEFT RIGHT'", line);
}
let kind = match parts[0] {
"==" => Same,
"!=" => Different,
_ => fail!("reftest line: '{:s}' has invalid kind '{:s}'",
line, parts[0])
};
let src_path = file_path.dir_path();
let src_dir = src_path.display().to_str();
let file_left = src_dir + "/" + parts[1];
let file_right = src_dir + "/" + parts[2];
let reftest = Reftest {
name: parts[1] + " / " + parts[2],
kind: kind,
files: [file_left, file_right],
id: next_id,
servo_args: servo_args.to_owned(),
};
next_id += 1;
tests.push(make_test(reftest));
}
}
tests
}
fn make_test(reftest: Reftest) -> TestDescAndFn {
let name = reftest.name.clone();
TestDescAndFn {
desc: TestDesc {
name: DynTestName(name),
ignore: false,
should_fail: false,
},
testfn: DynTestFn(proc() {
check_reftest(reftest);
}),
}
}
fn capture(reftest: &Reftest, side: uint) -> png::Image {
let filename = format!("/tmp/servo-reftest-{:06u}-{:u}.png", reftest.id, side);
let mut args = reftest.servo_args.clone();
args.push_all_move(~[~"-f", ~"-o", filename.clone(), reftest.files[side].clone()]);
let retval = match Process::status("./servo", args) {
Ok(status) => status,
Err(e) => fail!("failed to execute process: {}", e),
};
assert!(retval == ExitStatus(0));
png::load_png(&from_str::<Path>(filename).unwrap()).unwrap()
}
fn check_reftest(reftest: Reftest) {
let left = capture(&reftest, 0);
let right = capture(&reftest, 1);
let pixels: ~[u8] = left.pixels.iter().zip(right.pixels.iter()).map(|(&a, &b)| {
if a as i8 - b as i8 == 0 {
// White for correct
0xFF
} else {
// "1100" in the RGBA channel with an error for an incorrect value
// This results in some number of C0 and FFs, which is much more
// readable (and distinguishable) than the previous difference-wise
// scaling but does not require reconstructing the actual RGBA pixel.
0xC0
}
}).collect();
if pixels.iter().any(|&a| a < 255) {
let output = from_str::<Path>(format!("/tmp/servo-reftest-{:06u}-diff.png", reftest.id)).unwrap();
let img = png::Image {
width: left.width,
height: left.height,
color_type: png::RGBA8,
pixels: pixels,
};
let res = png::store_png(&img, &output);
assert!(res.is_ok());
assert!(reftest.kind == Different);
} else {
assert!(reftest.kind == Same);
}
} | if line.starts_with("#") {
continue;
} | random_line_split |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
extern crate extra;
extern crate png;
extern crate std;
extern crate test;
use std::io;
use std::io::{File, Reader, Process};
use std::io::process::ExitStatus;
use std::os;
use std::str;
use test::{DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn};
use test::run_tests_console;
fn main() {
let args = os::args();
let mut parts = args.tail().split(|e| "--" == e.as_slice());
let files = parts.next().unwrap(); //.split() is never empty
let servo_args = parts.next().unwrap_or(&[]);
if files.len() == 0 {
fail!("error: at least one reftest list must be given");
}
let tests = parse_lists(files, servo_args);
let test_opts = TestOpts {
filter: None,
run_ignored: false,
logfile: None,
run_tests: true,
run_benchmarks: false,
ratchet_noise_percent: None,
ratchet_metrics: None,
save_metrics: None,
test_shard: None,
};
match run_tests_console(&test_opts, tests) {
Ok(false) => os::set_exit_status(1), // tests failed
Err(_) => os::set_exit_status(2), // I/O-related failure
_ => (),
}
}
#[deriving(Eq)]
enum ReftestKind {
Same,
Different,
}
struct Reftest {
name: ~str,
kind: ReftestKind,
files: [~str,..2],
id: uint,
servo_args: ~[~str],
}
fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> ~[TestDescAndFn] {
let mut tests: ~[TestDescAndFn] = ~[];
let mut next_id = 0;
for file in filenames.iter() {
let file_path = Path::new(file.clone());
let contents = match File::open_mode(&file_path, io::Open, io::Read)
.and_then(|mut f| {
f.read_to_end()
}) {
Ok(s) => str::from_utf8_owned(s),
_ => fail!("Could not read file"),
};
for line in contents.unwrap().lines() {
// ignore comments
if line.starts_with("#") {
continue;
}
let parts: ~[&str] = line.split(' ').filter(|p|!p.is_empty()).collect();
if parts.len()!= 3 {
fail!("reftest line: '{:s}' doesn't match 'KIND LEFT RIGHT'", line);
}
let kind = match parts[0] {
"==" => Same,
"!=" => Different,
_ => fail!("reftest line: '{:s}' has invalid kind '{:s}'",
line, parts[0])
};
let src_path = file_path.dir_path();
let src_dir = src_path.display().to_str();
let file_left = src_dir + "/" + parts[1];
let file_right = src_dir + "/" + parts[2];
let reftest = Reftest {
name: parts[1] + " / " + parts[2],
kind: kind,
files: [file_left, file_right],
id: next_id,
servo_args: servo_args.to_owned(),
};
next_id += 1;
tests.push(make_test(reftest));
}
}
tests
}
fn make_test(reftest: Reftest) -> TestDescAndFn |
fn capture(reftest: &Reftest, side: uint) -> png::Image {
let filename = format!("/tmp/servo-reftest-{:06u}-{:u}.png", reftest.id, side);
let mut args = reftest.servo_args.clone();
args.push_all_move(~[~"-f", ~"-o", filename.clone(), reftest.files[side].clone()]);
let retval = match Process::status("./servo", args) {
Ok(status) => status,
Err(e) => fail!("failed to execute process: {}", e),
};
assert!(retval == ExitStatus(0));
png::load_png(&from_str::<Path>(filename).unwrap()).unwrap()
}
fn check_reftest(reftest: Reftest) {
let left = capture(&reftest, 0);
let right = capture(&reftest, 1);
let pixels: ~[u8] = left.pixels.iter().zip(right.pixels.iter()).map(|(&a, &b)| {
if a as i8 - b as i8 == 0 {
// White for correct
0xFF
} else {
// "1100" in the RGBA channel with an error for an incorrect value
// This results in some number of C0 and FFs, which is much more
// readable (and distinguishable) than the previous difference-wise
// scaling but does not require reconstructing the actual RGBA pixel.
0xC0
}
}).collect();
if pixels.iter().any(|&a| a < 255) {
let output = from_str::<Path>(format!("/tmp/servo-reftest-{:06u}-diff.png", reftest.id)).unwrap();
let img = png::Image {
width: left.width,
height: left.height,
color_type: png::RGBA8,
pixels: pixels,
};
let res = png::store_png(&img, &output);
assert!(res.is_ok());
assert!(reftest.kind == Different);
} else {
assert!(reftest.kind == Same);
}
}
| {
let name = reftest.name.clone();
TestDescAndFn {
desc: TestDesc {
name: DynTestName(name),
ignore: false,
should_fail: false,
},
testfn: DynTestFn(proc() {
check_reftest(reftest);
}),
}
} | identifier_body |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
extern crate extra;
extern crate png;
extern crate std;
extern crate test;
use std::io;
use std::io::{File, Reader, Process};
use std::io::process::ExitStatus;
use std::os;
use std::str;
use test::{DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn};
use test::run_tests_console;
fn main() {
let args = os::args();
let mut parts = args.tail().split(|e| "--" == e.as_slice());
let files = parts.next().unwrap(); //.split() is never empty
let servo_args = parts.next().unwrap_or(&[]);
if files.len() == 0 {
fail!("error: at least one reftest list must be given");
}
let tests = parse_lists(files, servo_args);
let test_opts = TestOpts {
filter: None,
run_ignored: false,
logfile: None,
run_tests: true,
run_benchmarks: false,
ratchet_noise_percent: None,
ratchet_metrics: None,
save_metrics: None,
test_shard: None,
};
match run_tests_console(&test_opts, tests) {
Ok(false) => os::set_exit_status(1), // tests failed
Err(_) => os::set_exit_status(2), // I/O-related failure
_ => (),
}
}
#[deriving(Eq)]
enum ReftestKind {
Same,
Different,
}
struct Reftest {
name: ~str,
kind: ReftestKind,
files: [~str,..2],
id: uint,
servo_args: ~[~str],
}
fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> ~[TestDescAndFn] {
let mut tests: ~[TestDescAndFn] = ~[];
let mut next_id = 0;
for file in filenames.iter() {
let file_path = Path::new(file.clone());
let contents = match File::open_mode(&file_path, io::Open, io::Read)
.and_then(|mut f| {
f.read_to_end()
}) {
Ok(s) => str::from_utf8_owned(s),
_ => fail!("Could not read file"),
};
for line in contents.unwrap().lines() {
// ignore comments
if line.starts_with("#") {
continue;
}
let parts: ~[&str] = line.split(' ').filter(|p|!p.is_empty()).collect();
if parts.len()!= 3 {
fail!("reftest line: '{:s}' doesn't match 'KIND LEFT RIGHT'", line);
}
let kind = match parts[0] {
"==" => Same,
"!=" => Different,
_ => fail!("reftest line: '{:s}' has invalid kind '{:s}'",
line, parts[0])
};
let src_path = file_path.dir_path();
let src_dir = src_path.display().to_str();
let file_left = src_dir + "/" + parts[1];
let file_right = src_dir + "/" + parts[2];
let reftest = Reftest {
name: parts[1] + " / " + parts[2],
kind: kind,
files: [file_left, file_right],
id: next_id,
servo_args: servo_args.to_owned(),
};
next_id += 1;
tests.push(make_test(reftest));
}
}
tests
}
fn make_test(reftest: Reftest) -> TestDescAndFn {
let name = reftest.name.clone();
TestDescAndFn {
desc: TestDesc {
name: DynTestName(name),
ignore: false,
should_fail: false,
},
testfn: DynTestFn(proc() {
check_reftest(reftest);
}),
}
}
fn | (reftest: &Reftest, side: uint) -> png::Image {
let filename = format!("/tmp/servo-reftest-{:06u}-{:u}.png", reftest.id, side);
let mut args = reftest.servo_args.clone();
args.push_all_move(~[~"-f", ~"-o", filename.clone(), reftest.files[side].clone()]);
let retval = match Process::status("./servo", args) {
Ok(status) => status,
Err(e) => fail!("failed to execute process: {}", e),
};
assert!(retval == ExitStatus(0));
png::load_png(&from_str::<Path>(filename).unwrap()).unwrap()
}
fn check_reftest(reftest: Reftest) {
let left = capture(&reftest, 0);
let right = capture(&reftest, 1);
let pixels: ~[u8] = left.pixels.iter().zip(right.pixels.iter()).map(|(&a, &b)| {
if a as i8 - b as i8 == 0 {
// White for correct
0xFF
} else {
// "1100" in the RGBA channel with an error for an incorrect value
// This results in some number of C0 and FFs, which is much more
// readable (and distinguishable) than the previous difference-wise
// scaling but does not require reconstructing the actual RGBA pixel.
0xC0
}
}).collect();
if pixels.iter().any(|&a| a < 255) {
let output = from_str::<Path>(format!("/tmp/servo-reftest-{:06u}-diff.png", reftest.id)).unwrap();
let img = png::Image {
width: left.width,
height: left.height,
color_type: png::RGBA8,
pixels: pixels,
};
let res = png::store_png(&img, &output);
assert!(res.is_ok());
assert!(reftest.kind == Different);
} else {
assert!(reftest.kind == Same);
}
}
| capture | identifier_name |
unsized3.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.
// Test structs with always-unsized fields.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::mem;
use std::raw;
use std::slice;
struct | <T> {
f: [T],
}
struct Bar {
f1: usize,
f2: [usize],
}
struct Baz {
f1: usize,
f2: str,
}
trait Tr {
fn foo(&self) -> usize;
}
struct St {
f: usize
}
impl Tr for St {
fn foo(&self) -> usize {
self.f
}
}
struct Qux<'a> {
f: Tr+'a
}
pub fn main() {
let _: &Foo<f64>;
let _: &Bar;
let _: &Baz;
let _: Box<Foo<i32>>;
let _: Box<Bar>;
let _: Box<Baz>;
let _ = mem::size_of::<Box<Foo<u8>>>();
let _ = mem::size_of::<Box<Bar>>();
let _ = mem::size_of::<Box<Baz>>();
unsafe {
struct Foo_<T> {
f: [T; 3]
}
let data: Box<Foo_<i32>> = box Foo_{f: [1, 2, 3] };
let x: &Foo<i32> = mem::transmute(slice::from_raw_parts(&*data, 3));
assert!(x.f.len() == 3);
assert!(x.f[0] == 1);
struct Baz_ {
f1: usize,
f2: [u8; 5],
}
let data: Box<_> = box Baz_ {
f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] };
let x: &Baz = mem::transmute(slice::from_raw_parts(&*data, 5));
assert!(x.f1 == 42);
let chs: Vec<char> = x.f2.chars().collect();
assert!(chs.len() == 5);
assert!(chs[0] == 'a');
assert!(chs[1] == 'b');
assert!(chs[2] == 'c');
assert!(chs[3] == 'd');
assert!(chs[4] == 'e');
struct Qux_ {
f: St
}
let obj: Box<St> = box St { f: 42 };
let obj: &Tr = &*obj;
let obj: raw::TraitObject = mem::transmute(&*obj);
let data: Box<_> = box Qux_{ f: St { f: 234 } };
let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
data: mem::transmute(&*data) });
assert!(x.f.foo() == 234);
}
}
| Foo | identifier_name |
unsized3.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.
// Test structs with always-unsized fields.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::mem;
use std::raw;
use std::slice;
struct Foo<T> {
f: [T],
}
struct Bar {
f1: usize,
f2: [usize],
}
struct Baz {
f1: usize,
f2: str,
}
trait Tr {
fn foo(&self) -> usize;
}
struct St {
f: usize
}
impl Tr for St {
fn foo(&self) -> usize {
self.f
}
}
struct Qux<'a> {
f: Tr+'a
}
pub fn main() {
let _: &Foo<f64>;
let _: &Bar;
let _: &Baz;
let _: Box<Foo<i32>>;
let _: Box<Bar>;
let _: Box<Baz>;
let _ = mem::size_of::<Box<Foo<u8>>>();
let _ = mem::size_of::<Box<Bar>>();
let _ = mem::size_of::<Box<Baz>>();
unsafe {
struct Foo_<T> {
f: [T; 3]
}
let data: Box<Foo_<i32>> = box Foo_{f: [1, 2, 3] };
let x: &Foo<i32> = mem::transmute(slice::from_raw_parts(&*data, 3));
assert!(x.f.len() == 3);
assert!(x.f[0] == 1);
struct Baz_ {
f1: usize,
f2: [u8; 5],
}
| let x: &Baz = mem::transmute(slice::from_raw_parts(&*data, 5));
assert!(x.f1 == 42);
let chs: Vec<char> = x.f2.chars().collect();
assert!(chs.len() == 5);
assert!(chs[0] == 'a');
assert!(chs[1] == 'b');
assert!(chs[2] == 'c');
assert!(chs[3] == 'd');
assert!(chs[4] == 'e');
struct Qux_ {
f: St
}
let obj: Box<St> = box St { f: 42 };
let obj: &Tr = &*obj;
let obj: raw::TraitObject = mem::transmute(&*obj);
let data: Box<_> = box Qux_{ f: St { f: 234 } };
let x: &Qux = mem::transmute(raw::TraitObject { vtable: obj.vtable,
data: mem::transmute(&*data) });
assert!(x.f.foo() == 234);
}
} | let data: Box<_> = box Baz_ {
f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] }; | random_line_split |
rpc.rs | extern crate crypto;
use bytes::BytesMut;
use crypto::digest::Digest;
use encoding::{all::ISO_8859_1, DecoderTrap, EncoderTrap, Encoding};
use futures::SinkExt;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpStream,
stream::StreamExt,
};
use tokio_util::codec::{Decoder, Encoder, Framed};
use tracing::*;
use crate::{errors::Error, util};
fn compute_nonce_hash(pass: &str, nonce: &str) -> String {
let mut digest = crypto::md5::Md5::new();
digest.input_str(&format!("{}{}", nonce, pass));
digest.result_str()
}
const TERMCHAR: u8 = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CodecMode {
Client,
Server,
}
pub struct BoincCodec {
mode: CodecMode,
next_index: usize,
}
impl BoincCodec {
#[must_use]
pub const fn new(mode: CodecMode) -> Self {
Self {
mode,
next_index: 0,
}
}
}
impl Decoder for BoincCodec {
type Item = Vec<treexml::Element>;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let read_to = src.len();
if let Some(offset) = src[self.next_index..read_to]
.iter()
.position(|b| *b == TERMCHAR)
{
let newline_index = offset + self.next_index;
self.next_index = 0;
let line = src.split_to(newline_index + 1);
let line = &line[..line.len() - 1];
let line = ISO_8859_1
.decode(line, DecoderTrap::Strict)
.map_err(|e| Error::DataParseError(format!("Invalid data received: {}", e)))?;
trace!("Received data: {}", line);
let line = line.trim_start_matches("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
let root_node = util::parse_node(line)?;
let expected_root = match self.mode {
CodecMode::Client => "boinc_gui_rpc_reply",
CodecMode::Server => "boinc_gui_rpc_request",
};
if root_node.name!= expected_root {
return Err(Error::DataParseError(format!(
"Invalid root: {}. Expected: {}",
root_node.name, expected_root
)));
}
Ok(Some(root_node.children))
} else {
self.next_index = read_to;
Ok(None)
}
}
}
impl Encoder<Vec<treexml::Element>> for BoincCodec {
type Error = Error;
fn encode(
&mut self,
item: Vec<treexml::Element>,
dst: &mut BytesMut,
) -> Result<(), Self::Error> {
let mut out = treexml::Element::new(match self.mode {
CodecMode::Client => "boinc_gui_rpc_request",
CodecMode::Server => "boinc_gui_rpc_reply",
});
out.children = item;
let data = format!("{}", out)
.replace("<?xml version='1.0'?>", "")
.replace(" />", "/>");
trace!("Sending data: {}", data);
dst.extend_from_slice(
&ISO_8859_1
.encode(&data, EncoderTrap::Strict)
.expect("Our data should always be correct"),
);
dst.extend_from_slice(&[TERMCHAR]);
Ok(())
}
}
pub struct | <Io> {
conn: Framed<Io, BoincCodec>,
}
impl DaemonStream<TcpStream> {
pub async fn connect(host: String, password: Option<String>) -> Result<Self, Error> {
Self::authenticate(TcpStream::connect(host).await?, password).await
}
}
impl<Io: AsyncRead + AsyncWrite + Unpin> DaemonStream<Io> {
async fn authenticate(io: Io, password: Option<String>) -> Result<Self, Error> {
let mut conn = BoincCodec::new(CodecMode::Client).framed(io);
let mut out = Some(vec![treexml::Element::new("auth1")]);
let mut nonce_sent = false;
loop {
if let Some(data) = out.take() {
conn.send(data).await?;
let data = conn
.try_next()
.await?
.ok_or_else(|| Error::DaemonError("EOF".into()))?;
for node in data {
match &*node.name {
"nonce" => {
if nonce_sent {
return Err(Error::DaemonError(
"Daemon requested nonce again - could be a bug".into(),
));
}
let mut nonce_node = treexml::Element::new("nonce_hash");
let pwd = password.clone().ok_or_else(|| {
Error::AuthError("Password required for nonce".to_string())
})?;
nonce_node.text = Some(compute_nonce_hash(
&pwd,
&node
.text
.ok_or_else(|| Error::AuthError("Invalid nonce".into()))?,
));
let mut auth2_node = treexml::Element::new("auth2");
auth2_node.children.push(nonce_node);
out = Some(vec![auth2_node]);
nonce_sent = true;
}
"unauthorized" => {
return Err(Error::AuthError("unauthorized".to_string()));
}
"error" => {
return Err(Error::DaemonError(format!(
"BOINC daemon returned error: {:?}",
node.text
)));
}
"authorized" => {
return Ok(Self { conn });
}
_ => {
return Err(Error::DaemonError(format!(
"Invalid response from daemon: {}",
node.name
)));
}
}
}
} else {
return Err(Error::DaemonError("Empty response".into()));
}
}
}
pub(crate) async fn query(
&mut self,
request_data: Vec<treexml::Element>,
) -> Result<Vec<treexml::Element>, Error> {
self.conn.send(request_data).await?;
let data = self
.conn
.try_next()
.await?
.ok_or_else(|| Error::DaemonError("EOF".into()))?;
Ok(data)
}
}
| DaemonStream | identifier_name |
rpc.rs | extern crate crypto;
use bytes::BytesMut;
use crypto::digest::Digest;
use encoding::{all::ISO_8859_1, DecoderTrap, EncoderTrap, Encoding};
use futures::SinkExt;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpStream,
stream::StreamExt,
};
use tokio_util::codec::{Decoder, Encoder, Framed};
use tracing::*;
use crate::{errors::Error, util};
fn compute_nonce_hash(pass: &str, nonce: &str) -> String {
let mut digest = crypto::md5::Md5::new();
digest.input_str(&format!("{}{}", nonce, pass));
digest.result_str()
}
const TERMCHAR: u8 = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CodecMode {
Client,
Server,
}
pub struct BoincCodec {
mode: CodecMode,
next_index: usize,
}
impl BoincCodec {
#[must_use]
pub const fn new(mode: CodecMode) -> Self {
Self {
mode,
next_index: 0,
}
}
}
impl Decoder for BoincCodec {
type Item = Vec<treexml::Element>;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let read_to = src.len();
if let Some(offset) = src[self.next_index..read_to]
.iter()
.position(|b| *b == TERMCHAR)
{
let newline_index = offset + self.next_index;
self.next_index = 0;
let line = src.split_to(newline_index + 1);
let line = &line[..line.len() - 1];
let line = ISO_8859_1
.decode(line, DecoderTrap::Strict)
.map_err(|e| Error::DataParseError(format!("Invalid data received: {}", e)))?;
trace!("Received data: {}", line);
let line = line.trim_start_matches("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
let root_node = util::parse_node(line)?;
let expected_root = match self.mode {
CodecMode::Client => "boinc_gui_rpc_reply",
CodecMode::Server => "boinc_gui_rpc_request",
};
if root_node.name!= expected_root {
return Err(Error::DataParseError(format!(
"Invalid root: {}. Expected: {}",
root_node.name, expected_root
)));
}
Ok(Some(root_node.children))
} else {
self.next_index = read_to;
Ok(None)
}
}
}
impl Encoder<Vec<treexml::Element>> for BoincCodec {
type Error = Error;
fn encode(
&mut self,
item: Vec<treexml::Element>,
dst: &mut BytesMut,
) -> Result<(), Self::Error> {
let mut out = treexml::Element::new(match self.mode {
CodecMode::Client => "boinc_gui_rpc_request",
CodecMode::Server => "boinc_gui_rpc_reply",
});
out.children = item;
let data = format!("{}", out)
.replace("<?xml version='1.0'?>", "")
.replace(" />", "/>");
trace!("Sending data: {}", data);
dst.extend_from_slice(
&ISO_8859_1
.encode(&data, EncoderTrap::Strict)
.expect("Our data should always be correct"),
);
dst.extend_from_slice(&[TERMCHAR]);
Ok(())
}
}
pub struct DaemonStream<Io> {
conn: Framed<Io, BoincCodec>,
}
impl DaemonStream<TcpStream> {
pub async fn connect(host: String, password: Option<String>) -> Result<Self, Error> {
Self::authenticate(TcpStream::connect(host).await?, password).await
}
}
impl<Io: AsyncRead + AsyncWrite + Unpin> DaemonStream<Io> {
async fn authenticate(io: Io, password: Option<String>) -> Result<Self, Error> {
let mut conn = BoincCodec::new(CodecMode::Client).framed(io);
let mut out = Some(vec![treexml::Element::new("auth1")]);
let mut nonce_sent = false;
loop {
if let Some(data) = out.take() {
conn.send(data).await?;
let data = conn
.try_next()
.await?
.ok_or_else(|| Error::DaemonError("EOF".into()))?;
for node in data {
match &*node.name {
"nonce" => {
if nonce_sent {
return Err(Error::DaemonError(
"Daemon requested nonce again - could be a bug".into(),
));
}
let mut nonce_node = treexml::Element::new("nonce_hash");
let pwd = password.clone().ok_or_else(|| {
Error::AuthError("Password required for nonce".to_string())
})?;
nonce_node.text = Some(compute_nonce_hash(
&pwd,
&node
.text
.ok_or_else(|| Error::AuthError("Invalid nonce".into()))?,
));
let mut auth2_node = treexml::Element::new("auth2");
auth2_node.children.push(nonce_node);
out = Some(vec![auth2_node]);
nonce_sent = true;
}
"unauthorized" => {
return Err(Error::AuthError("unauthorized".to_string()));
}
"error" => {
return Err(Error::DaemonError(format!(
"BOINC daemon returned error: {:?}",
node.text
)));
}
"authorized" => {
return Ok(Self { conn });
}
_ => {
return Err(Error::DaemonError(format!(
"Invalid response from daemon: {}",
node.name
)));
}
}
}
} else {
return Err(Error::DaemonError("Empty response".into()));
}
}
} |
pub(crate) async fn query(
&mut self,
request_data: Vec<treexml::Element>,
) -> Result<Vec<treexml::Element>, Error> {
self.conn.send(request_data).await?;
let data = self
.conn
.try_next()
.await?
.ok_or_else(|| Error::DaemonError("EOF".into()))?;
Ok(data)
}
} | random_line_split |
|
placement-in-syntax.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.
#![allow(dead_code, unused_variables)]
#![feature(box_heap)]
#![feature(placement_in_syntax)] | //
// Compare with new-box-syntax.rs
use std::boxed::{Box, HEAP};
struct Structure {
x: isize,
y: isize,
}
pub fn main() {
let x: Box<isize> = in HEAP { 2 };
let b: Box<isize> = in HEAP { 1 + 2 };
let c = in HEAP { 3 + 4 };
let s: Box<Structure> = in HEAP {
Structure {
x: 3,
y: 4,
}
};
} |
// Tests that the new `in` syntax works with unique pointers. | random_line_split |
placement-in-syntax.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.
#![allow(dead_code, unused_variables)]
#![feature(box_heap)]
#![feature(placement_in_syntax)]
// Tests that the new `in` syntax works with unique pointers.
//
// Compare with new-box-syntax.rs
use std::boxed::{Box, HEAP};
struct Structure {
x: isize,
y: isize,
}
pub fn | () {
let x: Box<isize> = in HEAP { 2 };
let b: Box<isize> = in HEAP { 1 + 2 };
let c = in HEAP { 3 + 4 };
let s: Box<Structure> = in HEAP {
Structure {
x: 3,
y: 4,
}
};
}
| main | identifier_name |
placement-in-syntax.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.
#![allow(dead_code, unused_variables)]
#![feature(box_heap)]
#![feature(placement_in_syntax)]
// Tests that the new `in` syntax works with unique pointers.
//
// Compare with new-box-syntax.rs
use std::boxed::{Box, HEAP};
struct Structure {
x: isize,
y: isize,
}
pub fn main() | {
let x: Box<isize> = in HEAP { 2 };
let b: Box<isize> = in HEAP { 1 + 2 };
let c = in HEAP { 3 + 4 };
let s: Box<Structure> = in HEAP {
Structure {
x: 3,
y: 4,
}
};
} | identifier_body |
|
lib.rs | /*!
# Kiss3d
Keep It Simple, Stupid 3d graphics engine.
This library is born from the frustration in front of the fact that today’s 3D
graphics library are:
* either too low level: you have to write your own shaders and opening a
window steals you 8 hours, 300 lines of code and 10L of coffee.
* or high level but too hard to understand/use: those are libraries made to
write beautiful animations or games. They have a lot of feature; too much
feature if you only want to draw a few geometries on the screen.
**Kiss3d** is not designed to be feature-complete or fast.
It is designed to be able to draw simple geometric figures and play with them
with one-liners.
## Features
Most features are one-liners.
* open a window with a default arc-ball camera and a point light.
* a first-person camera is available too and user-defined cameras are possible.
* display boxes, spheres, cones, cylinders, quads and lines.
* change an object color or texture.
* change an object transform (we use the [nalgebra](http://nalgebra.org) library
to do that). An object cannot be scaled though.
* create basic post-processing effects.
As an example, having a red, rotating cube with the light attached to the camera is as simple as:
```no_run
extern crate kiss3d;
extern crate nalgebra as na;
use na::Vec3;
use kiss3d::window::Window;
use kiss3d::light::Light;
fn main() {
let mut window = Window::new("Kiss3d: cube");
let mut c = window.add_cube(1.0, 1.0, 1.0);
c.set_color(1.0, 0.0, 0.0);
window.set_light(Light::StickToCamera);
while window.render() {
c.prepend_to_local_rotation(&Vec3::new(0.0f32, 0.014, 0.0));
}
}
```
Some controls are handled by default by the engine (they can be overridden by the user):
* `scroll`: zoom in / zoom out.
* `left click + drag`: look around.
* `right click + drag`: translate the view point.
* `enter`: look at the origin (0.0, 0.0, 0.0).
## Compilation
You will need the last nightly build of the [rust compiler](http://www.rust-lang.org)
and the official package manager: [cargo](https://github.com/rust-lang/cargo).
Simply add the following to your `Cargo.toml` file: | ```text
[dependencies.kiss3d]
git = "https://github.com/sebcrozet/kiss3d"
```
## Contributions
I’d love to see people improving this library for their own needs. However, keep in mind that
**Kiss3d** is KISS. One-liner features (from the user point of view) are preferred.
*/
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_qualifications)]
#![warn(missing_docs)] // FIXME: should be denied.
#![deny(unused_results)]
#![allow(unused_unsafe)] // FIXME: should be denied
#![allow(missing_copy_implementations)]
#![doc(html_root_url = "http://kiss3d.org/doc")]
extern crate libc;
extern crate time;
extern crate gl;
extern crate num;
extern crate nalgebra as na;
extern crate ncollide_procedural;
extern crate image;
extern crate freetype;
extern crate glfw;
mod error;
pub mod window;
pub mod scene;
pub mod camera;
pub mod light;
pub mod loader;
pub mod line_renderer;
pub mod point_renderer;
pub mod builtin;
pub mod post_processing;
pub mod resource;
pub mod text; | random_line_split |
|
mod.rs | //! Dedicated single thread actor-ref implementations
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::fmt::{self, Debug, Formatter};
use {Actor, ActorSpawner};
use {ActorRef, ActorRefImpl, ActorRefEnum};
use {SendError};
#[cfg(test)]
mod tests;
/// A simplistic environment to run an actor in
/// which can act as ActorRef.
///
/// It uses one thread per actor.
pub struct ActorCell<Message: Send> {
tx: Sender<Message>,
actor: Arc<Mutex<Box<Actor<Message>>>>,
}
/// An ActorSpawner which spawns a dedicated thread for every
/// actor.
pub struct DedicatedThreadSpawner;
impl ActorSpawner for DedicatedThreadSpawner {
/// Create and ActorCell for the given actor.
fn spawn<Message, A>(&self, actor: A) -> ActorRef<Message>
where Message: Send +'static, A: Actor<Message> +'static
{
let (tx, rx) = channel();
let actor_box: Box<Actor<Message>> = Box::new(actor);
let actor = Arc::new(Mutex::new(actor_box));
let actor_for_thread = actor.clone();
thread::spawn( move|| {
let mut actor = actor_for_thread.lock().unwrap();
loop {
match rx.recv() {
Ok(msg) => {
debug!("Processing");
actor.process(msg);
},
Err(error) => {
debug!("Quitting: {:?}", error);
break;
},
}
}
});
ActorRef(
ActorRefEnum::DedicatedThread(
ActorCell {
tx: tx,
actor: actor
}
)
)
}
}
impl<Message: Send +'static> ActorRefImpl<Message> for ActorCell<Message> {
fn | (&self, msg: Message) -> Result<(), SendError<Message>> {
Ok(try!(self.tx.send(msg)))
}
}
impl<Message: Send +'static> Debug for ActorCell<Message> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "ActorCell")
}
}
impl<Message: Send +'static> Clone for ActorCell<Message> {
fn clone(&self) -> ActorCell<Message> {
ActorCell {
tx: self.tx.clone(),
actor: self.actor.clone(),
}
}
}
| send | identifier_name |
mod.rs | //! Dedicated single thread actor-ref implementations
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::fmt::{self, Debug, Formatter};
use {Actor, ActorSpawner};
use {ActorRef, ActorRefImpl, ActorRefEnum};
use {SendError};
#[cfg(test)]
mod tests;
/// A simplistic environment to run an actor in
/// which can act as ActorRef.
///
/// It uses one thread per actor.
pub struct ActorCell<Message: Send> {
tx: Sender<Message>,
actor: Arc<Mutex<Box<Actor<Message>>>>,
}
/// An ActorSpawner which spawns a dedicated thread for every
/// actor.
pub struct DedicatedThreadSpawner;
impl ActorSpawner for DedicatedThreadSpawner {
/// Create and ActorCell for the given actor.
fn spawn<Message, A>(&self, actor: A) -> ActorRef<Message>
where Message: Send +'static, A: Actor<Message> +'static
| }
});
ActorRef(
ActorRefEnum::DedicatedThread(
ActorCell {
tx: tx,
actor: actor
}
)
)
}
}
impl<Message: Send +'static> ActorRefImpl<Message> for ActorCell<Message> {
fn send(&self, msg: Message) -> Result<(), SendError<Message>> {
Ok(try!(self.tx.send(msg)))
}
}
impl<Message: Send +'static> Debug for ActorCell<Message> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "ActorCell")
}
}
impl<Message: Send +'static> Clone for ActorCell<Message> {
fn clone(&self) -> ActorCell<Message> {
ActorCell {
tx: self.tx.clone(),
actor: self.actor.clone(),
}
}
}
| {
let (tx, rx) = channel();
let actor_box: Box<Actor<Message>> = Box::new(actor);
let actor = Arc::new(Mutex::new(actor_box));
let actor_for_thread = actor.clone();
thread::spawn( move|| {
let mut actor = actor_for_thread.lock().unwrap();
loop {
match rx.recv() {
Ok(msg) => {
debug!("Processing");
actor.process(msg);
},
Err(error) => {
debug!("Quitting: {:?}", error);
break;
},
} | identifier_body |
mod.rs | //! Dedicated single thread actor-ref implementations
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::fmt::{self, Debug, Formatter};
use {Actor, ActorSpawner};
use {ActorRef, ActorRefImpl, ActorRefEnum};
use {SendError};
#[cfg(test)]
mod tests;
/// A simplistic environment to run an actor in
/// which can act as ActorRef.
///
/// It uses one thread per actor.
pub struct ActorCell<Message: Send> {
tx: Sender<Message>,
actor: Arc<Mutex<Box<Actor<Message>>>>,
}
/// An ActorSpawner which spawns a dedicated thread for every
/// actor.
pub struct DedicatedThreadSpawner;
impl ActorSpawner for DedicatedThreadSpawner {
/// Create and ActorCell for the given actor.
fn spawn<Message, A>(&self, actor: A) -> ActorRef<Message>
where Message: Send +'static, A: Actor<Message> +'static
{
let (tx, rx) = channel();
let actor_box: Box<Actor<Message>> = Box::new(actor);
let actor = Arc::new(Mutex::new(actor_box));
let actor_for_thread = actor.clone();
thread::spawn( move|| {
let mut actor = actor_for_thread.lock().unwrap();
loop {
match rx.recv() {
Ok(msg) => | ,
Err(error) => {
debug!("Quitting: {:?}", error);
break;
},
}
}
});
ActorRef(
ActorRefEnum::DedicatedThread(
ActorCell {
tx: tx,
actor: actor
}
)
)
}
}
impl<Message: Send +'static> ActorRefImpl<Message> for ActorCell<Message> {
fn send(&self, msg: Message) -> Result<(), SendError<Message>> {
Ok(try!(self.tx.send(msg)))
}
}
impl<Message: Send +'static> Debug for ActorCell<Message> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "ActorCell")
}
}
impl<Message: Send +'static> Clone for ActorCell<Message> {
fn clone(&self) -> ActorCell<Message> {
ActorCell {
tx: self.tx.clone(),
actor: self.actor.clone(),
}
}
}
| {
debug!("Processing");
actor.process(msg);
} | conditional_block |
mod.rs | //! Dedicated single thread actor-ref implementations
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::fmt::{self, Debug, Formatter};
use {Actor, ActorSpawner};
use {ActorRef, ActorRefImpl, ActorRefEnum};
use {SendError};
#[cfg(test)]
mod tests;
/// A simplistic environment to run an actor in
/// which can act as ActorRef.
///
/// It uses one thread per actor.
pub struct ActorCell<Message: Send> {
tx: Sender<Message>,
actor: Arc<Mutex<Box<Actor<Message>>>>,
}
/// An ActorSpawner which spawns a dedicated thread for every
/// actor.
pub struct DedicatedThreadSpawner;
impl ActorSpawner for DedicatedThreadSpawner {
/// Create and ActorCell for the given actor.
fn spawn<Message, A>(&self, actor: A) -> ActorRef<Message>
where Message: Send +'static, A: Actor<Message> +'static
{
let (tx, rx) = channel();
let actor_box: Box<Actor<Message>> = Box::new(actor);
let actor = Arc::new(Mutex::new(actor_box));
let actor_for_thread = actor.clone();
thread::spawn( move|| {
let mut actor = actor_for_thread.lock().unwrap();
loop {
match rx.recv() {
Ok(msg) => {
debug!("Processing");
actor.process(msg);
},
Err(error) => {
debug!("Quitting: {:?}", error);
break;
},
}
}
});
ActorRef(
ActorRefEnum::DedicatedThread(
ActorCell {
tx: tx,
actor: actor
}
)
)
}
}
impl<Message: Send +'static> ActorRefImpl<Message> for ActorCell<Message> {
fn send(&self, msg: Message) -> Result<(), SendError<Message>> {
Ok(try!(self.tx.send(msg))) | }
impl<Message: Send +'static> Debug for ActorCell<Message> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "ActorCell")
}
}
impl<Message: Send +'static> Clone for ActorCell<Message> {
fn clone(&self) -> ActorCell<Message> {
ActorCell {
tx: self.tx.clone(),
actor: self.actor.clone(),
}
}
} | } | random_line_split |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
use ffi;
use itertools::{Itertools, Zip};
use std::mem::transmute;
use std::ops::Deref;
use std::ptr::null;
use std::os::raw;
use error::{Error, Result};
use model::{Model, Var, ConstrSense};
use model::expr::LinExpr;
use util;
// Location where the callback called.
const POLLING: i32 = 0;
const PRESOLVE: i32 = 1;
const SIMPLEX: i32 = 2;
const MIP: i32 = 3;
const MIPSOL: i32 = 4;
const MIPNODE: i32 = 5;
const MESSAGE: i32 = 6;
const BARRIER: i32 = 7;
const PRE_COLDEL: i32 = 1000;
const PRE_ROWDEL: i32 = 1001;
const PRE_SENCHG: i32 = 1002;
const PRE_BNDCHG: i32 = 1003;
const PRE_COECHG: i32 = 1004;
const SPX_ITRCNT: i32 = 2000;
const SPX_OBJVAL: i32 = 2001;
const SPX_PRIMINF: i32 = 2002;
const SPX_DUALINF: i32 = 2003;
const SPX_ISPERT: i32 = 2004;
const MIP_OBJBST: i32 = 3000;
const MIP_OBJBND: i32 = 3001;
const MIP_NODCNT: i32 = 3002;
const MIP_SOLCNT: i32 = 3003;
const MIP_CUTCNT: i32 = 3004;
const MIP_NODLFT: i32 = 3005;
const MIP_ITRCNT: i32 = 3006;
#[allow(dead_code)]
const MIP_OBJBNDC: i32 = 3007;
const MIPSOL_SOL: i32 = 4001;
const MIPSOL_OBJ: i32 = 4002;
const MIPSOL_OBJBST: i32 = 4003;
const MIPSOL_OBJBND: i32 = 4004;
const MIPSOL_NODCNT: i32 = 4005;
const MIPSOL_SOLCNT: i32 = 4006;
#[allow(dead_code)]
const MIPSOL_OBJBNDC: i32 = 4007;
const MIPNODE_STATUS: i32 = 5001;
const MIPNODE_REL: i32 = 5002;
const MIPNODE_OBJBST: i32 = 5003;
const MIPNODE_OBJBND: i32 = 5004;
const MIPNODE_NODCNT: i32 = 5005;
const MIPNODE_SOLCNT: i32 = 5006;
#[allow(dead_code)]
const MIPNODE_BRVAR: i32 = 5007;
#[allow(dead_code)]
const MIPNODE_OBJBNDC: i32 = 5008;
const MSG_STRING: i32 = 6001;
const RUNTIME: i32 = 6002;
const BARRIER_ITRCNT: i32 = 7001;
const BARRIER_PRIMOBJ: i32 = 7002;
const BARRIER_DUALOBJ: i32 = 7003;
const BARRIER_PRIMINF: i32 = 7004;
const BARRIER_DUALINF: i32 = 7005;
const BARRIER_COMPL: i32 = 7006;
/// Location where the callback called
///
/// If you want to get more information, see [official
/// manual](https://www.gurobi.com/documentation/6.5/refman/callback_codes.html).
#[derive(Debug, Clone)]
pub enum Where {
/// Periodic polling callback
Polling,
/// Currently performing presolve
PreSolve {
/// The number of columns removed by presolve to this point.
coldel: i32,
/// The number of rows removed by presolve to this point.
rowdel: i32,
/// The number of constraint senses changed by presolve to this point.
senchg: i32,
/// The number of variable bounds changed by presolve to this point.
bndchg: i32,
/// The number of coefficients changed by presolve to this point.
coecfg: i32
},
/// Currently in simplex
Simplex {
/// Current simplex iteration count.
itrcnt: f64,
/// Current simplex objective value.
objval: f64,
/// Current primal infeasibility.
priminf: f64,
/// Current dual infeasibility.
dualinf: f64,
/// Is problem current perturbed?
ispert: i32
},
/// Currently in MIP
MIP {
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64,
/// Current count of cutting planes applied.
cutcnt: i32,
/// Current unexplored node count.
nodleft: f64,
/// Current simplex iteration count.
itrcnt: f64
},
/// Found a new MIP incumbent
MIPSol {
/// Objective value for new solution.
obj: f64,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64
},
/// Currently exploring a MIP node
MIPNode {
/// Optimization status of current MIP node (see the Status Code section for further information).
status: i32,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: i32
},
/// Printing a log message
Message(String),
/// Currently in barrier.
Barrier {
/// Current barrier iteration count.
itrcnt: i32,
/// Primal objective value for current barrier iterate.
primobj: f64,
/// Dual objective value for current barrier iterate.
dualobj: f64,
/// Primal infeasibility for current barrier iterate.
priminf: f64,
/// Dual infeasibility for current barrier iterate.
dualinf: f64,
/// Complementarity violation for current barrier iterate.
compl: f64
}
}
impl Into<i32> for Where {
fn into(self) -> i32 {
match self {
Where::Polling => POLLING,
Where::PreSolve {.. } => PRESOLVE,
Where::Simplex {.. } => SIMPLEX,
Where::MIP {.. } => MIP,
Where::MIPSol {.. } => MIPSOL,
Where::MIPNode {.. } => MIPNODE,
Where::Message(_) => MESSAGE,
Where::Barrier {.. } => BARRIER,
}
}
}
/// The context object for Gurobi callback.
pub struct Callback<'a> {
cbdata: *mut ffi::c_void,
where_: Where,
model: &'a Model
}
pub trait New<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>>;
}
impl<'a> New<'a> for Callback<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>> {
let mut callback = Callback {
cbdata: cbdata,
where_: Where::Polling,
model: model
};
let where_ = match where_ {
POLLING => Where::Polling,
PRESOLVE => {
Where::PreSolve {
coldel: try!(callback.get_int(PRESOLVE, PRE_COLDEL)),
rowdel: try!(callback.get_int(PRESOLVE, PRE_ROWDEL)),
senchg: try!(callback.get_int(PRESOLVE, PRE_SENCHG)),
bndchg: try!(callback.get_int(PRESOLVE, PRE_BNDCHG)),
coecfg: try!(callback.get_int(PRESOLVE, PRE_COECHG))
}
}
SIMPLEX => {
Where::Simplex {
itrcnt: try!(callback.get_double(SIMPLEX, SPX_ITRCNT)),
objval: try!(callback.get_double(SIMPLEX, SPX_OBJVAL)),
priminf: try!(callback.get_double(SIMPLEX, SPX_PRIMINF)),
dualinf: try!(callback.get_double(SIMPLEX, SPX_DUALINF)),
ispert: try!(callback.get_int(SIMPLEX, SPX_ISPERT))
}
}
MIP => {
Where::MIP {
objbst: try!(callback.get_double(MIP, MIP_OBJBST)),
objbnd: try!(callback.get_double(MIP, MIP_OBJBND)),
nodcnt: try!(callback.get_double(MIP, MIP_NODCNT)),
solcnt: try!(callback.get_double(MIP, MIP_SOLCNT)),
cutcnt: try!(callback.get_int(MIP, MIP_CUTCNT)),
nodleft: try!(callback.get_double(MIP, MIP_NODLFT)),
itrcnt: try!(callback.get_double(MIP, MIP_ITRCNT))
}
}
MIPSOL => {
Where::MIPSol {
obj: try!(callback.get_double(MIPSOL, MIPSOL_OBJ)),
objbst: try!(callback.get_double(MIPSOL, MIPSOL_OBJBST)),
objbnd: try!(callback.get_double(MIPSOL, MIPSOL_OBJBND)),
nodcnt: try!(callback.get_double(MIPSOL, MIPSOL_NODCNT)),
solcnt: try!(callback.get_double(MIPSOL, MIPSOL_SOLCNT))
}
}
MIPNODE => {
Where::MIPNode {
status: try!(callback.get_int(MIPNODE, MIPNODE_STATUS)),
objbst: try!(callback.get_double(MIPNODE, MIPNODE_OBJBST)),
objbnd: try!(callback.get_double(MIPNODE, MIPNODE_OBJBND)),
nodcnt: try!(callback.get_double(MIPNODE, MIPNODE_NODCNT)),
solcnt: try!(callback.get_int(MIPNODE, MIPNODE_SOLCNT))
}
}
MESSAGE => Where::Message(try!(callback.get_string(MESSAGE, MSG_STRING)).trim().to_owned()),
BARRIER => {
Where::Barrier {
itrcnt: try!(callback.get_int(BARRIER, BARRIER_ITRCNT)),
primobj: try!(callback.get_double(BARRIER, BARRIER_PRIMOBJ)),
dualobj: try!(callback.get_double(BARRIER, BARRIER_DUALOBJ)),
priminf: try!(callback.get_double(BARRIER, BARRIER_PRIMINF)),
dualinf: try!(callback.get_double(BARRIER, BARRIER_DUALINF)),
compl: try!(callback.get_double(BARRIER, BARRIER_COMPL))
}
}
_ => panic!("Invalid callback location. {}", where_)
};
callback.where_ = where_;
Ok(callback)
}
}
impl<'a> Callback<'a> {
/// Retrieve the location where the callback called.
pub fn get_where(&self) -> Where { self.where_.clone() }
/// Retrive node relaxation solution values at the current node.
pub fn get_node_rel(&self, vars: &[Var]) -> Result<Vec<f64>> {
// memo: only MIPNode && status == Optimal
self.get_double_array(MIPNODE, MIPNODE_REL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Retrieve values from the current solution vector.
pub fn get_solution(&self, vars: &[Var]) -> Result<Vec<f64>> {
self.get_double_array(MIPSOL, MIPSOL_SOL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Provide a new feasible solution for a MIP model.
pub fn set_solution(&self, vars: &[Var], solution: &[f64]) -> Result<()> {
if vars.len()!= solution.len() || vars.len() < self.model.vars.len() {
return Err(Error::InconsitentDims);
}
let mut buf = vec![0.0; self.model.vars.len()];
for (v, &sol) in Zip::new((vars.iter(), solution.iter())) {
let i = v.index() as usize;
buf[i] = sol;
}
self.check_apicall(unsafe { ffi::GRBcbsolution(self.cbdata, buf.as_ptr()) })
}
/// Retrieve the elapsed solver runtime [sec].
pub fn get_runtime(&self) -> Result<f64> {
if let Where::Polling = self.get_where() {
return Err(Error::FromAPI("bad call in callback".to_owned(), 40001));
}
self.get_double(self.get_where().into(), RUNTIME)
}
/// Add a new cutting plane to the MIP model.
pub fn add_cut(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcbcut(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
/// Add a new lazy constraint to the MIP model.
pub fn add_lazy(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcblazy(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
fn get_int(&self, where_: i32, what: i32) -> Result<i32> {
let mut buf = 0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut i32 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double(&self, where_: i32, what: i32) -> Result<f64> {
let mut buf = 0.0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut f64 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double_array(&self, where_: i32, what: i32) -> Result<Vec<f64>> {
let mut buf = vec![0.0; self.model.vars.len()];
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, transmute(buf.as_mut_ptr())) }).and(Ok(buf))
}
fn get_string(&self, where_: i32, what: i32) -> Result<String> {
let mut buf = null();
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut *const i8 as *mut raw::c_void) })
.and(Ok(unsafe { util::from_c_str(buf) }))
}
fn check_apicall(&self, error: ffi::c_int) -> Result<()> {
if error!= 0 {
return Err(Error::FromAPI("Callback error".to_owned(), 40000));
}
Ok(())
}
}
impl<'a> Deref for Callback<'a> {
type Target = Model;
fn | (&self) -> &Model { self.model }
}
| deref | identifier_name |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
use ffi;
use itertools::{Itertools, Zip};
use std::mem::transmute;
use std::ops::Deref;
use std::ptr::null;
use std::os::raw;
use error::{Error, Result};
use model::{Model, Var, ConstrSense};
use model::expr::LinExpr;
use util;
// Location where the callback called.
const POLLING: i32 = 0;
const PRESOLVE: i32 = 1;
const SIMPLEX: i32 = 2;
const MIP: i32 = 3;
const MIPSOL: i32 = 4;
const MIPNODE: i32 = 5;
const MESSAGE: i32 = 6;
const BARRIER: i32 = 7;
const PRE_COLDEL: i32 = 1000;
const PRE_ROWDEL: i32 = 1001;
const PRE_SENCHG: i32 = 1002;
const PRE_BNDCHG: i32 = 1003;
const PRE_COECHG: i32 = 1004;
const SPX_ITRCNT: i32 = 2000;
const SPX_OBJVAL: i32 = 2001;
const SPX_PRIMINF: i32 = 2002;
const SPX_DUALINF: i32 = 2003;
const SPX_ISPERT: i32 = 2004;
const MIP_OBJBST: i32 = 3000;
const MIP_OBJBND: i32 = 3001;
const MIP_NODCNT: i32 = 3002;
const MIP_SOLCNT: i32 = 3003;
const MIP_CUTCNT: i32 = 3004;
const MIP_NODLFT: i32 = 3005;
const MIP_ITRCNT: i32 = 3006;
#[allow(dead_code)]
const MIP_OBJBNDC: i32 = 3007;
const MIPSOL_SOL: i32 = 4001;
const MIPSOL_OBJ: i32 = 4002;
const MIPSOL_OBJBST: i32 = 4003;
const MIPSOL_OBJBND: i32 = 4004;
const MIPSOL_NODCNT: i32 = 4005;
const MIPSOL_SOLCNT: i32 = 4006;
#[allow(dead_code)]
const MIPSOL_OBJBNDC: i32 = 4007;
const MIPNODE_STATUS: i32 = 5001;
const MIPNODE_REL: i32 = 5002;
const MIPNODE_OBJBST: i32 = 5003;
const MIPNODE_OBJBND: i32 = 5004;
const MIPNODE_NODCNT: i32 = 5005;
const MIPNODE_SOLCNT: i32 = 5006;
#[allow(dead_code)]
const MIPNODE_BRVAR: i32 = 5007;
#[allow(dead_code)]
const MIPNODE_OBJBNDC: i32 = 5008;
const MSG_STRING: i32 = 6001;
const RUNTIME: i32 = 6002;
const BARRIER_ITRCNT: i32 = 7001;
const BARRIER_PRIMOBJ: i32 = 7002;
const BARRIER_DUALOBJ: i32 = 7003;
const BARRIER_PRIMINF: i32 = 7004;
const BARRIER_DUALINF: i32 = 7005;
const BARRIER_COMPL: i32 = 7006;
/// Location where the callback called
///
/// If you want to get more information, see [official
/// manual](https://www.gurobi.com/documentation/6.5/refman/callback_codes.html).
#[derive(Debug, Clone)]
pub enum Where {
/// Periodic polling callback
Polling,
/// Currently performing presolve
PreSolve {
/// The number of columns removed by presolve to this point.
coldel: i32,
/// The number of rows removed by presolve to this point.
rowdel: i32,
/// The number of constraint senses changed by presolve to this point.
senchg: i32,
/// The number of variable bounds changed by presolve to this point.
bndchg: i32,
/// The number of coefficients changed by presolve to this point.
coecfg: i32
},
/// Currently in simplex
Simplex {
/// Current simplex iteration count.
itrcnt: f64,
/// Current simplex objective value.
objval: f64,
/// Current primal infeasibility.
priminf: f64,
/// Current dual infeasibility.
dualinf: f64,
/// Is problem current perturbed?
ispert: i32
},
/// Currently in MIP
MIP {
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64,
/// Current count of cutting planes applied.
cutcnt: i32,
/// Current unexplored node count.
nodleft: f64,
/// Current simplex iteration count.
itrcnt: f64
},
/// Found a new MIP incumbent
MIPSol {
/// Objective value for new solution.
obj: f64,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64
},
/// Currently exploring a MIP node
MIPNode {
/// Optimization status of current MIP node (see the Status Code section for further information).
status: i32,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: i32
},
/// Printing a log message
Message(String),
/// Currently in barrier.
Barrier {
/// Current barrier iteration count.
itrcnt: i32,
/// Primal objective value for current barrier iterate.
primobj: f64,
/// Dual objective value for current barrier iterate.
dualobj: f64,
/// Primal infeasibility for current barrier iterate.
priminf: f64,
/// Dual infeasibility for current barrier iterate.
dualinf: f64,
/// Complementarity violation for current barrier iterate.
compl: f64
}
}
impl Into<i32> for Where {
fn into(self) -> i32 {
match self {
Where::Polling => POLLING,
Where::PreSolve {.. } => PRESOLVE,
Where::Simplex {.. } => SIMPLEX,
Where::MIP {.. } => MIP,
Where::MIPSol {.. } => MIPSOL,
Where::MIPNode {.. } => MIPNODE,
Where::Message(_) => MESSAGE,
Where::Barrier {.. } => BARRIER,
}
}
}
/// The context object for Gurobi callback.
pub struct Callback<'a> {
cbdata: *mut ffi::c_void,
where_: Where,
model: &'a Model
}
pub trait New<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>>;
}
impl<'a> New<'a> for Callback<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>> | Where::Simplex {
itrcnt: try!(callback.get_double(SIMPLEX, SPX_ITRCNT)),
objval: try!(callback.get_double(SIMPLEX, SPX_OBJVAL)),
priminf: try!(callback.get_double(SIMPLEX, SPX_PRIMINF)),
dualinf: try!(callback.get_double(SIMPLEX, SPX_DUALINF)),
ispert: try!(callback.get_int(SIMPLEX, SPX_ISPERT))
}
}
MIP => {
Where::MIP {
objbst: try!(callback.get_double(MIP, MIP_OBJBST)),
objbnd: try!(callback.get_double(MIP, MIP_OBJBND)),
nodcnt: try!(callback.get_double(MIP, MIP_NODCNT)),
solcnt: try!(callback.get_double(MIP, MIP_SOLCNT)),
cutcnt: try!(callback.get_int(MIP, MIP_CUTCNT)),
nodleft: try!(callback.get_double(MIP, MIP_NODLFT)),
itrcnt: try!(callback.get_double(MIP, MIP_ITRCNT))
}
}
MIPSOL => {
Where::MIPSol {
obj: try!(callback.get_double(MIPSOL, MIPSOL_OBJ)),
objbst: try!(callback.get_double(MIPSOL, MIPSOL_OBJBST)),
objbnd: try!(callback.get_double(MIPSOL, MIPSOL_OBJBND)),
nodcnt: try!(callback.get_double(MIPSOL, MIPSOL_NODCNT)),
solcnt: try!(callback.get_double(MIPSOL, MIPSOL_SOLCNT))
}
}
MIPNODE => {
Where::MIPNode {
status: try!(callback.get_int(MIPNODE, MIPNODE_STATUS)),
objbst: try!(callback.get_double(MIPNODE, MIPNODE_OBJBST)),
objbnd: try!(callback.get_double(MIPNODE, MIPNODE_OBJBND)),
nodcnt: try!(callback.get_double(MIPNODE, MIPNODE_NODCNT)),
solcnt: try!(callback.get_int(MIPNODE, MIPNODE_SOLCNT))
}
}
MESSAGE => Where::Message(try!(callback.get_string(MESSAGE, MSG_STRING)).trim().to_owned()),
BARRIER => {
Where::Barrier {
itrcnt: try!(callback.get_int(BARRIER, BARRIER_ITRCNT)),
primobj: try!(callback.get_double(BARRIER, BARRIER_PRIMOBJ)),
dualobj: try!(callback.get_double(BARRIER, BARRIER_DUALOBJ)),
priminf: try!(callback.get_double(BARRIER, BARRIER_PRIMINF)),
dualinf: try!(callback.get_double(BARRIER, BARRIER_DUALINF)),
compl: try!(callback.get_double(BARRIER, BARRIER_COMPL))
}
}
_ => panic!("Invalid callback location. {}", where_)
};
callback.where_ = where_;
Ok(callback)
}
}
impl<'a> Callback<'a> {
/// Retrieve the location where the callback called.
pub fn get_where(&self) -> Where { self.where_.clone() }
/// Retrive node relaxation solution values at the current node.
pub fn get_node_rel(&self, vars: &[Var]) -> Result<Vec<f64>> {
// memo: only MIPNode && status == Optimal
self.get_double_array(MIPNODE, MIPNODE_REL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Retrieve values from the current solution vector.
pub fn get_solution(&self, vars: &[Var]) -> Result<Vec<f64>> {
self.get_double_array(MIPSOL, MIPSOL_SOL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Provide a new feasible solution for a MIP model.
pub fn set_solution(&self, vars: &[Var], solution: &[f64]) -> Result<()> {
if vars.len()!= solution.len() || vars.len() < self.model.vars.len() {
return Err(Error::InconsitentDims);
}
let mut buf = vec![0.0; self.model.vars.len()];
for (v, &sol) in Zip::new((vars.iter(), solution.iter())) {
let i = v.index() as usize;
buf[i] = sol;
}
self.check_apicall(unsafe { ffi::GRBcbsolution(self.cbdata, buf.as_ptr()) })
}
/// Retrieve the elapsed solver runtime [sec].
pub fn get_runtime(&self) -> Result<f64> {
if let Where::Polling = self.get_where() {
return Err(Error::FromAPI("bad call in callback".to_owned(), 40001));
}
self.get_double(self.get_where().into(), RUNTIME)
}
/// Add a new cutting plane to the MIP model.
pub fn add_cut(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcbcut(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
/// Add a new lazy constraint to the MIP model.
pub fn add_lazy(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcblazy(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
fn get_int(&self, where_: i32, what: i32) -> Result<i32> {
let mut buf = 0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut i32 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double(&self, where_: i32, what: i32) -> Result<f64> {
let mut buf = 0.0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut f64 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double_array(&self, where_: i32, what: i32) -> Result<Vec<f64>> {
let mut buf = vec![0.0; self.model.vars.len()];
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, transmute(buf.as_mut_ptr())) }).and(Ok(buf))
}
fn get_string(&self, where_: i32, what: i32) -> Result<String> {
let mut buf = null();
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut *const i8 as *mut raw::c_void) })
.and(Ok(unsafe { util::from_c_str(buf) }))
}
fn check_apicall(&self, error: ffi::c_int) -> Result<()> {
if error!= 0 {
return Err(Error::FromAPI("Callback error".to_owned(), 40000));
}
Ok(())
}
}
impl<'a> Deref for Callback<'a> {
type Target = Model;
fn deref(&self) -> &Model { self.model }
}
| {
let mut callback = Callback {
cbdata: cbdata,
where_: Where::Polling,
model: model
};
let where_ = match where_ {
POLLING => Where::Polling,
PRESOLVE => {
Where::PreSolve {
coldel: try!(callback.get_int(PRESOLVE, PRE_COLDEL)),
rowdel: try!(callback.get_int(PRESOLVE, PRE_ROWDEL)),
senchg: try!(callback.get_int(PRESOLVE, PRE_SENCHG)),
bndchg: try!(callback.get_int(PRESOLVE, PRE_BNDCHG)),
coecfg: try!(callback.get_int(PRESOLVE, PRE_COECHG))
}
}
SIMPLEX => { | identifier_body |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
use ffi;
use itertools::{Itertools, Zip};
use std::mem::transmute;
use std::ops::Deref;
use std::ptr::null;
use std::os::raw;
use error::{Error, Result};
use model::{Model, Var, ConstrSense};
use model::expr::LinExpr;
use util;
// Location where the callback called.
const POLLING: i32 = 0;
const PRESOLVE: i32 = 1;
const SIMPLEX: i32 = 2;
const MIP: i32 = 3;
const MIPSOL: i32 = 4;
const MIPNODE: i32 = 5;
const MESSAGE: i32 = 6;
const BARRIER: i32 = 7;
const PRE_COLDEL: i32 = 1000;
const PRE_ROWDEL: i32 = 1001;
const PRE_SENCHG: i32 = 1002;
const PRE_BNDCHG: i32 = 1003;
const PRE_COECHG: i32 = 1004;
const SPX_ITRCNT: i32 = 2000;
const SPX_OBJVAL: i32 = 2001;
const SPX_PRIMINF: i32 = 2002;
const SPX_DUALINF: i32 = 2003;
const SPX_ISPERT: i32 = 2004;
const MIP_OBJBST: i32 = 3000;
const MIP_OBJBND: i32 = 3001;
const MIP_NODCNT: i32 = 3002;
const MIP_SOLCNT: i32 = 3003;
const MIP_CUTCNT: i32 = 3004;
const MIP_NODLFT: i32 = 3005;
const MIP_ITRCNT: i32 = 3006;
#[allow(dead_code)]
const MIP_OBJBNDC: i32 = 3007;
const MIPSOL_SOL: i32 = 4001;
const MIPSOL_OBJ: i32 = 4002;
const MIPSOL_OBJBST: i32 = 4003;
const MIPSOL_OBJBND: i32 = 4004;
const MIPSOL_NODCNT: i32 = 4005;
const MIPSOL_SOLCNT: i32 = 4006;
#[allow(dead_code)]
const MIPSOL_OBJBNDC: i32 = 4007;
const MIPNODE_STATUS: i32 = 5001;
const MIPNODE_REL: i32 = 5002;
const MIPNODE_OBJBST: i32 = 5003;
const MIPNODE_OBJBND: i32 = 5004;
const MIPNODE_NODCNT: i32 = 5005;
const MIPNODE_SOLCNT: i32 = 5006;
#[allow(dead_code)]
const MIPNODE_BRVAR: i32 = 5007;
#[allow(dead_code)]
const MIPNODE_OBJBNDC: i32 = 5008;
const MSG_STRING: i32 = 6001;
const RUNTIME: i32 = 6002;
const BARRIER_ITRCNT: i32 = 7001;
const BARRIER_PRIMOBJ: i32 = 7002;
const BARRIER_DUALOBJ: i32 = 7003;
const BARRIER_PRIMINF: i32 = 7004;
const BARRIER_DUALINF: i32 = 7005;
const BARRIER_COMPL: i32 = 7006;
/// Location where the callback called
///
/// If you want to get more information, see [official
/// manual](https://www.gurobi.com/documentation/6.5/refman/callback_codes.html).
#[derive(Debug, Clone)]
pub enum Where {
/// Periodic polling callback
Polling,
/// Currently performing presolve
PreSolve {
/// The number of columns removed by presolve to this point.
coldel: i32,
/// The number of rows removed by presolve to this point.
rowdel: i32,
/// The number of constraint senses changed by presolve to this point.
senchg: i32,
/// The number of variable bounds changed by presolve to this point.
bndchg: i32,
/// The number of coefficients changed by presolve to this point.
coecfg: i32
},
/// Currently in simplex
Simplex {
/// Current simplex iteration count.
itrcnt: f64,
/// Current simplex objective value.
objval: f64,
/// Current primal infeasibility.
priminf: f64,
/// Current dual infeasibility.
dualinf: f64,
/// Is problem current perturbed?
ispert: i32
},
/// Currently in MIP
MIP {
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64,
/// Current count of cutting planes applied.
cutcnt: i32,
/// Current unexplored node count.
nodleft: f64,
/// Current simplex iteration count.
itrcnt: f64
},
/// Found a new MIP incumbent
MIPSol {
/// Objective value for new solution.
obj: f64,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64
},
/// Currently exploring a MIP node
MIPNode {
/// Optimization status of current MIP node (see the Status Code section for further information).
status: i32,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: i32
},
/// Printing a log message
Message(String),
/// Currently in barrier.
Barrier {
/// Current barrier iteration count.
itrcnt: i32,
/// Primal objective value for current barrier iterate.
primobj: f64,
/// Dual objective value for current barrier iterate.
dualobj: f64,
/// Primal infeasibility for current barrier iterate.
priminf: f64,
/// Dual infeasibility for current barrier iterate.
dualinf: f64,
/// Complementarity violation for current barrier iterate.
compl: f64
}
}
impl Into<i32> for Where {
fn into(self) -> i32 {
match self {
Where::Polling => POLLING,
Where::PreSolve {.. } => PRESOLVE,
Where::Simplex {.. } => SIMPLEX,
Where::MIP {.. } => MIP,
Where::MIPSol {.. } => MIPSOL,
Where::MIPNode {.. } => MIPNODE,
Where::Message(_) => MESSAGE,
Where::Barrier {.. } => BARRIER,
}
}
}
/// The context object for Gurobi callback.
pub struct Callback<'a> {
cbdata: *mut ffi::c_void,
where_: Where,
model: &'a Model
}
pub trait New<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>>;
}
impl<'a> New<'a> for Callback<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>> {
let mut callback = Callback {
cbdata: cbdata,
where_: Where::Polling,
model: model
};
let where_ = match where_ {
POLLING => Where::Polling,
PRESOLVE => {
Where::PreSolve {
coldel: try!(callback.get_int(PRESOLVE, PRE_COLDEL)),
rowdel: try!(callback.get_int(PRESOLVE, PRE_ROWDEL)),
senchg: try!(callback.get_int(PRESOLVE, PRE_SENCHG)),
bndchg: try!(callback.get_int(PRESOLVE, PRE_BNDCHG)),
coecfg: try!(callback.get_int(PRESOLVE, PRE_COECHG))
}
}
SIMPLEX => |
MIP => {
Where::MIP {
objbst: try!(callback.get_double(MIP, MIP_OBJBST)),
objbnd: try!(callback.get_double(MIP, MIP_OBJBND)),
nodcnt: try!(callback.get_double(MIP, MIP_NODCNT)),
solcnt: try!(callback.get_double(MIP, MIP_SOLCNT)),
cutcnt: try!(callback.get_int(MIP, MIP_CUTCNT)),
nodleft: try!(callback.get_double(MIP, MIP_NODLFT)),
itrcnt: try!(callback.get_double(MIP, MIP_ITRCNT))
}
}
MIPSOL => {
Where::MIPSol {
obj: try!(callback.get_double(MIPSOL, MIPSOL_OBJ)),
objbst: try!(callback.get_double(MIPSOL, MIPSOL_OBJBST)),
objbnd: try!(callback.get_double(MIPSOL, MIPSOL_OBJBND)),
nodcnt: try!(callback.get_double(MIPSOL, MIPSOL_NODCNT)),
solcnt: try!(callback.get_double(MIPSOL, MIPSOL_SOLCNT))
}
}
MIPNODE => {
Where::MIPNode {
status: try!(callback.get_int(MIPNODE, MIPNODE_STATUS)),
objbst: try!(callback.get_double(MIPNODE, MIPNODE_OBJBST)),
objbnd: try!(callback.get_double(MIPNODE, MIPNODE_OBJBND)),
nodcnt: try!(callback.get_double(MIPNODE, MIPNODE_NODCNT)),
solcnt: try!(callback.get_int(MIPNODE, MIPNODE_SOLCNT))
}
}
MESSAGE => Where::Message(try!(callback.get_string(MESSAGE, MSG_STRING)).trim().to_owned()),
BARRIER => {
Where::Barrier {
itrcnt: try!(callback.get_int(BARRIER, BARRIER_ITRCNT)),
primobj: try!(callback.get_double(BARRIER, BARRIER_PRIMOBJ)),
dualobj: try!(callback.get_double(BARRIER, BARRIER_DUALOBJ)),
priminf: try!(callback.get_double(BARRIER, BARRIER_PRIMINF)),
dualinf: try!(callback.get_double(BARRIER, BARRIER_DUALINF)),
compl: try!(callback.get_double(BARRIER, BARRIER_COMPL))
}
}
_ => panic!("Invalid callback location. {}", where_)
};
callback.where_ = where_;
Ok(callback)
}
}
impl<'a> Callback<'a> {
/// Retrieve the location where the callback called.
pub fn get_where(&self) -> Where { self.where_.clone() }
/// Retrive node relaxation solution values at the current node.
pub fn get_node_rel(&self, vars: &[Var]) -> Result<Vec<f64>> {
// memo: only MIPNode && status == Optimal
self.get_double_array(MIPNODE, MIPNODE_REL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Retrieve values from the current solution vector.
pub fn get_solution(&self, vars: &[Var]) -> Result<Vec<f64>> {
self.get_double_array(MIPSOL, MIPSOL_SOL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Provide a new feasible solution for a MIP model.
pub fn set_solution(&self, vars: &[Var], solution: &[f64]) -> Result<()> {
if vars.len()!= solution.len() || vars.len() < self.model.vars.len() {
return Err(Error::InconsitentDims);
}
let mut buf = vec![0.0; self.model.vars.len()];
for (v, &sol) in Zip::new((vars.iter(), solution.iter())) {
let i = v.index() as usize;
buf[i] = sol;
}
self.check_apicall(unsafe { ffi::GRBcbsolution(self.cbdata, buf.as_ptr()) })
}
/// Retrieve the elapsed solver runtime [sec].
pub fn get_runtime(&self) -> Result<f64> {
if let Where::Polling = self.get_where() {
return Err(Error::FromAPI("bad call in callback".to_owned(), 40001));
}
self.get_double(self.get_where().into(), RUNTIME)
}
/// Add a new cutting plane to the MIP model.
pub fn add_cut(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcbcut(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
/// Add a new lazy constraint to the MIP model.
pub fn add_lazy(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcblazy(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
fn get_int(&self, where_: i32, what: i32) -> Result<i32> {
let mut buf = 0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut i32 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double(&self, where_: i32, what: i32) -> Result<f64> {
let mut buf = 0.0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut f64 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double_array(&self, where_: i32, what: i32) -> Result<Vec<f64>> {
let mut buf = vec![0.0; self.model.vars.len()];
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, transmute(buf.as_mut_ptr())) }).and(Ok(buf))
}
fn get_string(&self, where_: i32, what: i32) -> Result<String> {
let mut buf = null();
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut *const i8 as *mut raw::c_void) })
.and(Ok(unsafe { util::from_c_str(buf) }))
}
fn check_apicall(&self, error: ffi::c_int) -> Result<()> {
if error!= 0 {
return Err(Error::FromAPI("Callback error".to_owned(), 40000));
}
Ok(())
}
}
impl<'a> Deref for Callback<'a> {
type Target = Model;
fn deref(&self) -> &Model { self.model }
}
| {
Where::Simplex {
itrcnt: try!(callback.get_double(SIMPLEX, SPX_ITRCNT)),
objval: try!(callback.get_double(SIMPLEX, SPX_OBJVAL)),
priminf: try!(callback.get_double(SIMPLEX, SPX_PRIMINF)),
dualinf: try!(callback.get_double(SIMPLEX, SPX_DUALINF)),
ispert: try!(callback.get_int(SIMPLEX, SPX_ISPERT))
}
} | conditional_block |
callback.rs | // Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.
use ffi;
use itertools::{Itertools, Zip};
use std::mem::transmute;
use std::ops::Deref;
use std::ptr::null;
use std::os::raw;
use error::{Error, Result};
use model::{Model, Var, ConstrSense};
use model::expr::LinExpr;
use util;
// Location where the callback called.
const POLLING: i32 = 0;
const PRESOLVE: i32 = 1;
const SIMPLEX: i32 = 2;
const MIP: i32 = 3;
const MIPSOL: i32 = 4;
const MIPNODE: i32 = 5;
const MESSAGE: i32 = 6;
const BARRIER: i32 = 7;
const PRE_COLDEL: i32 = 1000;
const PRE_ROWDEL: i32 = 1001;
const PRE_SENCHG: i32 = 1002;
const PRE_BNDCHG: i32 = 1003;
const PRE_COECHG: i32 = 1004;
const SPX_ITRCNT: i32 = 2000;
const SPX_OBJVAL: i32 = 2001;
const SPX_PRIMINF: i32 = 2002;
const SPX_DUALINF: i32 = 2003;
const SPX_ISPERT: i32 = 2004;
const MIP_OBJBST: i32 = 3000;
const MIP_OBJBND: i32 = 3001;
const MIP_NODCNT: i32 = 3002;
const MIP_SOLCNT: i32 = 3003;
const MIP_CUTCNT: i32 = 3004;
const MIP_NODLFT: i32 = 3005;
const MIP_ITRCNT: i32 = 3006;
#[allow(dead_code)]
const MIP_OBJBNDC: i32 = 3007;
const MIPSOL_SOL: i32 = 4001;
const MIPSOL_OBJ: i32 = 4002;
const MIPSOL_OBJBST: i32 = 4003;
const MIPSOL_OBJBND: i32 = 4004;
const MIPSOL_NODCNT: i32 = 4005;
const MIPSOL_SOLCNT: i32 = 4006;
#[allow(dead_code)]
const MIPSOL_OBJBNDC: i32 = 4007;
const MIPNODE_STATUS: i32 = 5001;
const MIPNODE_REL: i32 = 5002;
const MIPNODE_OBJBST: i32 = 5003;
const MIPNODE_OBJBND: i32 = 5004;
const MIPNODE_NODCNT: i32 = 5005;
const MIPNODE_SOLCNT: i32 = 5006;
#[allow(dead_code)]
const MIPNODE_BRVAR: i32 = 5007;
#[allow(dead_code)]
const MIPNODE_OBJBNDC: i32 = 5008;
const MSG_STRING: i32 = 6001;
const RUNTIME: i32 = 6002;
const BARRIER_ITRCNT: i32 = 7001;
const BARRIER_PRIMOBJ: i32 = 7002;
const BARRIER_DUALOBJ: i32 = 7003;
const BARRIER_PRIMINF: i32 = 7004;
const BARRIER_DUALINF: i32 = 7005;
const BARRIER_COMPL: i32 = 7006;
/// Location where the callback called
///
/// If you want to get more information, see [official
/// manual](https://www.gurobi.com/documentation/6.5/refman/callback_codes.html).
#[derive(Debug, Clone)]
pub enum Where {
/// Periodic polling callback
Polling,
/// Currently performing presolve
PreSolve {
/// The number of columns removed by presolve to this point.
coldel: i32,
/// The number of rows removed by presolve to this point.
rowdel: i32,
/// The number of constraint senses changed by presolve to this point.
senchg: i32,
/// The number of variable bounds changed by presolve to this point.
bndchg: i32,
/// The number of coefficients changed by presolve to this point.
coecfg: i32
},
/// Currently in simplex
Simplex {
/// Current simplex iteration count.
itrcnt: f64,
/// Current simplex objective value.
objval: f64,
/// Current primal infeasibility.
priminf: f64,
/// Current dual infeasibility.
dualinf: f64,
/// Is problem current perturbed?
ispert: i32
},
/// Currently in MIP
MIP {
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64,
/// Current count of cutting planes applied.
cutcnt: i32,
/// Current unexplored node count.
nodleft: f64,
/// Current simplex iteration count.
itrcnt: f64
},
/// Found a new MIP incumbent
MIPSol {
/// Objective value for new solution.
obj: f64,
/// Current best objective.
objbst: f64,
/// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64,
/// Current count of feasible solutions found.
solcnt: f64
},
/// Currently exploring a MIP node
MIPNode {
/// Optimization status of current MIP node (see the Status Code section for further information).
status: i32,
/// Current best objective.
objbst: f64, | /// Current count of feasible solutions found.
solcnt: i32
},
/// Printing a log message
Message(String),
/// Currently in barrier.
Barrier {
/// Current barrier iteration count.
itrcnt: i32,
/// Primal objective value for current barrier iterate.
primobj: f64,
/// Dual objective value for current barrier iterate.
dualobj: f64,
/// Primal infeasibility for current barrier iterate.
priminf: f64,
/// Dual infeasibility for current barrier iterate.
dualinf: f64,
/// Complementarity violation for current barrier iterate.
compl: f64
}
}
impl Into<i32> for Where {
fn into(self) -> i32 {
match self {
Where::Polling => POLLING,
Where::PreSolve {.. } => PRESOLVE,
Where::Simplex {.. } => SIMPLEX,
Where::MIP {.. } => MIP,
Where::MIPSol {.. } => MIPSOL,
Where::MIPNode {.. } => MIPNODE,
Where::Message(_) => MESSAGE,
Where::Barrier {.. } => BARRIER,
}
}
}
/// The context object for Gurobi callback.
pub struct Callback<'a> {
cbdata: *mut ffi::c_void,
where_: Where,
model: &'a Model
}
pub trait New<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>>;
}
impl<'a> New<'a> for Callback<'a> {
fn new(cbdata: *mut ffi::c_void, where_: i32, model: &'a Model) -> Result<Callback<'a>> {
let mut callback = Callback {
cbdata: cbdata,
where_: Where::Polling,
model: model
};
let where_ = match where_ {
POLLING => Where::Polling,
PRESOLVE => {
Where::PreSolve {
coldel: try!(callback.get_int(PRESOLVE, PRE_COLDEL)),
rowdel: try!(callback.get_int(PRESOLVE, PRE_ROWDEL)),
senchg: try!(callback.get_int(PRESOLVE, PRE_SENCHG)),
bndchg: try!(callback.get_int(PRESOLVE, PRE_BNDCHG)),
coecfg: try!(callback.get_int(PRESOLVE, PRE_COECHG))
}
}
SIMPLEX => {
Where::Simplex {
itrcnt: try!(callback.get_double(SIMPLEX, SPX_ITRCNT)),
objval: try!(callback.get_double(SIMPLEX, SPX_OBJVAL)),
priminf: try!(callback.get_double(SIMPLEX, SPX_PRIMINF)),
dualinf: try!(callback.get_double(SIMPLEX, SPX_DUALINF)),
ispert: try!(callback.get_int(SIMPLEX, SPX_ISPERT))
}
}
MIP => {
Where::MIP {
objbst: try!(callback.get_double(MIP, MIP_OBJBST)),
objbnd: try!(callback.get_double(MIP, MIP_OBJBND)),
nodcnt: try!(callback.get_double(MIP, MIP_NODCNT)),
solcnt: try!(callback.get_double(MIP, MIP_SOLCNT)),
cutcnt: try!(callback.get_int(MIP, MIP_CUTCNT)),
nodleft: try!(callback.get_double(MIP, MIP_NODLFT)),
itrcnt: try!(callback.get_double(MIP, MIP_ITRCNT))
}
}
MIPSOL => {
Where::MIPSol {
obj: try!(callback.get_double(MIPSOL, MIPSOL_OBJ)),
objbst: try!(callback.get_double(MIPSOL, MIPSOL_OBJBST)),
objbnd: try!(callback.get_double(MIPSOL, MIPSOL_OBJBND)),
nodcnt: try!(callback.get_double(MIPSOL, MIPSOL_NODCNT)),
solcnt: try!(callback.get_double(MIPSOL, MIPSOL_SOLCNT))
}
}
MIPNODE => {
Where::MIPNode {
status: try!(callback.get_int(MIPNODE, MIPNODE_STATUS)),
objbst: try!(callback.get_double(MIPNODE, MIPNODE_OBJBST)),
objbnd: try!(callback.get_double(MIPNODE, MIPNODE_OBJBND)),
nodcnt: try!(callback.get_double(MIPNODE, MIPNODE_NODCNT)),
solcnt: try!(callback.get_int(MIPNODE, MIPNODE_SOLCNT))
}
}
MESSAGE => Where::Message(try!(callback.get_string(MESSAGE, MSG_STRING)).trim().to_owned()),
BARRIER => {
Where::Barrier {
itrcnt: try!(callback.get_int(BARRIER, BARRIER_ITRCNT)),
primobj: try!(callback.get_double(BARRIER, BARRIER_PRIMOBJ)),
dualobj: try!(callback.get_double(BARRIER, BARRIER_DUALOBJ)),
priminf: try!(callback.get_double(BARRIER, BARRIER_PRIMINF)),
dualinf: try!(callback.get_double(BARRIER, BARRIER_DUALINF)),
compl: try!(callback.get_double(BARRIER, BARRIER_COMPL))
}
}
_ => panic!("Invalid callback location. {}", where_)
};
callback.where_ = where_;
Ok(callback)
}
}
impl<'a> Callback<'a> {
/// Retrieve the location where the callback called.
pub fn get_where(&self) -> Where { self.where_.clone() }
/// Retrive node relaxation solution values at the current node.
pub fn get_node_rel(&self, vars: &[Var]) -> Result<Vec<f64>> {
// memo: only MIPNode && status == Optimal
self.get_double_array(MIPNODE, MIPNODE_REL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Retrieve values from the current solution vector.
pub fn get_solution(&self, vars: &[Var]) -> Result<Vec<f64>> {
self.get_double_array(MIPSOL, MIPSOL_SOL).map(|buf| vars.iter().map(|v| buf[v.index() as usize]).collect_vec())
}
/// Provide a new feasible solution for a MIP model.
pub fn set_solution(&self, vars: &[Var], solution: &[f64]) -> Result<()> {
if vars.len()!= solution.len() || vars.len() < self.model.vars.len() {
return Err(Error::InconsitentDims);
}
let mut buf = vec![0.0; self.model.vars.len()];
for (v, &sol) in Zip::new((vars.iter(), solution.iter())) {
let i = v.index() as usize;
buf[i] = sol;
}
self.check_apicall(unsafe { ffi::GRBcbsolution(self.cbdata, buf.as_ptr()) })
}
/// Retrieve the elapsed solver runtime [sec].
pub fn get_runtime(&self) -> Result<f64> {
if let Where::Polling = self.get_where() {
return Err(Error::FromAPI("bad call in callback".to_owned(), 40001));
}
self.get_double(self.get_where().into(), RUNTIME)
}
/// Add a new cutting plane to the MIP model.
pub fn add_cut(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcbcut(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
/// Add a new lazy constraint to the MIP model.
pub fn add_lazy(&self, lhs: LinExpr, sense: ConstrSense, rhs: f64) -> Result<()> {
let (vars, coeff, offset) = lhs.into();
self.check_apicall(unsafe {
ffi::GRBcblazy(self.cbdata,
coeff.len() as ffi::c_int,
vars.as_ptr(),
coeff.as_ptr(),
sense.into(),
rhs - offset)
})
}
fn get_int(&self, where_: i32, what: i32) -> Result<i32> {
let mut buf = 0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut i32 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double(&self, where_: i32, what: i32) -> Result<f64> {
let mut buf = 0.0;
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut f64 as *mut raw::c_void) }).and(Ok(buf.into()))
}
fn get_double_array(&self, where_: i32, what: i32) -> Result<Vec<f64>> {
let mut buf = vec![0.0; self.model.vars.len()];
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, transmute(buf.as_mut_ptr())) }).and(Ok(buf))
}
fn get_string(&self, where_: i32, what: i32) -> Result<String> {
let mut buf = null();
self.check_apicall(unsafe { ffi::GRBcbget(self.cbdata, where_, what, &mut buf as *mut *const i8 as *mut raw::c_void) })
.and(Ok(unsafe { util::from_c_str(buf) }))
}
fn check_apicall(&self, error: ffi::c_int) -> Result<()> {
if error!= 0 {
return Err(Error::FromAPI("Callback error".to_owned(), 40000));
}
Ok(())
}
}
impl<'a> Deref for Callback<'a> {
type Target = Model;
fn deref(&self) -> &Model { self.model }
} | /// Current best objective bound.
objbnd: f64,
/// Current explored node count.
nodcnt: f64, | random_line_split |
function.rs | use object::values::Value;
use object::string::InString;
use vm::opcode::Instruction;
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct LocVar {
varname: InString,
startpc: u32, // first point where variable is active
endpc: u32 // first point where variable is dead
}
// Masks for vararg
pub const HASARG : u8 = 1;
pub const ISVARARG: u8 = 2;
pub const NEEDSARG: u8 = 4;
/// Function prototypes
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct Proto {
k: Vec<Value>, // constants used by the function
code: Vec<Instruction>,
p: Vec<Proto>, // functions defined inside the function
lineinfo: Vec<u32>, // map from instructions to source lines
locvars: Vec<LocVar>, // information about local variables
upvalues: Vec<InString>, // upvalue names
source: InString, // source code for this function
linedefined: u32,
lastlinedefined: u32,
//TODO: gclist?
nups: u8, // number of upvalues
numparams: u8,
is_vararg: u8, // OR'd values of HASARG, ISVARARG, NEEDSARG
maxstacksize: u8
}
impl LocVar {
pub fn new(varname: InString, startpc: u32, endpc: u32) -> LocVar
{
LocVar {
varname: varname,
startpc: startpc,
endpc: endpc
}
}
}
impl Proto {
pub fn new(source: InString,
linedefined: u32,
lastlinedefined: u32,
nups: u8,
numparams: u8,
is_vararg: u8,
maxstacksize: u8)
-> Proto {
Proto {
| code: Vec::new(),
p: Vec::new(),
lineinfo: Vec::new(),
locvars: Vec::new(),
upvalues: Vec::new(),
source: source,
linedefined: linedefined,
lastlinedefined: lastlinedefined,
nups: nups,
numparams: numparams,
is_vararg: is_vararg,
maxstacksize: maxstacksize
}
}
} | k: Vec::new(),
| random_line_split |
function.rs | use object::values::Value;
use object::string::InString;
use vm::opcode::Instruction;
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct LocVar {
varname: InString,
startpc: u32, // first point where variable is active
endpc: u32 // first point where variable is dead
}
// Masks for vararg
pub const HASARG : u8 = 1;
pub const ISVARARG: u8 = 2;
pub const NEEDSARG: u8 = 4;
/// Function prototypes
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct Proto {
k: Vec<Value>, // constants used by the function
code: Vec<Instruction>,
p: Vec<Proto>, // functions defined inside the function
lineinfo: Vec<u32>, // map from instructions to source lines
locvars: Vec<LocVar>, // information about local variables
upvalues: Vec<InString>, // upvalue names
source: InString, // source code for this function
linedefined: u32,
lastlinedefined: u32,
//TODO: gclist?
nups: u8, // number of upvalues
numparams: u8,
is_vararg: u8, // OR'd values of HASARG, ISVARARG, NEEDSARG
maxstacksize: u8
}
impl LocVar {
pub fn new(varname: InString, startpc: u32, endpc: u32) -> LocVar
|
}
impl Proto {
pub fn new(source: InString,
linedefined: u32,
lastlinedefined: u32,
nups: u8,
numparams: u8,
is_vararg: u8,
maxstacksize: u8)
-> Proto {
Proto {
k: Vec::new(),
code: Vec::new(),
p: Vec::new(),
lineinfo: Vec::new(),
locvars: Vec::new(),
upvalues: Vec::new(),
source: source,
linedefined: linedefined,
lastlinedefined: lastlinedefined,
nups: nups,
numparams: numparams,
is_vararg: is_vararg,
maxstacksize: maxstacksize
}
}
}
| {
LocVar {
varname: varname,
startpc: startpc,
endpc: endpc
}
} | identifier_body |
function.rs | use object::values::Value;
use object::string::InString;
use vm::opcode::Instruction;
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct LocVar {
varname: InString,
startpc: u32, // first point where variable is active
endpc: u32 // first point where variable is dead
}
// Masks for vararg
pub const HASARG : u8 = 1;
pub const ISVARARG: u8 = 2;
pub const NEEDSARG: u8 = 4;
/// Function prototypes
#[derive(PartialEq,Eq,Hash,Debug,Clone)]
pub struct Proto {
k: Vec<Value>, // constants used by the function
code: Vec<Instruction>,
p: Vec<Proto>, // functions defined inside the function
lineinfo: Vec<u32>, // map from instructions to source lines
locvars: Vec<LocVar>, // information about local variables
upvalues: Vec<InString>, // upvalue names
source: InString, // source code for this function
linedefined: u32,
lastlinedefined: u32,
//TODO: gclist?
nups: u8, // number of upvalues
numparams: u8,
is_vararg: u8, // OR'd values of HASARG, ISVARARG, NEEDSARG
maxstacksize: u8
}
impl LocVar {
pub fn new(varname: InString, startpc: u32, endpc: u32) -> LocVar
{
LocVar {
varname: varname,
startpc: startpc,
endpc: endpc
}
}
}
impl Proto {
pub fn | (source: InString,
linedefined: u32,
lastlinedefined: u32,
nups: u8,
numparams: u8,
is_vararg: u8,
maxstacksize: u8)
-> Proto {
Proto {
k: Vec::new(),
code: Vec::new(),
p: Vec::new(),
lineinfo: Vec::new(),
locvars: Vec::new(),
upvalues: Vec::new(),
source: source,
linedefined: linedefined,
lastlinedefined: lastlinedefined,
nups: nups,
numparams: numparams,
is_vararg: is_vararg,
maxstacksize: maxstacksize
}
}
}
| new | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
extern crate aster;
extern crate quasi;
#[cfg(feature = "with-syntex")]
extern crate syntex;
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
#[cfg(not(feature = "with-syntex"))]
use syntax::feature_gate::AttributeType;
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in");
#[cfg(feature = "with-syntex")]
pub fn register(reg: &mut syntex::Registry) {
use syntax::{ast, fold};
/// Strip the serde attributes from the crate.
#[cfg(feature = "with-syntex")]
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
/// Helper folder that strips the serde attributes after the extensions have been expanded.
struct StripAttributeFolder;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
_ => {}
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
} | reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Deserialize"),
syntax::ext::base::MultiDecorator(
Box::new(de::expand_derive_deserialize)));
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
} |
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("feature(custom_derive)"); | random_line_split |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
extern crate aster;
extern crate quasi;
#[cfg(feature = "with-syntex")]
extern crate syntex;
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
#[cfg(not(feature = "with-syntex"))]
use syntax::feature_gate::AttributeType;
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in");
#[cfg(feature = "with-syntex")]
pub fn register(reg: &mut syntex::Registry) | fold::noop_fold_mac(mac, self)
}
}
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("feature(custom_derive)");
reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Deserialize"),
syntax::ext::base::MultiDecorator(
Box::new(de::expand_derive_deserialize)));
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
}
| {
use syntax::{ast, fold};
/// Strip the serde attributes from the crate.
#[cfg(feature = "with-syntex")]
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
/// Helper folder that strips the serde attributes after the extensions have been expanded.
struct StripAttributeFolder;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
_ => {}
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { | identifier_body |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
extern crate aster;
extern crate quasi;
#[cfg(feature = "with-syntex")]
extern crate syntex;
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
#[cfg(not(feature = "with-syntex"))]
use syntax::feature_gate::AttributeType;
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in");
#[cfg(feature = "with-syntex")]
pub fn register(reg: &mut syntex::Registry) {
use syntax::{ast, fold};
/// Strip the serde attributes from the crate.
#[cfg(feature = "with-syntex")]
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
/// Helper folder that strips the serde attributes after the extensions have been expanded.
struct StripAttributeFolder;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => |
_ => {}
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("feature(custom_derive)");
reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Deserialize"),
syntax::ext::base::MultiDecorator(
Box::new(de::expand_derive_deserialize)));
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
}
| { return None; } | conditional_block |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi_macros))]
extern crate aster;
extern crate quasi;
#[cfg(feature = "with-syntex")]
extern crate syntex;
#[cfg(feature = "with-syntex")]
#[macro_use]
extern crate syntex_syntax as syntax;
#[cfg(not(feature = "with-syntex"))]
#[macro_use]
extern crate syntax;
#[cfg(not(feature = "with-syntex"))]
extern crate rustc_plugin;
#[cfg(not(feature = "with-syntex"))]
use syntax::feature_gate::AttributeType;
#[cfg(feature = "with-syntex")]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "with-syntex"))]
include!("lib.rs.in");
#[cfg(feature = "with-syntex")]
pub fn register(reg: &mut syntex::Registry) {
use syntax::{ast, fold};
/// Strip the serde attributes from the crate.
#[cfg(feature = "with-syntex")]
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
/// Helper folder that strips the serde attributes after the extensions have been expanded.
struct | ;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
_ => {}
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("feature(custom_derive)");
reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Deserialize"),
syntax::ext::base::MultiDecorator(
Box::new(de::expand_derive_deserialize)));
reg.register_attribute("serde".to_owned(), AttributeType::Normal);
}
| StripAttributeFolder | identifier_name |
clients.rs | // Learn stuff about our users.
+ my name is *
- <set name=<formal>>Nice to meet you, <get name>.
- <set name=<formal>><get name>, nice to meet you.
+ my name is <bot master>
- <set name=<bot master>>That's my master's name too.
+ my name is <bot name>
- <set name=<bot name>>What a coincidence! That's my name too!
- <set name=<bot name>>That's my name too!
+ call me *
- <set name=<formal>><get name>, I will call you that from now on.
+ i am * years old
- <set age=<star>>A lot of people are <get age>, you're not alone.
- <set age=<star>>Cool, I'm <bot age> myself.{weight=49}
+ i am a (@malenoun)
- <set sex=male>Alright, you're a <star>.
+ i am a (@femalenoun)
- <set sex=female>Alright, you're female.
+ i (am from|live in) *
- <set location=<formal>>I've spoken to people from <get location> before.
|
+ i have a girlfriend
- <set status=girlfriend>What's her name?
+ i have a boyfriend
- <set status=boyfriend>What's his name?
+ *
% whats her name
- <set spouse=<formal>>That's a pretty name.
+ *
% whats his name
- <set spouse=<formal>>That's a cool name.
+ my (girlfriend|boyfriend)* name is *
- <set spouse=<formal>>That's a nice name.
+ (what is my name|who am i|do you know my name|do you know who i am){weight=10}
- Your name is <get name>.
- You told me your name is <get name>.
- Aren't you <get name>?
+ (how old am i|do you know how old i am|do you know my age){weight=10}
- You are <get age> years old.
- You're <get age>.
+ am i a (@malenoun) or a (@femalenoun){weight=10}
- You're a <get sex>.
+ am i (@malenoun) or (@femalenoun){weight=10}
- You're a <get sex>.
+ what is my favorite *{weight=10}
- Your favorite <star> is <get fav<star>>
+ who is my (boyfriend|girlfriend|spouse){weight=10}
- <get spouse> | + my favorite * is *
- <set fav<star1>=<star2>>Why is it your favorite?
+ i am single
- <set status=single><set spouse=nobody>I am too. | random_line_split |
mod_dir_path.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.
// run-pass
#![allow(unused_macros)]
// ignore-pretty issue #37195
mod mod_dir_simple {
#[path = "test.rs"]
pub mod syrup;
}
pub fn main() | {
assert_eq!(mod_dir_simple::syrup::foo(), 10);
#[path = "auxiliary"]
mod foo {
mod two_macros_2;
}
#[path = "auxiliary"]
mod bar {
macro_rules! m { () => { mod two_macros_2; } }
m!();
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.