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 |
---|---|---|---|---|
blink_ops.rs
|
/* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use algorithm;
use node::{Node, Leaf, INode};
use blinktree::physical_node::{PhysicalNode, T_LEAF, T_INODE};
#[deriving(Clone)]
pub enum Movement {
Right,
Down,
}
pub trait BLinkOps<K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>> {
fn move_right<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<&'a Ptr> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if! can_contain {
node.link_ptr()
} else {
None
}
}
fn get_value<'a>(&self, leaf: &'a LEAF, key: &K) -> Option<&'a V> {
if!self.can_contain_key(leaf,key) {
return None;
}
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), key);
debug!("[get] ptr: {}, keys: {} values: {}, key: {}, idx: {}",
leaf.my_ptr().to_str(), leaf.keys().to_str(),
leaf.values().to_str(), key.to_str(), idx.to_str());
if leaf.keys()[idx].cmp(key) == Equal {
Some(&leaf.values()[idx])
} else {
None
}
}
fn get_ptr<'a>(&self, inode: &'a INODE, key: &K) -> Option<&'a Ptr> {
if!self.can_contain_key(inode,key) {
return None;
}
let idx = algorithm::bsearch_idx(inode.keys().slice_from(0), key);
debug!("[get_ptr] key: {}, ptr: {}, keys: {} values: {}, idx: {}, is_most_right_node: {}, is_root: {}",
key.to_str(), inode.my_ptr().to_str(), inode.keys().to_str(),
inode.values().to_str(), idx.to_str(), inode.is_most_right_node(), inode.is_root());
Some(&inode.values()[idx])
}
fn scannode<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<(&'a Ptr, Movement)> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if(! can_contain) {
return node.link_ptr().map(|r| (r, Right));
}
match node {
&Leaf(*) => None,
&INode(ref inode) =>
self.get_ptr(inode, key).map(|r| (r, Down))
}
}
fn split_and_insert_leaf(&self, leaf: &mut LEAF, new_page: Ptr, key: K, value: V) -> LEAF {
let new_size = leaf.keys().len()/2;
self.insert_leaf(leaf, key, value);
let (keys_new, values_new) = leaf.split_at(new_size);
let link_ptr = leaf.set_link_ptr(new_page.clone());
PhysicalNode::new(T_LEAF, new_page, link_ptr, keys_new, values_new)
}
/// Default splitting strategy:
///
/// example max_size = 4:
/// split
/// |
/// |<= 3 <|<= 5 <|<= 10 <|<= 15 <|<= 30
/// . . . . .
///
fn split_and_insert_inode(&self, inode: &mut INODE, new_page: Ptr, key: K, value: Ptr) -> INODE {
let new_size = inode.keys().len()/2;
self.insert_inode(inode, key, value);
let (keys_new, values_new) = inode.split_at(new_size);
debug!("[split_and_insert_inode] keys.len: {}, value.len: {}", keys_new.to_str(), values_new.to_str());
let link_ptr = inode.set_link_ptr(new_page.clone());
PhysicalNode::new(T_INODE, new_page, link_ptr, keys_new, values_new)
}
fn insert_leaf(&self, leaf: &mut LEAF, key: K, value: V) {
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), &key);
leaf.mut_keys().insert(idx, key);
leaf.mut_values().insert(idx, value);
}
fn insert_inode(&self, inode: &mut INODE, key: K, value: Ptr) {
let mut idx = algorithm::bsearch_idx(inode.keys().slice_from(0), &key);
inode.mut_keys().insert(idx, key);
//if (inode.is_root() || inode.is_most_right_node()) {
idx += 1;
//}
inode.mut_values().insert(idx, value);
}
fn can_contain_key<
K1: TotalOrd,
V1,
Ptr1,
N : PhysicalNode<K1,V1,Ptr1>>(&self, node: &N, key: &K1) -> bool {
node.is_root()
|| (node.is_most_right_node() && key.cmp(node.max_key()) == Greater)
|| (key.cmp(node.max_key()) == Less ||
key.cmp(node.max_key()) == Equal)
}
}
pub struct DefaultBLinkOps<K,V,Ptr, INODE, LEAF>;
impl <K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>
>
BLinkOps<K,V,Ptr,INODE, LEAF> for DefaultBLinkOps<K,V,Ptr, INODE, LEAF> {}
#[cfg(test)]
mod test {
use super::{BLinkOps, DefaultBLinkOps};
use blinktree::physical_node::{PhysicalNode, DefaultBLinkNode, T_ROOT, T_LEAF};
macro_rules! can_contains_range(
($node:ident, $from:expr, $to:expr) => (
for i in range($from, $to+1) {
assert!(self.can_contain_key(&$node, &i),
format!("cannot contain key {}, is_root: {}, is_leaf: {}, is_inode: {}",
i, $node.is_root(), $node.is_leaf(), $node.is_inode()));
}
)
)
trait BLinkOpsTest<INODE: PhysicalNode<uint, uint, uint>,
LEAF: PhysicalNode<uint, uint, uint>>
: BLinkOps<uint,uint,uint,INODE,LEAF> {
fn test(&self) {
self.test_can_contain_key();
self.test_needs_split();
self.test_insert_into_inode_ptr_must_be_off_by_one();
}
fn
|
(&self) {
let tpe = T_ROOT ^ T_LEAF;
let root : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(tpe, 0u, None, ~[2u],~[0u,1u]);
can_contains_range!(root, 0u, 10);
assert!(self.can_contain_key(&root, &10000));
let leaf : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(T_LEAF, 0u, None, ~[2u,4],~[0,1]);
can_contains_range!(leaf, 0u, 4);
}
fn test_needs_split(&self) {
}
// ionde otherwise
// keys: . 4. 1 | 2 | 3
// values: 1 3 10 1 4
fn test_insert_into_inode_ptr_must_be_off_by_one(&self) {
let mut inode: INODE = PhysicalNode::new(T_ROOT & T_LEAF, 0u, None, ~[1],~[0,1]);
self.insert_inode(&mut inode, 4, 4);
self.insert_inode(&mut inode, 3, 3);
let expected = ~[0,1,3,4];
assert!(inode.values() == &expected,
format!("expected: {}, got {}", expected.to_str(), inode.values().to_str()))
}
}
impl BLinkOpsTest<DefaultBLinkNode<uint, uint, uint>,
DefaultBLinkNode<uint, uint, uint>>
for DefaultBLinkOps<uint,uint,uint,
DefaultBLinkNode<uint,uint,uint>,
DefaultBLinkNode<uint, uint, uint>> {}
#[test]
fn test_default_blink_ops() {
let ops = DefaultBLinkOps;
ops.test();
}
}
|
test_can_contain_key
|
identifier_name
|
blink_ops.rs
|
/* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use algorithm;
use node::{Node, Leaf, INode};
use blinktree::physical_node::{PhysicalNode, T_LEAF, T_INODE};
#[deriving(Clone)]
pub enum Movement {
Right,
Down,
}
pub trait BLinkOps<K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>> {
fn move_right<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<&'a Ptr> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if! can_contain {
node.link_ptr()
} else {
None
}
}
fn get_value<'a>(&self, leaf: &'a LEAF, key: &K) -> Option<&'a V> {
if!self.can_contain_key(leaf,key) {
return None;
}
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), key);
debug!("[get] ptr: {}, keys: {} values: {}, key: {}, idx: {}",
leaf.my_ptr().to_str(), leaf.keys().to_str(),
leaf.values().to_str(), key.to_str(), idx.to_str());
if leaf.keys()[idx].cmp(key) == Equal {
Some(&leaf.values()[idx])
} else {
None
}
}
fn get_ptr<'a>(&self, inode: &'a INODE, key: &K) -> Option<&'a Ptr>
|
fn scannode<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<(&'a Ptr, Movement)> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if(! can_contain) {
return node.link_ptr().map(|r| (r, Right));
}
match node {
&Leaf(*) => None,
&INode(ref inode) =>
self.get_ptr(inode, key).map(|r| (r, Down))
}
}
fn split_and_insert_leaf(&self, leaf: &mut LEAF, new_page: Ptr, key: K, value: V) -> LEAF {
let new_size = leaf.keys().len()/2;
self.insert_leaf(leaf, key, value);
let (keys_new, values_new) = leaf.split_at(new_size);
let link_ptr = leaf.set_link_ptr(new_page.clone());
PhysicalNode::new(T_LEAF, new_page, link_ptr, keys_new, values_new)
}
/// Default splitting strategy:
///
/// example max_size = 4:
/// split
/// |
/// |<= 3 <|<= 5 <|<= 10 <|<= 15 <|<= 30
/// . . . . .
///
fn split_and_insert_inode(&self, inode: &mut INODE, new_page: Ptr, key: K, value: Ptr) -> INODE {
let new_size = inode.keys().len()/2;
self.insert_inode(inode, key, value);
let (keys_new, values_new) = inode.split_at(new_size);
debug!("[split_and_insert_inode] keys.len: {}, value.len: {}", keys_new.to_str(), values_new.to_str());
let link_ptr = inode.set_link_ptr(new_page.clone());
PhysicalNode::new(T_INODE, new_page, link_ptr, keys_new, values_new)
}
fn insert_leaf(&self, leaf: &mut LEAF, key: K, value: V) {
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), &key);
leaf.mut_keys().insert(idx, key);
leaf.mut_values().insert(idx, value);
}
fn insert_inode(&self, inode: &mut INODE, key: K, value: Ptr) {
let mut idx = algorithm::bsearch_idx(inode.keys().slice_from(0), &key);
inode.mut_keys().insert(idx, key);
//if (inode.is_root() || inode.is_most_right_node()) {
idx += 1;
//}
inode.mut_values().insert(idx, value);
}
fn can_contain_key<
K1: TotalOrd,
V1,
Ptr1,
N : PhysicalNode<K1,V1,Ptr1>>(&self, node: &N, key: &K1) -> bool {
node.is_root()
|| (node.is_most_right_node() && key.cmp(node.max_key()) == Greater)
|| (key.cmp(node.max_key()) == Less ||
key.cmp(node.max_key()) == Equal)
}
}
pub struct DefaultBLinkOps<K,V,Ptr, INODE, LEAF>;
impl <K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>
>
BLinkOps<K,V,Ptr,INODE, LEAF> for DefaultBLinkOps<K,V,Ptr, INODE, LEAF> {}
#[cfg(test)]
mod test {
use super::{BLinkOps, DefaultBLinkOps};
use blinktree::physical_node::{PhysicalNode, DefaultBLinkNode, T_ROOT, T_LEAF};
macro_rules! can_contains_range(
($node:ident, $from:expr, $to:expr) => (
for i in range($from, $to+1) {
assert!(self.can_contain_key(&$node, &i),
format!("cannot contain key {}, is_root: {}, is_leaf: {}, is_inode: {}",
i, $node.is_root(), $node.is_leaf(), $node.is_inode()));
}
)
)
trait BLinkOpsTest<INODE: PhysicalNode<uint, uint, uint>,
LEAF: PhysicalNode<uint, uint, uint>>
: BLinkOps<uint,uint,uint,INODE,LEAF> {
fn test(&self) {
self.test_can_contain_key();
self.test_needs_split();
self.test_insert_into_inode_ptr_must_be_off_by_one();
}
fn test_can_contain_key(&self) {
let tpe = T_ROOT ^ T_LEAF;
let root : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(tpe, 0u, None, ~[2u],~[0u,1u]);
can_contains_range!(root, 0u, 10);
assert!(self.can_contain_key(&root, &10000));
let leaf : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(T_LEAF, 0u, None, ~[2u,4],~[0,1]);
can_contains_range!(leaf, 0u, 4);
}
fn test_needs_split(&self) {
}
// ionde otherwise
// keys: . 4. 1 | 2 | 3
// values: 1 3 10 1 4
fn test_insert_into_inode_ptr_must_be_off_by_one(&self) {
let mut inode: INODE = PhysicalNode::new(T_ROOT & T_LEAF, 0u, None, ~[1],~[0,1]);
self.insert_inode(&mut inode, 4, 4);
self.insert_inode(&mut inode, 3, 3);
let expected = ~[0,1,3,4];
assert!(inode.values() == &expected,
format!("expected: {}, got {}", expected.to_str(), inode.values().to_str()))
}
}
impl BLinkOpsTest<DefaultBLinkNode<uint, uint, uint>,
DefaultBLinkNode<uint, uint, uint>>
for DefaultBLinkOps<uint,uint,uint,
DefaultBLinkNode<uint,uint,uint>,
DefaultBLinkNode<uint, uint, uint>> {}
#[test]
fn test_default_blink_ops() {
let ops = DefaultBLinkOps;
ops.test();
}
}
|
{
if !self.can_contain_key(inode,key) {
return None;
}
let idx = algorithm::bsearch_idx(inode.keys().slice_from(0), key);
debug!("[get_ptr] key: {}, ptr: {}, keys: {} values: {}, idx: {}, is_most_right_node: {}, is_root: {}",
key.to_str(), inode.my_ptr().to_str(), inode.keys().to_str(),
inode.values().to_str(), idx.to_str(), inode.is_most_right_node(), inode.is_root());
Some(&inode.values()[idx])
}
|
identifier_body
|
blink_ops.rs
|
/* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use algorithm;
use node::{Node, Leaf, INode};
use blinktree::physical_node::{PhysicalNode, T_LEAF, T_INODE};
#[deriving(Clone)]
pub enum Movement {
Right,
Down,
}
pub trait BLinkOps<K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>> {
fn move_right<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<&'a Ptr> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if! can_contain {
node.link_ptr()
} else {
None
}
}
fn get_value<'a>(&self, leaf: &'a LEAF, key: &K) -> Option<&'a V> {
if!self.can_contain_key(leaf,key) {
return None;
}
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), key);
debug!("[get] ptr: {}, keys: {} values: {}, key: {}, idx: {}",
leaf.my_ptr().to_str(), leaf.keys().to_str(),
leaf.values().to_str(), key.to_str(), idx.to_str());
if leaf.keys()[idx].cmp(key) == Equal {
Some(&leaf.values()[idx])
} else
|
}
fn get_ptr<'a>(&self, inode: &'a INODE, key: &K) -> Option<&'a Ptr> {
if!self.can_contain_key(inode,key) {
return None;
}
let idx = algorithm::bsearch_idx(inode.keys().slice_from(0), key);
debug!("[get_ptr] key: {}, ptr: {}, keys: {} values: {}, idx: {}, is_most_right_node: {}, is_root: {}",
key.to_str(), inode.my_ptr().to_str(), inode.keys().to_str(),
inode.values().to_str(), idx.to_str(), inode.is_most_right_node(), inode.is_root());
Some(&inode.values()[idx])
}
fn scannode<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<(&'a Ptr, Movement)> {
let can_contain = match node {
&Leaf(ref leaf) => self.can_contain_key(leaf, key),
&INode(ref inode) => self.can_contain_key(inode, key)
};
if(! can_contain) {
return node.link_ptr().map(|r| (r, Right));
}
match node {
&Leaf(*) => None,
&INode(ref inode) =>
self.get_ptr(inode, key).map(|r| (r, Down))
}
}
fn split_and_insert_leaf(&self, leaf: &mut LEAF, new_page: Ptr, key: K, value: V) -> LEAF {
let new_size = leaf.keys().len()/2;
self.insert_leaf(leaf, key, value);
let (keys_new, values_new) = leaf.split_at(new_size);
let link_ptr = leaf.set_link_ptr(new_page.clone());
PhysicalNode::new(T_LEAF, new_page, link_ptr, keys_new, values_new)
}
/// Default splitting strategy:
///
/// example max_size = 4:
/// split
/// |
/// |<= 3 <|<= 5 <|<= 10 <|<= 15 <|<= 30
/// . . . . .
///
fn split_and_insert_inode(&self, inode: &mut INODE, new_page: Ptr, key: K, value: Ptr) -> INODE {
let new_size = inode.keys().len()/2;
self.insert_inode(inode, key, value);
let (keys_new, values_new) = inode.split_at(new_size);
debug!("[split_and_insert_inode] keys.len: {}, value.len: {}", keys_new.to_str(), values_new.to_str());
let link_ptr = inode.set_link_ptr(new_page.clone());
PhysicalNode::new(T_INODE, new_page, link_ptr, keys_new, values_new)
}
fn insert_leaf(&self, leaf: &mut LEAF, key: K, value: V) {
let idx = algorithm::bsearch_idx(leaf.keys().slice_from(0), &key);
leaf.mut_keys().insert(idx, key);
leaf.mut_values().insert(idx, value);
}
fn insert_inode(&self, inode: &mut INODE, key: K, value: Ptr) {
let mut idx = algorithm::bsearch_idx(inode.keys().slice_from(0), &key);
inode.mut_keys().insert(idx, key);
//if (inode.is_root() || inode.is_most_right_node()) {
idx += 1;
//}
inode.mut_values().insert(idx, value);
}
fn can_contain_key<
K1: TotalOrd,
V1,
Ptr1,
N : PhysicalNode<K1,V1,Ptr1>>(&self, node: &N, key: &K1) -> bool {
node.is_root()
|| (node.is_most_right_node() && key.cmp(node.max_key()) == Greater)
|| (key.cmp(node.max_key()) == Less ||
key.cmp(node.max_key()) == Equal)
}
}
pub struct DefaultBLinkOps<K,V,Ptr, INODE, LEAF>;
impl <K: TotalOrd + ToStr,
V: ToStr,
Ptr: Clone + ToStr,
INODE: PhysicalNode<K,Ptr,Ptr>,
LEAF: PhysicalNode<K,V,Ptr>
>
BLinkOps<K,V,Ptr,INODE, LEAF> for DefaultBLinkOps<K,V,Ptr, INODE, LEAF> {}
#[cfg(test)]
mod test {
use super::{BLinkOps, DefaultBLinkOps};
use blinktree::physical_node::{PhysicalNode, DefaultBLinkNode, T_ROOT, T_LEAF};
macro_rules! can_contains_range(
($node:ident, $from:expr, $to:expr) => (
for i in range($from, $to+1) {
assert!(self.can_contain_key(&$node, &i),
format!("cannot contain key {}, is_root: {}, is_leaf: {}, is_inode: {}",
i, $node.is_root(), $node.is_leaf(), $node.is_inode()));
}
)
)
trait BLinkOpsTest<INODE: PhysicalNode<uint, uint, uint>,
LEAF: PhysicalNode<uint, uint, uint>>
: BLinkOps<uint,uint,uint,INODE,LEAF> {
fn test(&self) {
self.test_can_contain_key();
self.test_needs_split();
self.test_insert_into_inode_ptr_must_be_off_by_one();
}
fn test_can_contain_key(&self) {
let tpe = T_ROOT ^ T_LEAF;
let root : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(tpe, 0u, None, ~[2u],~[0u,1u]);
can_contains_range!(root, 0u, 10);
assert!(self.can_contain_key(&root, &10000));
let leaf : DefaultBLinkNode<uint, uint, uint> =
PhysicalNode::new(T_LEAF, 0u, None, ~[2u,4],~[0,1]);
can_contains_range!(leaf, 0u, 4);
}
fn test_needs_split(&self) {
}
// ionde otherwise
// keys: . 4. 1 | 2 | 3
// values: 1 3 10 1 4
fn test_insert_into_inode_ptr_must_be_off_by_one(&self) {
let mut inode: INODE = PhysicalNode::new(T_ROOT & T_LEAF, 0u, None, ~[1],~[0,1]);
self.insert_inode(&mut inode, 4, 4);
self.insert_inode(&mut inode, 3, 3);
let expected = ~[0,1,3,4];
assert!(inode.values() == &expected,
format!("expected: {}, got {}", expected.to_str(), inode.values().to_str()))
}
}
impl BLinkOpsTest<DefaultBLinkNode<uint, uint, uint>,
DefaultBLinkNode<uint, uint, uint>>
for DefaultBLinkOps<uint,uint,uint,
DefaultBLinkNode<uint,uint,uint>,
DefaultBLinkNode<uint, uint, uint>> {}
#[test]
fn test_default_blink_ops() {
let ops = DefaultBLinkOps;
ops.test();
}
}
|
{
None
}
|
conditional_block
|
connection.rs
|
use proto;
use byteorder::{BigEndian, WriteBytesExt};
use std;
use std::net::{IpAddr, TcpStream};
use std::sync::Mutex;
use openssl;
use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream};
use protobuf;
// Connect
const SSL_HANDSHAKE_RETRIES: u8 = 3;
#[derive(Debug)]
pub enum ConnectionError {
ExceededHandshakeRetries(&'static str),
Ssl(openssl::ssl::Error),
TcpStream(std::io::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for ConnectionError {
fn from(e: openssl::ssl::Error) -> Self {
ConnectionError::Ssl(e)
}
}
impl From<openssl::error::ErrorStack> for ConnectionError {
fn from(e: openssl::error::ErrorStack) -> Self {
ConnectionError::Ssl(openssl::ssl::Error::from(e))
}
}
impl From<std::io::Error> for ConnectionError {
fn from(e: std::io::Error) -> Self
|
}
#[derive(Debug)]
pub enum SendError {
MessageTooLarge(&'static str),
Ssl(openssl::ssl::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for SendError {
fn from(e: openssl::ssl::Error) -> Self {
SendError::Ssl(e)
}
}
pub struct Connection {
control_channel: Mutex<SslStream<TcpStream>>
}
impl Connection {
pub fn new(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<Connection, ConnectionError> {
let stream = try!(Connection::connect(host, port, verify, nodelay));
Ok(Connection { control_channel: Mutex::new(stream) })
}
fn connect(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<SslStream<TcpStream>, ConnectionError> {
let mut context = try!(SslContext::new(SslMethod::Tlsv1));
if verify {
context.set_verify(openssl::ssl::SSL_VERIFY_PEER);
} else {
context.set_verify(openssl::ssl::SSL_VERIFY_NONE);
}
let stream = try!(TcpStream::connect((host, port)));
// I don't know how this can fail, so just unwrapping for now...
// TODO: figure this out
stream.set_nodelay(nodelay).unwrap();
match SslStream::connect(&context, stream) {
Ok(val) => Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(interrupted_stream) => {
let mut ssl_stream = interrupted_stream;
let mut tries: u8 = 1;
while tries < SSL_HANDSHAKE_RETRIES {
match ssl_stream.handshake() {
Ok(val) => return Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => return Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(new_interrupted_stream) => {
ssl_stream = new_interrupted_stream;
tries += 1;
continue
}
}
}
}
Err(ConnectionError::ExceededHandshakeRetries("Exceeded number of handshake retries"))
}
}
}
}
pub fn version_exchange(&self, version: u32, release: String, os: String, os_version: String) -> Result<usize, SendError> {
let mut version_message = proto::Version::new();
version_message.set_version(version);
version_message.set_release(release);
version_message.set_os(os);
version_message.set_os_version(os_version);
self.send_message(0, version_message)
}
// TODO: authentication with tokens
pub fn authenticate(&self, username: String, password: String) -> Result<usize, SendError> {
let mut auth_message = proto::Authenticate::new();
auth_message.set_username(username);
auth_message.set_password(password);
// TODO: register 0 celt versions
auth_message.set_opus(true);
self.send_message(2, auth_message)
}
pub fn ping(&self) -> Result<usize, SendError> {
let ping_message = proto::Ping::new();
// TODO: fill the ping with info
self.send_message(3, ping_message)
}
fn send_message<M: protobuf::core::Message>(&self, id: u16, message: M) -> Result<usize, SendError> {
let mut packet = vec![];
// ID - what type of message are we sending
packet.write_u16::<BigEndian>(id).unwrap();
let payload = message.write_to_bytes().unwrap();
if payload.len() as u64 > u32::max_value() as u64 {
return Err(SendError::MessageTooLarge("Payload too large to fit in one packet!"))
}
// The length of the payload
packet.write_u32::<BigEndian>(payload.len() as u32).unwrap();
// The payload itself
packet.extend(payload);
// Panic on poisoned mutex - this is desired (because could only be poisoned from panic)
// https://doc.rust-lang.org/std/sync/struct.Mutex.html#poisoning
let mut channel = self.control_channel.lock().unwrap();
match channel.ssl_write(&*packet) {
Err(err) => Err(SendError::Ssl(err)),
Ok(val) => Ok(val)
}
}
//fn read_message(&self) -> Result<protobuf::core::Message, ReadError> {
//}
}
|
{
ConnectionError::TcpStream(e)
}
|
identifier_body
|
connection.rs
|
use proto;
use byteorder::{BigEndian, WriteBytesExt};
use std;
use std::net::{IpAddr, TcpStream};
use std::sync::Mutex;
use openssl;
use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream};
use protobuf;
// Connect
const SSL_HANDSHAKE_RETRIES: u8 = 3;
#[derive(Debug)]
pub enum ConnectionError {
ExceededHandshakeRetries(&'static str),
Ssl(openssl::ssl::Error),
TcpStream(std::io::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for ConnectionError {
fn from(e: openssl::ssl::Error) -> Self {
ConnectionError::Ssl(e)
}
}
impl From<openssl::error::ErrorStack> for ConnectionError {
fn from(e: openssl::error::ErrorStack) -> Self {
ConnectionError::Ssl(openssl::ssl::Error::from(e))
}
}
impl From<std::io::Error> for ConnectionError {
fn from(e: std::io::Error) -> Self {
ConnectionError::TcpStream(e)
}
}
#[derive(Debug)]
pub enum SendError {
MessageTooLarge(&'static str),
Ssl(openssl::ssl::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for SendError {
fn from(e: openssl::ssl::Error) -> Self {
SendError::Ssl(e)
}
}
pub struct Connection {
control_channel: Mutex<SslStream<TcpStream>>
}
impl Connection {
pub fn new(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<Connection, ConnectionError> {
let stream = try!(Connection::connect(host, port, verify, nodelay));
Ok(Connection { control_channel: Mutex::new(stream) })
}
fn connect(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<SslStream<TcpStream>, ConnectionError> {
let mut context = try!(SslContext::new(SslMethod::Tlsv1));
if verify {
context.set_verify(openssl::ssl::SSL_VERIFY_PEER);
} else {
context.set_verify(openssl::ssl::SSL_VERIFY_NONE);
}
let stream = try!(TcpStream::connect((host, port)));
// I don't know how this can fail, so just unwrapping for now...
// TODO: figure this out
stream.set_nodelay(nodelay).unwrap();
match SslStream::connect(&context, stream) {
Ok(val) => Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(interrupted_stream) => {
let mut ssl_stream = interrupted_stream;
let mut tries: u8 = 1;
while tries < SSL_HANDSHAKE_RETRIES {
match ssl_stream.handshake() {
Ok(val) => return Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => return Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(new_interrupted_stream) => {
ssl_stream = new_interrupted_stream;
tries += 1;
continue
}
}
}
}
Err(ConnectionError::ExceededHandshakeRetries("Exceeded number of handshake retries"))
}
}
}
}
pub fn version_exchange(&self, version: u32, release: String, os: String, os_version: String) -> Result<usize, SendError> {
let mut version_message = proto::Version::new();
version_message.set_version(version);
version_message.set_release(release);
version_message.set_os(os);
version_message.set_os_version(os_version);
self.send_message(0, version_message)
}
// TODO: authentication with tokens
pub fn authenticate(&self, username: String, password: String) -> Result<usize, SendError> {
let mut auth_message = proto::Authenticate::new();
auth_message.set_username(username);
auth_message.set_password(password);
// TODO: register 0 celt versions
auth_message.set_opus(true);
self.send_message(2, auth_message)
}
pub fn ping(&self) -> Result<usize, SendError> {
let ping_message = proto::Ping::new();
// TODO: fill the ping with info
self.send_message(3, ping_message)
}
fn send_message<M: protobuf::core::Message>(&self, id: u16, message: M) -> Result<usize, SendError> {
let mut packet = vec![];
// ID - what type of message are we sending
packet.write_u16::<BigEndian>(id).unwrap();
let payload = message.write_to_bytes().unwrap();
if payload.len() as u64 > u32::max_value() as u64 {
return Err(SendError::MessageTooLarge("Payload too large to fit in one packet!"))
}
// The length of the payload
packet.write_u32::<BigEndian>(payload.len() as u32).unwrap();
// The payload itself
packet.extend(payload);
// Panic on poisoned mutex - this is desired (because could only be poisoned from panic)
// https://doc.rust-lang.org/std/sync/struct.Mutex.html#poisoning
let mut channel = self.control_channel.lock().unwrap();
match channel.ssl_write(&*packet) {
Err(err) => Err(SendError::Ssl(err)),
Ok(val) => Ok(val)
}
}
|
//fn read_message(&self) -> Result<protobuf::core::Message, ReadError> {
//}
}
|
random_line_split
|
|
connection.rs
|
use proto;
use byteorder::{BigEndian, WriteBytesExt};
use std;
use std::net::{IpAddr, TcpStream};
use std::sync::Mutex;
use openssl;
use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream};
use protobuf;
// Connect
const SSL_HANDSHAKE_RETRIES: u8 = 3;
#[derive(Debug)]
pub enum ConnectionError {
ExceededHandshakeRetries(&'static str),
Ssl(openssl::ssl::Error),
TcpStream(std::io::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for ConnectionError {
fn from(e: openssl::ssl::Error) -> Self {
ConnectionError::Ssl(e)
}
}
impl From<openssl::error::ErrorStack> for ConnectionError {
fn from(e: openssl::error::ErrorStack) -> Self {
ConnectionError::Ssl(openssl::ssl::Error::from(e))
}
}
impl From<std::io::Error> for ConnectionError {
fn
|
(e: std::io::Error) -> Self {
ConnectionError::TcpStream(e)
}
}
#[derive(Debug)]
pub enum SendError {
MessageTooLarge(&'static str),
Ssl(openssl::ssl::Error)
} // TODO: this should impl error, display
impl From<openssl::ssl::Error> for SendError {
fn from(e: openssl::ssl::Error) -> Self {
SendError::Ssl(e)
}
}
pub struct Connection {
control_channel: Mutex<SslStream<TcpStream>>
}
impl Connection {
pub fn new(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<Connection, ConnectionError> {
let stream = try!(Connection::connect(host, port, verify, nodelay));
Ok(Connection { control_channel: Mutex::new(stream) })
}
fn connect(host: IpAddr, port: u16, verify: bool, nodelay: bool) -> Result<SslStream<TcpStream>, ConnectionError> {
let mut context = try!(SslContext::new(SslMethod::Tlsv1));
if verify {
context.set_verify(openssl::ssl::SSL_VERIFY_PEER);
} else {
context.set_verify(openssl::ssl::SSL_VERIFY_NONE);
}
let stream = try!(TcpStream::connect((host, port)));
// I don't know how this can fail, so just unwrapping for now...
// TODO: figure this out
stream.set_nodelay(nodelay).unwrap();
match SslStream::connect(&context, stream) {
Ok(val) => Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(interrupted_stream) => {
let mut ssl_stream = interrupted_stream;
let mut tries: u8 = 1;
while tries < SSL_HANDSHAKE_RETRIES {
match ssl_stream.handshake() {
Ok(val) => return Ok(val),
Err(err) => match err {
HandshakeError::Failure(handshake_err) => return Err(ConnectionError::Ssl(handshake_err)),
HandshakeError::Interrupted(new_interrupted_stream) => {
ssl_stream = new_interrupted_stream;
tries += 1;
continue
}
}
}
}
Err(ConnectionError::ExceededHandshakeRetries("Exceeded number of handshake retries"))
}
}
}
}
pub fn version_exchange(&self, version: u32, release: String, os: String, os_version: String) -> Result<usize, SendError> {
let mut version_message = proto::Version::new();
version_message.set_version(version);
version_message.set_release(release);
version_message.set_os(os);
version_message.set_os_version(os_version);
self.send_message(0, version_message)
}
// TODO: authentication with tokens
pub fn authenticate(&self, username: String, password: String) -> Result<usize, SendError> {
let mut auth_message = proto::Authenticate::new();
auth_message.set_username(username);
auth_message.set_password(password);
// TODO: register 0 celt versions
auth_message.set_opus(true);
self.send_message(2, auth_message)
}
pub fn ping(&self) -> Result<usize, SendError> {
let ping_message = proto::Ping::new();
// TODO: fill the ping with info
self.send_message(3, ping_message)
}
fn send_message<M: protobuf::core::Message>(&self, id: u16, message: M) -> Result<usize, SendError> {
let mut packet = vec![];
// ID - what type of message are we sending
packet.write_u16::<BigEndian>(id).unwrap();
let payload = message.write_to_bytes().unwrap();
if payload.len() as u64 > u32::max_value() as u64 {
return Err(SendError::MessageTooLarge("Payload too large to fit in one packet!"))
}
// The length of the payload
packet.write_u32::<BigEndian>(payload.len() as u32).unwrap();
// The payload itself
packet.extend(payload);
// Panic on poisoned mutex - this is desired (because could only be poisoned from panic)
// https://doc.rust-lang.org/std/sync/struct.Mutex.html#poisoning
let mut channel = self.control_channel.lock().unwrap();
match channel.ssl_write(&*packet) {
Err(err) => Err(SendError::Ssl(err)),
Ok(val) => Ok(val)
}
}
//fn read_message(&self) -> Result<protobuf::core::Message, ReadError> {
//}
}
|
from
|
identifier_name
|
symbol.rs
|
use clingo::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn main() {
// create a number, identifier (function without arguments), and a function symbol
let number_symbol = Symbol::create_number(42);
let identifier_symbol = Symbol::create_id("x", true).unwrap();
let mut symbols = vec![number_symbol, identifier_symbol];
let function_symbol = Symbol::create_function("x", &symbols, true).unwrap();
symbols.push(function_symbol);
// print the symbols along with their hash values
let mut hasher = DefaultHasher::new();
for symbol in &symbols {
symbol.hash(&mut hasher);
println!(
"the hash of {} is {}",
symbol.to_string().unwrap(),
hasher.finish()
);
}
// retrieve argument symbols of a symbol
let symbols2 = function_symbol.arguments().unwrap();
// equal to comparison
for symbol in symbols2 {
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] == symbol {
print!("equal");
} else
|
println!(" to {}", symbol.to_string().unwrap());
}
// less than comparison
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] < symbols[1] {
print!("less");
} else {
print!("not less");
}
println!(" than {}", symbols[1].to_string().unwrap());
}
|
{
print!("not equal");
}
|
conditional_block
|
symbol.rs
|
use clingo::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn main() {
// create a number, identifier (function without arguments), and a function symbol
let number_symbol = Symbol::create_number(42);
let identifier_symbol = Symbol::create_id("x", true).unwrap();
let mut symbols = vec![number_symbol, identifier_symbol];
let function_symbol = Symbol::create_function("x", &symbols, true).unwrap();
symbols.push(function_symbol);
|
"the hash of {} is {}",
symbol.to_string().unwrap(),
hasher.finish()
);
}
// retrieve argument symbols of a symbol
let symbols2 = function_symbol.arguments().unwrap();
// equal to comparison
for symbol in symbols2 {
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] == symbol {
print!("equal");
} else {
print!("not equal");
}
println!(" to {}", symbol.to_string().unwrap());
}
// less than comparison
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] < symbols[1] {
print!("less");
} else {
print!("not less");
}
println!(" than {}", symbols[1].to_string().unwrap());
}
|
// print the symbols along with their hash values
let mut hasher = DefaultHasher::new();
for symbol in &symbols {
symbol.hash(&mut hasher);
println!(
|
random_line_split
|
symbol.rs
|
use clingo::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn
|
() {
// create a number, identifier (function without arguments), and a function symbol
let number_symbol = Symbol::create_number(42);
let identifier_symbol = Symbol::create_id("x", true).unwrap();
let mut symbols = vec![number_symbol, identifier_symbol];
let function_symbol = Symbol::create_function("x", &symbols, true).unwrap();
symbols.push(function_symbol);
// print the symbols along with their hash values
let mut hasher = DefaultHasher::new();
for symbol in &symbols {
symbol.hash(&mut hasher);
println!(
"the hash of {} is {}",
symbol.to_string().unwrap(),
hasher.finish()
);
}
// retrieve argument symbols of a symbol
let symbols2 = function_symbol.arguments().unwrap();
// equal to comparison
for symbol in symbols2 {
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] == symbol {
print!("equal");
} else {
print!("not equal");
}
println!(" to {}", symbol.to_string().unwrap());
}
// less than comparison
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] < symbols[1] {
print!("less");
} else {
print!("not less");
}
println!(" than {}", symbols[1].to_string().unwrap());
}
|
main
|
identifier_name
|
symbol.rs
|
use clingo::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn main()
|
// retrieve argument symbols of a symbol
let symbols2 = function_symbol.arguments().unwrap();
// equal to comparison
for symbol in symbols2 {
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] == symbol {
print!("equal");
} else {
print!("not equal");
}
println!(" to {}", symbol.to_string().unwrap());
}
// less than comparison
print!("{} is ", symbols[0].to_string().unwrap());
if symbols[0] < symbols[1] {
print!("less");
} else {
print!("not less");
}
println!(" than {}", symbols[1].to_string().unwrap());
}
|
{
// create a number, identifier (function without arguments), and a function symbol
let number_symbol = Symbol::create_number(42);
let identifier_symbol = Symbol::create_id("x", true).unwrap();
let mut symbols = vec![number_symbol, identifier_symbol];
let function_symbol = Symbol::create_function("x", &symbols, true).unwrap();
symbols.push(function_symbol);
// print the symbols along with their hash values
let mut hasher = DefaultHasher::new();
for symbol in &symbols {
symbol.hash(&mut hasher);
println!(
"the hash of {} is {}",
symbol.to_string().unwrap(),
hasher.finish()
);
}
|
identifier_body
|
unboxed-closure-sugar-not-used-on-fn.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 that the `Fn` traits require `()` form without a feature gate.
fn bar1(x: &Fn<(),()>) {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
fn
|
<T>(x: &T) where T: Fn<(),()> {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
fn main() { }
|
bar2
|
identifier_name
|
unboxed-closure-sugar-not-used-on-fn.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 that the `Fn` traits require `()` form without a feature gate.
fn bar1(x: &Fn<(),()>) {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
fn bar2<T>(x: &T) where T: Fn<(),()> {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
fn main() { }
|
random_line_split
|
|
unboxed-closure-sugar-not-used-on-fn.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 that the `Fn` traits require `()` form without a feature gate.
fn bar1(x: &Fn<(),()>) {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
fn bar2<T>(x: &T) where T: Fn<(),()>
|
fn main() { }
|
{
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family
}
|
identifier_body
|
tokenize.rs
|
// Copyright 2014 The html5ever 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 debug;
extern crate html5;
use std::io;
use std::char;
use std::default::Default;
use html5::tokenizer::{TokenSink, Token, TokenizerOpts, ParseError};
use html5::tokenizer::{CharacterTokens, NullCharacterToken, TagToken, StartTag, EndTag};
use html5::driver::{tokenize_to, one_input};
struct
|
{
in_char_run: bool,
}
impl TokenPrinter {
fn is_char(&mut self, is_char: bool) {
match (self.in_char_run, is_char) {
(false, true ) => print!("CHAR : \""),
(true, false) => println!("\""),
_ => (),
}
self.in_char_run = is_char;
}
fn do_char(&mut self, c: char) {
self.is_char(true);
char::escape_default(c, |d| print!("{:c}", d));
}
}
impl TokenSink for TokenPrinter {
fn process_token(&mut self, token: Token) {
match token {
CharacterTokens(b) => {
for c in b.as_slice().chars() {
self.do_char(c);
}
}
NullCharacterToken => self.do_char('\0'),
TagToken(tag) => {
self.is_char(false);
// This is not proper HTML serialization, of course.
match tag.kind {
StartTag => print!("TAG : <\x1b[32m{:s}\x1b[0m", tag.name),
EndTag => print!("TAG : <\x1b[31m/{:s}\x1b[0m", tag.name),
}
for attr in tag.attrs.iter() {
print!(" \x1b[36m{:s}\x1b[0m='\x1b[34m{:s}\x1b[0m'", attr.name, attr.value);
}
if tag.self_closing {
print!(" \x1b[31m/\x1b[0m");
}
println!(">");
}
ParseError(err) => {
self.is_char(false);
println!("ERROR: {:s}", err);
}
_ => {
self.is_char(false);
println!("OTHER: {}", token);
}
}
}
}
fn main() {
let mut sink = TokenPrinter {
in_char_run: false,
};
let input = io::stdin().read_to_str().unwrap();
tokenize_to(&mut sink, one_input(input), TokenizerOpts {
profile: true,
.. Default::default()
});
sink.is_char(false);
}
|
TokenPrinter
|
identifier_name
|
tokenize.rs
|
// Copyright 2014 The html5ever 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 debug;
extern crate html5;
use std::io;
use std::char;
use std::default::Default;
use html5::tokenizer::{TokenSink, Token, TokenizerOpts, ParseError};
use html5::tokenizer::{CharacterTokens, NullCharacterToken, TagToken, StartTag, EndTag};
use html5::driver::{tokenize_to, one_input};
struct TokenPrinter {
in_char_run: bool,
}
impl TokenPrinter {
fn is_char(&mut self, is_char: bool) {
match (self.in_char_run, is_char) {
(false, true ) => print!("CHAR : \""),
(true, false) => println!("\""),
_ => (),
}
self.in_char_run = is_char;
}
fn do_char(&mut self, c: char) {
self.is_char(true);
char::escape_default(c, |d| print!("{:c}", d));
}
}
impl TokenSink for TokenPrinter {
fn process_token(&mut self, token: Token) {
match token {
CharacterTokens(b) => {
for c in b.as_slice().chars() {
self.do_char(c);
}
}
NullCharacterToken => self.do_char('\0'),
TagToken(tag) => {
self.is_char(false);
// This is not proper HTML serialization, of course.
match tag.kind {
StartTag => print!("TAG : <\x1b[32m{:s}\x1b[0m", tag.name),
EndTag => print!("TAG : <\x1b[31m/{:s}\x1b[0m", tag.name),
}
for attr in tag.attrs.iter() {
print!(" \x1b[36m{:s}\x1b[0m='\x1b[34m{:s}\x1b[0m'", attr.name, attr.value);
}
if tag.self_closing
|
println!(">");
}
ParseError(err) => {
self.is_char(false);
println!("ERROR: {:s}", err);
}
_ => {
self.is_char(false);
println!("OTHER: {}", token);
}
}
}
}
fn main() {
let mut sink = TokenPrinter {
in_char_run: false,
};
let input = io::stdin().read_to_str().unwrap();
tokenize_to(&mut sink, one_input(input), TokenizerOpts {
profile: true,
.. Default::default()
});
sink.is_char(false);
}
|
{
print!(" \x1b[31m/\x1b[0m");
}
|
conditional_block
|
tokenize.rs
|
// Copyright 2014 The html5ever 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 debug;
extern crate html5;
use std::io;
use std::char;
use std::default::Default;
use html5::tokenizer::{TokenSink, Token, TokenizerOpts, ParseError};
use html5::tokenizer::{CharacterTokens, NullCharacterToken, TagToken, StartTag, EndTag};
use html5::driver::{tokenize_to, one_input};
struct TokenPrinter {
in_char_run: bool,
}
impl TokenPrinter {
fn is_char(&mut self, is_char: bool) {
match (self.in_char_run, is_char) {
(false, true ) => print!("CHAR : \""),
(true, false) => println!("\""),
_ => (),
}
self.in_char_run = is_char;
}
fn do_char(&mut self, c: char) {
self.is_char(true);
char::escape_default(c, |d| print!("{:c}", d));
}
}
impl TokenSink for TokenPrinter {
fn process_token(&mut self, token: Token) {
match token {
CharacterTokens(b) => {
for c in b.as_slice().chars() {
self.do_char(c);
}
}
NullCharacterToken => self.do_char('\0'),
TagToken(tag) => {
self.is_char(false);
// This is not proper HTML serialization, of course.
match tag.kind {
StartTag => print!("TAG : <\x1b[32m{:s}\x1b[0m", tag.name),
EndTag => print!("TAG : <\x1b[31m/{:s}\x1b[0m", tag.name),
}
for attr in tag.attrs.iter() {
print!(" \x1b[36m{:s}\x1b[0m='\x1b[34m{:s}\x1b[0m'", attr.name, attr.value);
}
if tag.self_closing {
print!(" \x1b[31m/\x1b[0m");
}
println!(">");
}
|
ParseError(err) => {
self.is_char(false);
println!("ERROR: {:s}", err);
}
_ => {
self.is_char(false);
println!("OTHER: {}", token);
}
}
}
}
fn main() {
let mut sink = TokenPrinter {
in_char_run: false,
};
let input = io::stdin().read_to_str().unwrap();
tokenize_to(&mut sink, one_input(input), TokenizerOpts {
profile: true,
.. Default::default()
});
sink.is_char(false);
}
|
random_line_split
|
|
master.rs
|
//! The master module provides the Master struct which instructs Workers which
//! portions of the image they should render and collects their results to combine
//! into the final image.
use std::path::PathBuf;
use std::io::prelude::*;
use std::collections::HashMap;
use std::net::ToSocketAddrs;
use std::iter;
use std::time::SystemTime;
use bincode::{Infinite, serialize, deserialize};
use image;
use mio::tcp::{TcpStream, Shutdown};
use mio::*;
use film::Image;
use exec::Config;
use exec::distrib::{worker, Instructions, Frame};
use sampler::BlockQueue;
/// Stores distributed rendering status. The frame is either `InProgress` and contains
/// partially rendered results from the workers who've reported the frame or is `Completed`
/// and has been saved out to disk.
#[derive(Debug)]
enum DistributedFrame {
InProgress {
// The number of workers who have reported results for this
// frame so far
num_reporting: usize,
render: Image,
// Start time of this frame, when we got the first tiles in from a worker
first_tile_recv: SystemTime,
},
Completed,
}
impl DistributedFrame {
pub fn start(img_dim: (usize, usize)) -> DistributedFrame
|
}
/// Buffer for collecting results from a worker asynchronously. The buffer is filled
/// as we get readable events from the workers until it reaches the expected size.
/// After this the Frame is decoded and accumulated in the appropriate `DistributedFrame`
#[derive(Clone, Debug)]
struct WorkerBuffer {
pub buf: Vec<u8>,
pub expected_size: usize,
pub currently_read: usize,
}
impl WorkerBuffer {
pub fn new() -> WorkerBuffer {
WorkerBuffer { buf: Vec::new(), expected_size: 8, currently_read: 0 }
}
}
/// The Master organizes the set of Worker processes and instructions them what parts
/// of the scene to render. As workers report results the master collects them and
/// saves out the PNG once all workers have reported the frame.
pub struct Master {
/// Hostnames of the workers to send work too
workers: Vec<String>,
connections: Vec<TcpStream>,
/// Temporary buffers to store worker results in as they're
/// read in over TCP
worker_buffers: Vec<WorkerBuffer>,
config: Config,
/// List of the frames we're collecting or have completed
frames: HashMap<usize, DistributedFrame>,
img_dim: (usize, usize),
/// Number of 8x8 blocks we're assigning per worker
blocks_per_worker: usize,
/// Remainder of blocks that will be tacked on to the last
/// worker's assignment
blocks_remainder: usize,
}
impl Master {
/// Create a new master that will contact the worker nodes passed and
/// send instructions on what parts of the scene to start rendering
pub fn start_workers(workers: Vec<String>, config: Config, img_dim: (usize, usize))
-> (Master, EventLoop<Master>) {
// Figure out how many blocks we have for this image and assign them to our workers
let queue = BlockQueue::new((img_dim.0 as u32, img_dim.1 as u32), (8, 8), (0, 0));
let blocks_per_worker = queue.len() / workers.len();
let blocks_remainder = queue.len() % workers.len();
let mut event_loop = EventLoop::<Master>::new().unwrap();
let mut connections = Vec::new();
// Connect to each worker and add them to the event loop
for (i, host) in workers.iter().enumerate() {
let addr = (&host[..], worker::PORT).to_socket_addrs().unwrap().next().unwrap();
match TcpStream::connect(&addr) {
Ok(stream) => {
// Each worker is identified in the event loop by their index in the vec
if let Err(e) = event_loop.register(&stream, Token(i), EventSet::all(), PollOpt::level()) {
panic!("Error registering stream from {}: {}", host, e);
}
connections.push(stream);
},
Err(e) => panic!("Failed to contact worker {}: {:?}", host, e),
}
}
let worker_buffers: Vec<_> = iter::repeat(WorkerBuffer::new()).take(workers.len()).collect();
let master = Master { workers: workers, connections: connections,
worker_buffers: worker_buffers, config: config,
frames: HashMap::new(),
img_dim: img_dim,
blocks_per_worker: blocks_per_worker,
blocks_remainder: blocks_remainder };
(master, event_loop)
}
/// Read a result frame from a worker and save it into the list of frames we're collecting from
/// all workers. Will save out the final render if all workers have reported results for this
/// frame.
fn save_results(&mut self, frame: Frame) {
let frame_num = frame.frame as usize;
let img_dim = self.img_dim;
// Find the frame being reported and create it if we haven't received parts of this frame yet
let mut df = self.frames.entry(frame_num).or_insert_with(|| DistributedFrame::start(img_dim));
let mut finished = false;
match *df {
DistributedFrame::InProgress { ref mut num_reporting, ref mut render, ref first_tile_recv } => {
// Collect results from the worker and see if we've finished the frame and can save
// it out
render.add_blocks(frame.block_size, &frame.blocks, &frame.pixels);
*num_reporting += 1;
if *num_reporting == self.workers.len() {
let render_time = first_tile_recv.elapsed().expect("Failed to get rendering time?");
let out_file = match self.config.out_path.extension() {
Some(_) => self.config.out_path.clone(),
None => self.config.out_path.join(
PathBuf::from(format!("frame{:05}.png", frame_num))),
};
let img = render.get_srgb8();
let dim = render.dimensions();
match image::save_buffer(&out_file.as_path(), &img[..], dim.0 as u32,
dim.1 as u32, image::RGB(8)) {
Ok(_) => {},
Err(e) => println!("Error saving image, {}", e),
};
println!("Frame {}: time between receiving first and last tile {:4}s",
frame_num, render_time.as_secs() as f64 + render_time.subsec_nanos() as f64 * 1e-9);
println!("Frame {}: rendered to '{}'\n--------------------", frame_num, out_file.display());
finished = true;
}
},
DistributedFrame::Completed => println!("Worker reporting on completed frame {}?", frame_num),
}
// This is a bit awkward, since we borrow df in the match we can't mark it finished in there
if finished {
*df = DistributedFrame::Completed;
}
}
/// Read results from a worker and accumulate this data in its worker buffer. Returns true if
/// we've read the data being sent and can decode the buffer
fn read_worker_buffer(&mut self, worker: usize) -> bool {
let buf = &mut self.worker_buffers[worker];
// If we haven't read the size of data being sent, read that now
if buf.currently_read < 8 {
// First 8 bytes are a u64 specifying the number of bytes being sent
buf.buf.extend(iter::repeat(0u8).take(8));
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
if buf.currently_read == buf.expected_size {
// How many bytes we expect to get from the worker for a frame
buf.expected_size = deserialize(&buf.buf[..]).unwrap();
// Extend the Vec so we've got enough room for the remaning bytes, minus the 8 for the
// encoded size header
buf.buf.extend(iter::repeat(0u8).take(buf.expected_size - 8));
}
}
// If we've finished reading the size header we can now start reading the frame data
if buf.currently_read >= 8 {
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
}
buf.currently_read == buf.expected_size
}
}
impl Handler for Master {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Master>, token: Token, event: EventSet) {
let worker = token.as_usize();
if event.is_error() {
// We don't do distributed error handling so should abort if we fail to
// connect for now
panic!("Error connecting to {}", self.workers[worker]);
}
// If the worker has terminated, shutdown the read end of the connection
if event.is_hup() {
if let Err(e) = self.connections[worker].shutdown(Shutdown::Both) {
println!("Error shutting down worker {}: {}", worker, e);
}
// Remove the connection from the event loop
if let Err(e) = event_loop.deregister(&self.connections[worker]) {
println!("Error deregistering worker {}: {}", worker, e);
}
}
// A worker is ready to receive instructions from us
if event.is_writable() {
let b_start = worker * self.blocks_per_worker;
let b_count =
if worker == self.workers.len() - 1 {
self.blocks_per_worker + self.blocks_remainder
} else {
self.blocks_per_worker
};
let instr = Instructions::new(&self.config.scene_file,
(self.config.frame_info.start, self.config.frame_info.end),
b_start, b_count);
// Encode and send our instructions to the worker
let bytes = serialize(&instr, Infinite).unwrap();
if let Err(e) = self.connections[worker].write_all(&bytes[..]) {
println!("Failed to send instructions to {}: {:?}", self.workers[worker], e);
}
// Register that we no longer care about writable events on this connection
event_loop.reregister(&self.connections[worker], token,
EventSet::readable() | EventSet::error() | EventSet::hup(),
PollOpt::level()).expect("Re-registering failed");
}
// Some results are available from a worker
// Read results from the worker, if we've accumulated all the data being sent
// decode and accumulate the frame
if event.is_readable() && self.read_worker_buffer(worker) {
let frame = deserialize(&self.worker_buffers[worker].buf[..]).unwrap();
self.save_results(frame);
// Clean up the worker buffer for the next frame
self.worker_buffers[worker].buf.clear();
self.worker_buffers[worker].expected_size = 8;
self.worker_buffers[worker].currently_read = 0;
}
// After getting results from the worker we check if we've completed all our frames
// and exit if so
let all_complete = self.frames.values().fold(true,
|all, v| {
match *v {
DistributedFrame::Completed => true && all,
_ => false,
}
});
// The frame start/end range is inclusive, so we must add 1 here
let num_frames = self.config.frame_info.end - self.config.frame_info.start + 1;
if self.frames.len() == num_frames && all_complete {
event_loop.shutdown();
}
}
}
|
{
DistributedFrame::InProgress {
num_reporting: 0,
render: Image::new(img_dim),
first_tile_recv: SystemTime::now(),
}
}
|
identifier_body
|
master.rs
|
//! The master module provides the Master struct which instructs Workers which
//! portions of the image they should render and collects their results to combine
//! into the final image.
use std::path::PathBuf;
use std::io::prelude::*;
use std::collections::HashMap;
use std::net::ToSocketAddrs;
use std::iter;
use std::time::SystemTime;
use bincode::{Infinite, serialize, deserialize};
use image;
use mio::tcp::{TcpStream, Shutdown};
use mio::*;
use film::Image;
use exec::Config;
use exec::distrib::{worker, Instructions, Frame};
use sampler::BlockQueue;
/// Stores distributed rendering status. The frame is either `InProgress` and contains
/// partially rendered results from the workers who've reported the frame or is `Completed`
/// and has been saved out to disk.
#[derive(Debug)]
enum DistributedFrame {
InProgress {
// The number of workers who have reported results for this
// frame so far
num_reporting: usize,
render: Image,
// Start time of this frame, when we got the first tiles in from a worker
first_tile_recv: SystemTime,
},
Completed,
}
impl DistributedFrame {
pub fn start(img_dim: (usize, usize)) -> DistributedFrame {
DistributedFrame::InProgress {
num_reporting: 0,
render: Image::new(img_dim),
first_tile_recv: SystemTime::now(),
}
}
}
/// Buffer for collecting results from a worker asynchronously. The buffer is filled
/// as we get readable events from the workers until it reaches the expected size.
/// After this the Frame is decoded and accumulated in the appropriate `DistributedFrame`
#[derive(Clone, Debug)]
struct WorkerBuffer {
pub buf: Vec<u8>,
pub expected_size: usize,
pub currently_read: usize,
}
impl WorkerBuffer {
pub fn new() -> WorkerBuffer {
WorkerBuffer { buf: Vec::new(), expected_size: 8, currently_read: 0 }
}
}
/// The Master organizes the set of Worker processes and instructions them what parts
/// of the scene to render. As workers report results the master collects them and
/// saves out the PNG once all workers have reported the frame.
pub struct Master {
/// Hostnames of the workers to send work too
workers: Vec<String>,
connections: Vec<TcpStream>,
/// Temporary buffers to store worker results in as they're
/// read in over TCP
worker_buffers: Vec<WorkerBuffer>,
config: Config,
/// List of the frames we're collecting or have completed
frames: HashMap<usize, DistributedFrame>,
img_dim: (usize, usize),
/// Number of 8x8 blocks we're assigning per worker
blocks_per_worker: usize,
/// Remainder of blocks that will be tacked on to the last
/// worker's assignment
blocks_remainder: usize,
}
impl Master {
/// Create a new master that will contact the worker nodes passed and
/// send instructions on what parts of the scene to start rendering
pub fn start_workers(workers: Vec<String>, config: Config, img_dim: (usize, usize))
-> (Master, EventLoop<Master>) {
// Figure out how many blocks we have for this image and assign them to our workers
let queue = BlockQueue::new((img_dim.0 as u32, img_dim.1 as u32), (8, 8), (0, 0));
let blocks_per_worker = queue.len() / workers.len();
let blocks_remainder = queue.len() % workers.len();
let mut event_loop = EventLoop::<Master>::new().unwrap();
let mut connections = Vec::new();
// Connect to each worker and add them to the event loop
|
for (i, host) in workers.iter().enumerate() {
let addr = (&host[..], worker::PORT).to_socket_addrs().unwrap().next().unwrap();
match TcpStream::connect(&addr) {
Ok(stream) => {
// Each worker is identified in the event loop by their index in the vec
if let Err(e) = event_loop.register(&stream, Token(i), EventSet::all(), PollOpt::level()) {
panic!("Error registering stream from {}: {}", host, e);
}
connections.push(stream);
},
Err(e) => panic!("Failed to contact worker {}: {:?}", host, e),
}
}
let worker_buffers: Vec<_> = iter::repeat(WorkerBuffer::new()).take(workers.len()).collect();
let master = Master { workers: workers, connections: connections,
worker_buffers: worker_buffers, config: config,
frames: HashMap::new(),
img_dim: img_dim,
blocks_per_worker: blocks_per_worker,
blocks_remainder: blocks_remainder };
(master, event_loop)
}
/// Read a result frame from a worker and save it into the list of frames we're collecting from
/// all workers. Will save out the final render if all workers have reported results for this
/// frame.
fn save_results(&mut self, frame: Frame) {
let frame_num = frame.frame as usize;
let img_dim = self.img_dim;
// Find the frame being reported and create it if we haven't received parts of this frame yet
let mut df = self.frames.entry(frame_num).or_insert_with(|| DistributedFrame::start(img_dim));
let mut finished = false;
match *df {
DistributedFrame::InProgress { ref mut num_reporting, ref mut render, ref first_tile_recv } => {
// Collect results from the worker and see if we've finished the frame and can save
// it out
render.add_blocks(frame.block_size, &frame.blocks, &frame.pixels);
*num_reporting += 1;
if *num_reporting == self.workers.len() {
let render_time = first_tile_recv.elapsed().expect("Failed to get rendering time?");
let out_file = match self.config.out_path.extension() {
Some(_) => self.config.out_path.clone(),
None => self.config.out_path.join(
PathBuf::from(format!("frame{:05}.png", frame_num))),
};
let img = render.get_srgb8();
let dim = render.dimensions();
match image::save_buffer(&out_file.as_path(), &img[..], dim.0 as u32,
dim.1 as u32, image::RGB(8)) {
Ok(_) => {},
Err(e) => println!("Error saving image, {}", e),
};
println!("Frame {}: time between receiving first and last tile {:4}s",
frame_num, render_time.as_secs() as f64 + render_time.subsec_nanos() as f64 * 1e-9);
println!("Frame {}: rendered to '{}'\n--------------------", frame_num, out_file.display());
finished = true;
}
},
DistributedFrame::Completed => println!("Worker reporting on completed frame {}?", frame_num),
}
// This is a bit awkward, since we borrow df in the match we can't mark it finished in there
if finished {
*df = DistributedFrame::Completed;
}
}
/// Read results from a worker and accumulate this data in its worker buffer. Returns true if
/// we've read the data being sent and can decode the buffer
fn read_worker_buffer(&mut self, worker: usize) -> bool {
let buf = &mut self.worker_buffers[worker];
// If we haven't read the size of data being sent, read that now
if buf.currently_read < 8 {
// First 8 bytes are a u64 specifying the number of bytes being sent
buf.buf.extend(iter::repeat(0u8).take(8));
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
if buf.currently_read == buf.expected_size {
// How many bytes we expect to get from the worker for a frame
buf.expected_size = deserialize(&buf.buf[..]).unwrap();
// Extend the Vec so we've got enough room for the remaning bytes, minus the 8 for the
// encoded size header
buf.buf.extend(iter::repeat(0u8).take(buf.expected_size - 8));
}
}
// If we've finished reading the size header we can now start reading the frame data
if buf.currently_read >= 8 {
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
}
buf.currently_read == buf.expected_size
}
}
impl Handler for Master {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Master>, token: Token, event: EventSet) {
let worker = token.as_usize();
if event.is_error() {
// We don't do distributed error handling so should abort if we fail to
// connect for now
panic!("Error connecting to {}", self.workers[worker]);
}
// If the worker has terminated, shutdown the read end of the connection
if event.is_hup() {
if let Err(e) = self.connections[worker].shutdown(Shutdown::Both) {
println!("Error shutting down worker {}: {}", worker, e);
}
// Remove the connection from the event loop
if let Err(e) = event_loop.deregister(&self.connections[worker]) {
println!("Error deregistering worker {}: {}", worker, e);
}
}
// A worker is ready to receive instructions from us
if event.is_writable() {
let b_start = worker * self.blocks_per_worker;
let b_count =
if worker == self.workers.len() - 1 {
self.blocks_per_worker + self.blocks_remainder
} else {
self.blocks_per_worker
};
let instr = Instructions::new(&self.config.scene_file,
(self.config.frame_info.start, self.config.frame_info.end),
b_start, b_count);
// Encode and send our instructions to the worker
let bytes = serialize(&instr, Infinite).unwrap();
if let Err(e) = self.connections[worker].write_all(&bytes[..]) {
println!("Failed to send instructions to {}: {:?}", self.workers[worker], e);
}
// Register that we no longer care about writable events on this connection
event_loop.reregister(&self.connections[worker], token,
EventSet::readable() | EventSet::error() | EventSet::hup(),
PollOpt::level()).expect("Re-registering failed");
}
// Some results are available from a worker
// Read results from the worker, if we've accumulated all the data being sent
// decode and accumulate the frame
if event.is_readable() && self.read_worker_buffer(worker) {
let frame = deserialize(&self.worker_buffers[worker].buf[..]).unwrap();
self.save_results(frame);
// Clean up the worker buffer for the next frame
self.worker_buffers[worker].buf.clear();
self.worker_buffers[worker].expected_size = 8;
self.worker_buffers[worker].currently_read = 0;
}
// After getting results from the worker we check if we've completed all our frames
// and exit if so
let all_complete = self.frames.values().fold(true,
|all, v| {
match *v {
DistributedFrame::Completed => true && all,
_ => false,
}
});
// The frame start/end range is inclusive, so we must add 1 here
let num_frames = self.config.frame_info.end - self.config.frame_info.start + 1;
if self.frames.len() == num_frames && all_complete {
event_loop.shutdown();
}
}
}
|
random_line_split
|
|
master.rs
|
//! The master module provides the Master struct which instructs Workers which
//! portions of the image they should render and collects their results to combine
//! into the final image.
use std::path::PathBuf;
use std::io::prelude::*;
use std::collections::HashMap;
use std::net::ToSocketAddrs;
use std::iter;
use std::time::SystemTime;
use bincode::{Infinite, serialize, deserialize};
use image;
use mio::tcp::{TcpStream, Shutdown};
use mio::*;
use film::Image;
use exec::Config;
use exec::distrib::{worker, Instructions, Frame};
use sampler::BlockQueue;
/// Stores distributed rendering status. The frame is either `InProgress` and contains
/// partially rendered results from the workers who've reported the frame or is `Completed`
/// and has been saved out to disk.
#[derive(Debug)]
enum DistributedFrame {
InProgress {
// The number of workers who have reported results for this
// frame so far
num_reporting: usize,
render: Image,
// Start time of this frame, when we got the first tiles in from a worker
first_tile_recv: SystemTime,
},
Completed,
}
impl DistributedFrame {
pub fn
|
(img_dim: (usize, usize)) -> DistributedFrame {
DistributedFrame::InProgress {
num_reporting: 0,
render: Image::new(img_dim),
first_tile_recv: SystemTime::now(),
}
}
}
/// Buffer for collecting results from a worker asynchronously. The buffer is filled
/// as we get readable events from the workers until it reaches the expected size.
/// After this the Frame is decoded and accumulated in the appropriate `DistributedFrame`
#[derive(Clone, Debug)]
struct WorkerBuffer {
pub buf: Vec<u8>,
pub expected_size: usize,
pub currently_read: usize,
}
impl WorkerBuffer {
pub fn new() -> WorkerBuffer {
WorkerBuffer { buf: Vec::new(), expected_size: 8, currently_read: 0 }
}
}
/// The Master organizes the set of Worker processes and instructions them what parts
/// of the scene to render. As workers report results the master collects them and
/// saves out the PNG once all workers have reported the frame.
pub struct Master {
/// Hostnames of the workers to send work too
workers: Vec<String>,
connections: Vec<TcpStream>,
/// Temporary buffers to store worker results in as they're
/// read in over TCP
worker_buffers: Vec<WorkerBuffer>,
config: Config,
/// List of the frames we're collecting or have completed
frames: HashMap<usize, DistributedFrame>,
img_dim: (usize, usize),
/// Number of 8x8 blocks we're assigning per worker
blocks_per_worker: usize,
/// Remainder of blocks that will be tacked on to the last
/// worker's assignment
blocks_remainder: usize,
}
impl Master {
/// Create a new master that will contact the worker nodes passed and
/// send instructions on what parts of the scene to start rendering
pub fn start_workers(workers: Vec<String>, config: Config, img_dim: (usize, usize))
-> (Master, EventLoop<Master>) {
// Figure out how many blocks we have for this image and assign them to our workers
let queue = BlockQueue::new((img_dim.0 as u32, img_dim.1 as u32), (8, 8), (0, 0));
let blocks_per_worker = queue.len() / workers.len();
let blocks_remainder = queue.len() % workers.len();
let mut event_loop = EventLoop::<Master>::new().unwrap();
let mut connections = Vec::new();
// Connect to each worker and add them to the event loop
for (i, host) in workers.iter().enumerate() {
let addr = (&host[..], worker::PORT).to_socket_addrs().unwrap().next().unwrap();
match TcpStream::connect(&addr) {
Ok(stream) => {
// Each worker is identified in the event loop by their index in the vec
if let Err(e) = event_loop.register(&stream, Token(i), EventSet::all(), PollOpt::level()) {
panic!("Error registering stream from {}: {}", host, e);
}
connections.push(stream);
},
Err(e) => panic!("Failed to contact worker {}: {:?}", host, e),
}
}
let worker_buffers: Vec<_> = iter::repeat(WorkerBuffer::new()).take(workers.len()).collect();
let master = Master { workers: workers, connections: connections,
worker_buffers: worker_buffers, config: config,
frames: HashMap::new(),
img_dim: img_dim,
blocks_per_worker: blocks_per_worker,
blocks_remainder: blocks_remainder };
(master, event_loop)
}
/// Read a result frame from a worker and save it into the list of frames we're collecting from
/// all workers. Will save out the final render if all workers have reported results for this
/// frame.
fn save_results(&mut self, frame: Frame) {
let frame_num = frame.frame as usize;
let img_dim = self.img_dim;
// Find the frame being reported and create it if we haven't received parts of this frame yet
let mut df = self.frames.entry(frame_num).or_insert_with(|| DistributedFrame::start(img_dim));
let mut finished = false;
match *df {
DistributedFrame::InProgress { ref mut num_reporting, ref mut render, ref first_tile_recv } => {
// Collect results from the worker and see if we've finished the frame and can save
// it out
render.add_blocks(frame.block_size, &frame.blocks, &frame.pixels);
*num_reporting += 1;
if *num_reporting == self.workers.len() {
let render_time = first_tile_recv.elapsed().expect("Failed to get rendering time?");
let out_file = match self.config.out_path.extension() {
Some(_) => self.config.out_path.clone(),
None => self.config.out_path.join(
PathBuf::from(format!("frame{:05}.png", frame_num))),
};
let img = render.get_srgb8();
let dim = render.dimensions();
match image::save_buffer(&out_file.as_path(), &img[..], dim.0 as u32,
dim.1 as u32, image::RGB(8)) {
Ok(_) => {},
Err(e) => println!("Error saving image, {}", e),
};
println!("Frame {}: time between receiving first and last tile {:4}s",
frame_num, render_time.as_secs() as f64 + render_time.subsec_nanos() as f64 * 1e-9);
println!("Frame {}: rendered to '{}'\n--------------------", frame_num, out_file.display());
finished = true;
}
},
DistributedFrame::Completed => println!("Worker reporting on completed frame {}?", frame_num),
}
// This is a bit awkward, since we borrow df in the match we can't mark it finished in there
if finished {
*df = DistributedFrame::Completed;
}
}
/// Read results from a worker and accumulate this data in its worker buffer. Returns true if
/// we've read the data being sent and can decode the buffer
fn read_worker_buffer(&mut self, worker: usize) -> bool {
let buf = &mut self.worker_buffers[worker];
// If we haven't read the size of data being sent, read that now
if buf.currently_read < 8 {
// First 8 bytes are a u64 specifying the number of bytes being sent
buf.buf.extend(iter::repeat(0u8).take(8));
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
if buf.currently_read == buf.expected_size {
// How many bytes we expect to get from the worker for a frame
buf.expected_size = deserialize(&buf.buf[..]).unwrap();
// Extend the Vec so we've got enough room for the remaning bytes, minus the 8 for the
// encoded size header
buf.buf.extend(iter::repeat(0u8).take(buf.expected_size - 8));
}
}
// If we've finished reading the size header we can now start reading the frame data
if buf.currently_read >= 8 {
match self.connections[worker].read(&mut buf.buf[buf.currently_read..]) {
Ok(n) => buf.currently_read += n,
Err(e) => println!("Error reading results from worker {}: {}", self.workers[worker], e),
}
}
buf.currently_read == buf.expected_size
}
}
impl Handler for Master {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Master>, token: Token, event: EventSet) {
let worker = token.as_usize();
if event.is_error() {
// We don't do distributed error handling so should abort if we fail to
// connect for now
panic!("Error connecting to {}", self.workers[worker]);
}
// If the worker has terminated, shutdown the read end of the connection
if event.is_hup() {
if let Err(e) = self.connections[worker].shutdown(Shutdown::Both) {
println!("Error shutting down worker {}: {}", worker, e);
}
// Remove the connection from the event loop
if let Err(e) = event_loop.deregister(&self.connections[worker]) {
println!("Error deregistering worker {}: {}", worker, e);
}
}
// A worker is ready to receive instructions from us
if event.is_writable() {
let b_start = worker * self.blocks_per_worker;
let b_count =
if worker == self.workers.len() - 1 {
self.blocks_per_worker + self.blocks_remainder
} else {
self.blocks_per_worker
};
let instr = Instructions::new(&self.config.scene_file,
(self.config.frame_info.start, self.config.frame_info.end),
b_start, b_count);
// Encode and send our instructions to the worker
let bytes = serialize(&instr, Infinite).unwrap();
if let Err(e) = self.connections[worker].write_all(&bytes[..]) {
println!("Failed to send instructions to {}: {:?}", self.workers[worker], e);
}
// Register that we no longer care about writable events on this connection
event_loop.reregister(&self.connections[worker], token,
EventSet::readable() | EventSet::error() | EventSet::hup(),
PollOpt::level()).expect("Re-registering failed");
}
// Some results are available from a worker
// Read results from the worker, if we've accumulated all the data being sent
// decode and accumulate the frame
if event.is_readable() && self.read_worker_buffer(worker) {
let frame = deserialize(&self.worker_buffers[worker].buf[..]).unwrap();
self.save_results(frame);
// Clean up the worker buffer for the next frame
self.worker_buffers[worker].buf.clear();
self.worker_buffers[worker].expected_size = 8;
self.worker_buffers[worker].currently_read = 0;
}
// After getting results from the worker we check if we've completed all our frames
// and exit if so
let all_complete = self.frames.values().fold(true,
|all, v| {
match *v {
DistributedFrame::Completed => true && all,
_ => false,
}
});
// The frame start/end range is inclusive, so we must add 1 here
let num_frames = self.config.frame_info.end - self.config.frame_info.start + 1;
if self.frames.len() == num_frames && all_complete {
event_loop.shutdown();
}
}
}
|
start
|
identifier_name
|
command.rs
|
// Copyright (C) 2018 Pietro Albini
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::env;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::process;
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
use regex::Regex;
use common::config::Config;
use common::prelude::*;
lazy_static! {
static ref ADDR_RE: Regex = Regex::new(r"127\.0\.0\.1:[0-9]+").unwrap();
}
fn binaries_path() -> Result<PathBuf> {
let mut current = env::current_exe()?;
current.pop();
if current.ends_with("deps") {
current.pop();
}
Ok(current)
}
#[allow(dead_code)]
pub enum Stream {
Stdout,
Stderr,
}
pub struct
|
{
child: process::Child,
stdout: BufReader<process::ChildStdout>,
stderr: BufReader<process::ChildStderr>,
}
impl Command {
pub fn new(binary: &str, args: &[&str]) -> Result<Self> {
let mut child = process::Command::new(binaries_path()?.join(binary))
.args(args)
.stdout(process::Stdio::piped())
.stderr(process::Stdio::piped())
.spawn()?;
Ok(Command {
stdout: BufReader::new(child.stdout.take().unwrap()),
stderr: BufReader::new(child.stderr.take().unwrap()),
child,
})
}
pub fn capture_line(
&mut self,
content: &str,
stream: Stream,
) -> Result<String> {
let reader = match stream {
Stream::Stdout => &mut self.stdout as &mut BufRead,
Stream::Stderr => &mut self.stderr as &mut BufRead,
};
let mut buffer = String::new();
loop {
buffer.clear();
reader.read_line(&mut buffer)?;
if buffer.contains(content) {
break;
}
}
buffer.shrink_to_fit();
Ok(buffer)
}
pub fn signal(&mut self, signal: Signal) -> Result<()> {
kill(Pid::from_raw(self.child.id() as i32), signal)?;
Ok(())
}
pub fn stop(&mut self) -> Result<()> {
self.signal(Signal::SIGTERM)?;
self.wait()
}
pub fn wait(&mut self) -> Result<()> {
self.child.wait()?;
Ok(())
}
}
pub struct FisherCommand {
inner: Command,
}
impl FisherCommand {
pub fn new(config: &Config) -> Result<Self> {
Ok(FisherCommand {
inner: Command::new("fisher", &[
config.save()?.to_str().unwrap(),
])?,
})
}
pub fn server_addr(&mut self) -> Result<SocketAddr> {
let line = self.capture_line("listening", Stream::Stdout)?;
let captures = ADDR_RE.captures(&line).unwrap();
println!("{:?}", captures);
Ok((&captures[0]).parse()?)
}
}
impl Deref for FisherCommand {
type Target = Command;
fn deref(&self) -> &Command {
&self.inner
}
}
impl DerefMut for FisherCommand {
fn deref_mut(&mut self) -> &mut Command {
&mut self.inner
}
}
|
Command
|
identifier_name
|
command.rs
|
// Copyright (C) 2018 Pietro Albini
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::env;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::process;
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
use regex::Regex;
use common::config::Config;
use common::prelude::*;
lazy_static! {
static ref ADDR_RE: Regex = Regex::new(r"127\.0\.0\.1:[0-9]+").unwrap();
}
fn binaries_path() -> Result<PathBuf> {
let mut current = env::current_exe()?;
current.pop();
if current.ends_with("deps") {
current.pop();
}
Ok(current)
}
#[allow(dead_code)]
pub enum Stream {
Stdout,
Stderr,
}
pub struct Command {
child: process::Child,
stdout: BufReader<process::ChildStdout>,
stderr: BufReader<process::ChildStderr>,
}
impl Command {
pub fn new(binary: &str, args: &[&str]) -> Result<Self> {
let mut child = process::Command::new(binaries_path()?.join(binary))
.args(args)
.stdout(process::Stdio::piped())
.stderr(process::Stdio::piped())
.spawn()?;
Ok(Command {
stdout: BufReader::new(child.stdout.take().unwrap()),
stderr: BufReader::new(child.stderr.take().unwrap()),
child,
})
}
pub fn capture_line(
&mut self,
content: &str,
stream: Stream,
) -> Result<String> {
let reader = match stream {
Stream::Stdout => &mut self.stdout as &mut BufRead,
Stream::Stderr => &mut self.stderr as &mut BufRead,
};
let mut buffer = String::new();
loop {
buffer.clear();
reader.read_line(&mut buffer)?;
if buffer.contains(content) {
break;
}
}
buffer.shrink_to_fit();
Ok(buffer)
}
pub fn signal(&mut self, signal: Signal) -> Result<()> {
kill(Pid::from_raw(self.child.id() as i32), signal)?;
Ok(())
}
pub fn stop(&mut self) -> Result<()> {
self.signal(Signal::SIGTERM)?;
self.wait()
}
pub fn wait(&mut self) -> Result<()> {
self.child.wait()?;
Ok(())
}
}
pub struct FisherCommand {
inner: Command,
|
impl FisherCommand {
pub fn new(config: &Config) -> Result<Self> {
Ok(FisherCommand {
inner: Command::new("fisher", &[
config.save()?.to_str().unwrap(),
])?,
})
}
pub fn server_addr(&mut self) -> Result<SocketAddr> {
let line = self.capture_line("listening", Stream::Stdout)?;
let captures = ADDR_RE.captures(&line).unwrap();
println!("{:?}", captures);
Ok((&captures[0]).parse()?)
}
}
impl Deref for FisherCommand {
type Target = Command;
fn deref(&self) -> &Command {
&self.inner
}
}
impl DerefMut for FisherCommand {
fn deref_mut(&mut self) -> &mut Command {
&mut self.inner
}
}
|
}
|
random_line_split
|
sleeper_list.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Maintains a shared list of sleeping schedulers. Schedulers
//! use this to wake each other up.
use container::Container;
use vec::OwnedVector;
use option::{Option, Some, None};
use cell::Cell;
use unstable::sync::{UnsafeArc, LittleLock};
use rt::sched::SchedHandle;
use clone::Clone;
pub struct SleeperList {
priv state: UnsafeArc<State>
}
struct State {
count: uint,
stack: ~[SchedHandle],
lock: LittleLock
}
impl SleeperList {
pub fn new() -> SleeperList {
SleeperList {
state: UnsafeArc::new(State {
count: 0,
stack: ~[],
lock: LittleLock::new()
})
}
}
pub fn push(&mut self, handle: SchedHandle) {
let handle = Cell::new(handle);
unsafe {
let state = self.state.get();
do (*state).lock.lock {
(*state).count += 1;
(*state).stack.push(handle.take());
}
}
}
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
do (*state).lock.lock {
if!(*state).stack.is_empty() {
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
/// A pop that may sometimes miss enqueued elements, but is much faster
/// to give up without doing any synchronization
pub fn casual_pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
// NB: Unsynchronized check
if (*state).count == 0 { return None; }
do (*state).lock.lock {
if!(*state).stack.is_empty()
|
else {
None
}
}
}
}
}
impl Clone for SleeperList {
fn clone(&self) -> SleeperList {
SleeperList {
state: self.state.clone()
}
}
}
|
{
// NB: count is also protected by the lock
(*state).count -= 1;
Some((*state).stack.pop())
}
|
conditional_block
|
sleeper_list.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
//
// 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.
//! Maintains a shared list of sleeping schedulers. Schedulers
//! use this to wake each other up.
use container::Container;
use vec::OwnedVector;
use option::{Option, Some, None};
use cell::Cell;
use unstable::sync::{UnsafeArc, LittleLock};
use rt::sched::SchedHandle;
use clone::Clone;
pub struct SleeperList {
priv state: UnsafeArc<State>
}
struct State {
count: uint,
stack: ~[SchedHandle],
lock: LittleLock
}
impl SleeperList {
pub fn new() -> SleeperList {
SleeperList {
state: UnsafeArc::new(State {
count: 0,
stack: ~[],
lock: LittleLock::new()
})
}
}
pub fn push(&mut self, handle: SchedHandle) {
let handle = Cell::new(handle);
unsafe {
let state = self.state.get();
do (*state).lock.lock {
(*state).count += 1;
(*state).stack.push(handle.take());
}
}
}
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
do (*state).lock.lock {
if!(*state).stack.is_empty() {
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
/// A pop that may sometimes miss enqueued elements, but is much faster
/// to give up without doing any synchronization
pub fn casual_pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
// NB: Unsynchronized check
if (*state).count == 0 { return None; }
do (*state).lock.lock {
if!(*state).stack.is_empty() {
// NB: count is also protected by the lock
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
}
impl Clone for SleeperList {
fn clone(&self) -> SleeperList {
SleeperList {
state: self.state.clone()
}
}
}
|
// http://rust-lang.org/COPYRIGHT.
|
random_line_split
|
sleeper_list.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Maintains a shared list of sleeping schedulers. Schedulers
//! use this to wake each other up.
use container::Container;
use vec::OwnedVector;
use option::{Option, Some, None};
use cell::Cell;
use unstable::sync::{UnsafeArc, LittleLock};
use rt::sched::SchedHandle;
use clone::Clone;
pub struct SleeperList {
priv state: UnsafeArc<State>
}
struct State {
count: uint,
stack: ~[SchedHandle],
lock: LittleLock
}
impl SleeperList {
pub fn new() -> SleeperList
|
pub fn push(&mut self, handle: SchedHandle) {
let handle = Cell::new(handle);
unsafe {
let state = self.state.get();
do (*state).lock.lock {
(*state).count += 1;
(*state).stack.push(handle.take());
}
}
}
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
do (*state).lock.lock {
if!(*state).stack.is_empty() {
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
/// A pop that may sometimes miss enqueued elements, but is much faster
/// to give up without doing any synchronization
pub fn casual_pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
// NB: Unsynchronized check
if (*state).count == 0 { return None; }
do (*state).lock.lock {
if!(*state).stack.is_empty() {
// NB: count is also protected by the lock
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
}
impl Clone for SleeperList {
fn clone(&self) -> SleeperList {
SleeperList {
state: self.state.clone()
}
}
}
|
{
SleeperList {
state: UnsafeArc::new(State {
count: 0,
stack: ~[],
lock: LittleLock::new()
})
}
}
|
identifier_body
|
sleeper_list.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Maintains a shared list of sleeping schedulers. Schedulers
//! use this to wake each other up.
use container::Container;
use vec::OwnedVector;
use option::{Option, Some, None};
use cell::Cell;
use unstable::sync::{UnsafeArc, LittleLock};
use rt::sched::SchedHandle;
use clone::Clone;
pub struct SleeperList {
priv state: UnsafeArc<State>
}
struct State {
count: uint,
stack: ~[SchedHandle],
lock: LittleLock
}
impl SleeperList {
pub fn
|
() -> SleeperList {
SleeperList {
state: UnsafeArc::new(State {
count: 0,
stack: ~[],
lock: LittleLock::new()
})
}
}
pub fn push(&mut self, handle: SchedHandle) {
let handle = Cell::new(handle);
unsafe {
let state = self.state.get();
do (*state).lock.lock {
(*state).count += 1;
(*state).stack.push(handle.take());
}
}
}
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
do (*state).lock.lock {
if!(*state).stack.is_empty() {
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
/// A pop that may sometimes miss enqueued elements, but is much faster
/// to give up without doing any synchronization
pub fn casual_pop(&mut self) -> Option<SchedHandle> {
unsafe {
let state = self.state.get();
// NB: Unsynchronized check
if (*state).count == 0 { return None; }
do (*state).lock.lock {
if!(*state).stack.is_empty() {
// NB: count is also protected by the lock
(*state).count -= 1;
Some((*state).stack.pop())
} else {
None
}
}
}
}
}
impl Clone for SleeperList {
fn clone(&self) -> SleeperList {
SleeperList {
state: self.state.clone()
}
}
}
|
new
|
identifier_name
|
task-perf-alloc-unwind.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.
#![feature(unsafe_destructor)]
use std::os;
use std::task;
use std::time::Duration;
#[deriving(Clone)]
enum List<T> {
Nil, Cons(T, Box<List<T>>)
}
enum UniqueList {
ULNil, ULCons(Box<UniqueList>)
}
fn main() {
let (repeat, depth) = if os::getenv("RUST_BENCH").is_some() {
(50, 1000)
} else {
(10, 10)
};
run(repeat, depth);
}
fn
|
(repeat: int, depth: int) {
for _ in range(0, repeat) {
let dur = Duration::span(|| {
task::try(proc() {
recurse_or_panic(depth, None)
});
});
println!("iter: {}", dur);
}
}
type nillist = List<()>;
// Filled with things that have to be unwound
struct State {
unique: Box<nillist>,
vec: Vec<Box<nillist>>,
res: r
}
struct r {
_l: Box<nillist>,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&mut self) {}
}
fn r(l: Box<nillist>) -> r {
r {
_l: l
}
}
fn recurse_or_panic(depth: int, st: Option<State>) {
if depth == 0 {
panic!();
} else {
let depth = depth - 1;
let st = match st {
None => {
State {
unique: box Nil,
vec: vec!(box Nil),
res: r(box Nil)
}
}
Some(st) => {
let mut v = st.vec.clone();
v.push_all(&[box Cons((), st.vec.last().unwrap().clone())]);
State {
unique: box Cons((), box *st.unique),
vec: v,
res: r(box Cons((), st.res._l.clone())),
}
}
};
recurse_or_panic(depth, Some(st));
}
}
|
run
|
identifier_name
|
task-perf-alloc-unwind.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.
//
|
// <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(unsafe_destructor)]
use std::os;
use std::task;
use std::time::Duration;
#[deriving(Clone)]
enum List<T> {
Nil, Cons(T, Box<List<T>>)
}
enum UniqueList {
ULNil, ULCons(Box<UniqueList>)
}
fn main() {
let (repeat, depth) = if os::getenv("RUST_BENCH").is_some() {
(50, 1000)
} else {
(10, 10)
};
run(repeat, depth);
}
fn run(repeat: int, depth: int) {
for _ in range(0, repeat) {
let dur = Duration::span(|| {
task::try(proc() {
recurse_or_panic(depth, None)
});
});
println!("iter: {}", dur);
}
}
type nillist = List<()>;
// Filled with things that have to be unwound
struct State {
unique: Box<nillist>,
vec: Vec<Box<nillist>>,
res: r
}
struct r {
_l: Box<nillist>,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&mut self) {}
}
fn r(l: Box<nillist>) -> r {
r {
_l: l
}
}
fn recurse_or_panic(depth: int, st: Option<State>) {
if depth == 0 {
panic!();
} else {
let depth = depth - 1;
let st = match st {
None => {
State {
unique: box Nil,
vec: vec!(box Nil),
res: r(box Nil)
}
}
Some(st) => {
let mut v = st.vec.clone();
v.push_all(&[box Cons((), st.vec.last().unwrap().clone())]);
State {
unique: box Cons((), box *st.unique),
vec: v,
res: r(box Cons((), st.res._l.clone())),
}
}
};
recurse_or_panic(depth, Some(st));
}
}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
task-perf-alloc-unwind.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.
#![feature(unsafe_destructor)]
use std::os;
use std::task;
use std::time::Duration;
#[deriving(Clone)]
enum List<T> {
Nil, Cons(T, Box<List<T>>)
}
enum UniqueList {
ULNil, ULCons(Box<UniqueList>)
}
fn main() {
let (repeat, depth) = if os::getenv("RUST_BENCH").is_some() {
(50, 1000)
} else {
(10, 10)
};
run(repeat, depth);
}
fn run(repeat: int, depth: int) {
for _ in range(0, repeat) {
let dur = Duration::span(|| {
task::try(proc() {
recurse_or_panic(depth, None)
});
});
println!("iter: {}", dur);
}
}
type nillist = List<()>;
// Filled with things that have to be unwound
struct State {
unique: Box<nillist>,
vec: Vec<Box<nillist>>,
res: r
}
struct r {
_l: Box<nillist>,
}
#[unsafe_destructor]
impl Drop for r {
fn drop(&mut self) {}
}
fn r(l: Box<nillist>) -> r {
r {
_l: l
}
}
fn recurse_or_panic(depth: int, st: Option<State>) {
if depth == 0
|
else {
let depth = depth - 1;
let st = match st {
None => {
State {
unique: box Nil,
vec: vec!(box Nil),
res: r(box Nil)
}
}
Some(st) => {
let mut v = st.vec.clone();
v.push_all(&[box Cons((), st.vec.last().unwrap().clone())]);
State {
unique: box Cons((), box *st.unique),
vec: v,
res: r(box Cons((), st.res._l.clone())),
}
}
};
recurse_or_panic(depth, Some(st));
}
}
|
{
panic!();
}
|
conditional_block
|
lib.rs
|
//! # url_open
//! A simple crate to open URLs in the default web browser.
//!
//! ### Usage
//!
//! ```no_run
//! extern crate url;
//! extern crate url_open;
//!
//! use url::Url;
//! use url_open::UrlOpen;
//!
//! fn main() {
//! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open();
//! }
//! ```
extern crate url;
use url::Url;
/// Convenience method to open URLs
pub trait UrlOpen {
fn open(&self);
}
impl UrlOpen for Url {
fn open(&self) {
open(self);
}
}
#[cfg(target_os = "windows")]
pub fn open(url: &Url) {
extern crate shell32;
extern crate winapi;
use std::ffi::CString;
use std::ptr;
unsafe {
shell32::ShellExecuteA(ptr::null_mut(),
CString::new("open").unwrap().as_ptr(),
CString::new(url.to_string().replace("\n", "%0A")).unwrap().as_ptr(),
ptr::null(),
ptr::null(),
winapi::SW_SHOWNORMAL);
}
}
#[cfg(target_os = "macos")]
pub fn open(url: &Url)
|
#[cfg(target_os = "linux")]
pub fn open(url: &Url) {
let _ = std::process::Command::new("xdg-open").arg(url.to_string()).output();
}
|
{
let _ = std::process::Command::new("open").arg(url.to_string()).output();
}
|
identifier_body
|
lib.rs
|
//! # url_open
//! A simple crate to open URLs in the default web browser.
//!
//! ### Usage
//!
//! ```no_run
//! extern crate url;
//! extern crate url_open;
//!
//! use url::Url;
//! use url_open::UrlOpen;
//!
//! fn main() {
//! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open();
//! }
//! ```
extern crate url;
use url::Url;
/// Convenience method to open URLs
pub trait UrlOpen {
fn open(&self);
}
impl UrlOpen for Url {
fn open(&self) {
open(self);
}
}
#[cfg(target_os = "windows")]
pub fn open(url: &Url) {
extern crate shell32;
extern crate winapi;
use std::ffi::CString;
use std::ptr;
unsafe {
shell32::ShellExecuteA(ptr::null_mut(),
CString::new("open").unwrap().as_ptr(),
CString::new(url.to_string().replace("\n", "%0A")).unwrap().as_ptr(),
ptr::null(),
ptr::null(),
winapi::SW_SHOWNORMAL);
}
}
#[cfg(target_os = "macos")]
pub fn open(url: &Url) {
let _ = std::process::Command::new("open").arg(url.to_string()).output();
}
#[cfg(target_os = "linux")]
pub fn
|
(url: &Url) {
let _ = std::process::Command::new("xdg-open").arg(url.to_string()).output();
}
|
open
|
identifier_name
|
lib.rs
|
//! # url_open
//! A simple crate to open URLs in the default web browser.
//!
//! ### Usage
//!
//! ```no_run
//! extern crate url;
//! extern crate url_open;
//!
//! use url::Url;
//! use url_open::UrlOpen;
//!
//! fn main() {
//! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open();
//! }
//! ```
extern crate url;
use url::Url;
|
impl UrlOpen for Url {
fn open(&self) {
open(self);
}
}
#[cfg(target_os = "windows")]
pub fn open(url: &Url) {
extern crate shell32;
extern crate winapi;
use std::ffi::CString;
use std::ptr;
unsafe {
shell32::ShellExecuteA(ptr::null_mut(),
CString::new("open").unwrap().as_ptr(),
CString::new(url.to_string().replace("\n", "%0A")).unwrap().as_ptr(),
ptr::null(),
ptr::null(),
winapi::SW_SHOWNORMAL);
}
}
#[cfg(target_os = "macos")]
pub fn open(url: &Url) {
let _ = std::process::Command::new("open").arg(url.to_string()).output();
}
#[cfg(target_os = "linux")]
pub fn open(url: &Url) {
let _ = std::process::Command::new("xdg-open").arg(url.to_string()).output();
}
|
/// Convenience method to open URLs
pub trait UrlOpen {
fn open(&self);
}
|
random_line_split
|
map.rs
|
use engine::Tile;
use util::FromChar;
use util::units::{Point, Size};
use std::path::Path;
use std::fs::File;
use std::io::Read;
/// A map.
pub struct Map {
pub tiles: Vec<Vec<Tile>>,
pub size: Size,
pub starting_position: Point,
}
impl Map {
/// Creates a new map from a string.
pub fn from_string(s: String) -> Map {
let lines: Vec<&str> = s.split('\n').filter(|l|!l.is_empty()).collect();
let expected_line_length = lines.first().expect("Map string contained no lines").len();
if!lines.iter().all(|x| x.len() == expected_line_length) {
panic!("Different length lines in level string")
}
let tiles: Vec<Vec<Tile>> = lines
.iter()
.map(|l| l.chars().map(|c| Tile::from_char(c)).collect())
.collect();
let mut starting_position = None;
for (y, row_vec) in lines.iter().enumerate() {
for (x, tile) in row_vec.chars().enumerate() {
if tile == '@' {
starting_position = Some(Point::new(x as i32, y as i32));
}
}
}
let starting_position = starting_position
.expect("Map string did not contain a starting position, '@'");
let size = Size::new(tiles.len() as i32, tiles[0].len() as i32);
Map {
tiles: tiles,
size: size,
starting_position: starting_position,
}
}
pub fn from_file<T>(path: T) -> Map
where
T: AsRef<Path>,
{
let mut level_file = File::open(path).ok().expect("Could not find level file");
let mut level_string = String::new();
level_file
.read_to_string(&mut level_string)
.ok()
.expect("Could not read from level file");
Map::from_string(level_string)
}
pub fn at(&self, loc: Point) -> Tile
|
pub fn is_walkable(&self, loc: Point) -> bool {
self.at(loc).is_walkable()
}
pub fn set_tile(&mut self, loc: Point, tile: Tile) {
self.tiles[loc.y as usize][loc.x as usize] = tile;
}
pub fn height(&self) -> i32 {
self.tiles.len() as i32
}
pub fn width(&self) -> i32 {
self.tiles[0].len() as i32
}
}
|
{
self.tiles[loc.y as usize][loc.x as usize]
}
|
identifier_body
|
map.rs
|
use engine::Tile;
use util::FromChar;
use util::units::{Point, Size};
use std::path::Path;
use std::fs::File;
use std::io::Read;
/// A map.
pub struct Map {
pub tiles: Vec<Vec<Tile>>,
pub size: Size,
pub starting_position: Point,
}
impl Map {
/// Creates a new map from a string.
pub fn from_string(s: String) -> Map {
let lines: Vec<&str> = s.split('\n').filter(|l|!l.is_empty()).collect();
let expected_line_length = lines.first().expect("Map string contained no lines").len();
if!lines.iter().all(|x| x.len() == expected_line_length) {
panic!("Different length lines in level string")
}
let tiles: Vec<Vec<Tile>> = lines
.iter()
.map(|l| l.chars().map(|c| Tile::from_char(c)).collect())
.collect();
let mut starting_position = None;
for (y, row_vec) in lines.iter().enumerate() {
for (x, tile) in row_vec.chars().enumerate() {
if tile == '@' {
starting_position = Some(Point::new(x as i32, y as i32));
}
}
}
let starting_position = starting_position
.expect("Map string did not contain a starting position, '@'");
let size = Size::new(tiles.len() as i32, tiles[0].len() as i32);
Map {
tiles: tiles,
|
pub fn from_file<T>(path: T) -> Map
where
T: AsRef<Path>,
{
let mut level_file = File::open(path).ok().expect("Could not find level file");
let mut level_string = String::new();
level_file
.read_to_string(&mut level_string)
.ok()
.expect("Could not read from level file");
Map::from_string(level_string)
}
pub fn at(&self, loc: Point) -> Tile {
self.tiles[loc.y as usize][loc.x as usize]
}
pub fn is_walkable(&self, loc: Point) -> bool {
self.at(loc).is_walkable()
}
pub fn set_tile(&mut self, loc: Point, tile: Tile) {
self.tiles[loc.y as usize][loc.x as usize] = tile;
}
pub fn height(&self) -> i32 {
self.tiles.len() as i32
}
pub fn width(&self) -> i32 {
self.tiles[0].len() as i32
}
}
|
size: size,
starting_position: starting_position,
}
}
|
random_line_split
|
map.rs
|
use engine::Tile;
use util::FromChar;
use util::units::{Point, Size};
use std::path::Path;
use std::fs::File;
use std::io::Read;
/// A map.
pub struct Map {
pub tiles: Vec<Vec<Tile>>,
pub size: Size,
pub starting_position: Point,
}
impl Map {
/// Creates a new map from a string.
pub fn from_string(s: String) -> Map {
let lines: Vec<&str> = s.split('\n').filter(|l|!l.is_empty()).collect();
let expected_line_length = lines.first().expect("Map string contained no lines").len();
if!lines.iter().all(|x| x.len() == expected_line_length)
|
let tiles: Vec<Vec<Tile>> = lines
.iter()
.map(|l| l.chars().map(|c| Tile::from_char(c)).collect())
.collect();
let mut starting_position = None;
for (y, row_vec) in lines.iter().enumerate() {
for (x, tile) in row_vec.chars().enumerate() {
if tile == '@' {
starting_position = Some(Point::new(x as i32, y as i32));
}
}
}
let starting_position = starting_position
.expect("Map string did not contain a starting position, '@'");
let size = Size::new(tiles.len() as i32, tiles[0].len() as i32);
Map {
tiles: tiles,
size: size,
starting_position: starting_position,
}
}
pub fn from_file<T>(path: T) -> Map
where
T: AsRef<Path>,
{
let mut level_file = File::open(path).ok().expect("Could not find level file");
let mut level_string = String::new();
level_file
.read_to_string(&mut level_string)
.ok()
.expect("Could not read from level file");
Map::from_string(level_string)
}
pub fn at(&self, loc: Point) -> Tile {
self.tiles[loc.y as usize][loc.x as usize]
}
pub fn is_walkable(&self, loc: Point) -> bool {
self.at(loc).is_walkable()
}
pub fn set_tile(&mut self, loc: Point, tile: Tile) {
self.tiles[loc.y as usize][loc.x as usize] = tile;
}
pub fn height(&self) -> i32 {
self.tiles.len() as i32
}
pub fn width(&self) -> i32 {
self.tiles[0].len() as i32
}
}
|
{
panic!("Different length lines in level string")
}
|
conditional_block
|
map.rs
|
use engine::Tile;
use util::FromChar;
use util::units::{Point, Size};
use std::path::Path;
use std::fs::File;
use std::io::Read;
/// A map.
pub struct Map {
pub tiles: Vec<Vec<Tile>>,
pub size: Size,
pub starting_position: Point,
}
impl Map {
/// Creates a new map from a string.
pub fn from_string(s: String) -> Map {
let lines: Vec<&str> = s.split('\n').filter(|l|!l.is_empty()).collect();
let expected_line_length = lines.first().expect("Map string contained no lines").len();
if!lines.iter().all(|x| x.len() == expected_line_length) {
panic!("Different length lines in level string")
}
let tiles: Vec<Vec<Tile>> = lines
.iter()
.map(|l| l.chars().map(|c| Tile::from_char(c)).collect())
.collect();
let mut starting_position = None;
for (y, row_vec) in lines.iter().enumerate() {
for (x, tile) in row_vec.chars().enumerate() {
if tile == '@' {
starting_position = Some(Point::new(x as i32, y as i32));
}
}
}
let starting_position = starting_position
.expect("Map string did not contain a starting position, '@'");
let size = Size::new(tiles.len() as i32, tiles[0].len() as i32);
Map {
tiles: tiles,
size: size,
starting_position: starting_position,
}
}
pub fn from_file<T>(path: T) -> Map
where
T: AsRef<Path>,
{
let mut level_file = File::open(path).ok().expect("Could not find level file");
let mut level_string = String::new();
level_file
.read_to_string(&mut level_string)
.ok()
.expect("Could not read from level file");
Map::from_string(level_string)
}
pub fn at(&self, loc: Point) -> Tile {
self.tiles[loc.y as usize][loc.x as usize]
}
pub fn is_walkable(&self, loc: Point) -> bool {
self.at(loc).is_walkable()
}
pub fn set_tile(&mut self, loc: Point, tile: Tile) {
self.tiles[loc.y as usize][loc.x as usize] = tile;
}
pub fn height(&self) -> i32 {
self.tiles.len() as i32
}
pub fn
|
(&self) -> i32 {
self.tiles[0].len() as i32
}
}
|
width
|
identifier_name
|
mod.rs
|
pub use self::cargo_clean::{clean, CleanOptions};
pub use self::cargo_compile::{compile, compile_pkg, resolve_dependencies, CompileOptions};
|
pub use self::cargo_rustc::{Context, LayoutProxy};
pub use self::cargo_rustc::{BuildOutput, BuildConfig, TargetConfig};
pub use self::cargo_rustc::{CommandType, CommandPrototype, ExecEngine, ProcessEngine};
pub use self::cargo_run::run;
pub use self::cargo_install::{install, install_list, uninstall};
pub use self::cargo_new::{new, init, NewOptions, VersionControl};
pub use self::cargo_doc::{doc, DocOptions};
pub use self::cargo_generate_lockfile::{generate_lockfile};
pub use self::cargo_generate_lockfile::{update_lockfile};
pub use self::cargo_generate_lockfile::UpdateOptions;
pub use self::lockfile::{load_pkg_lockfile, write_pkg_lockfile};
pub use self::cargo_test::{run_tests, run_benches, TestOptions};
pub use self::cargo_package::package;
pub use self::registry::{publish, registry_configuration, RegistryConfig};
pub use self::registry::{registry_login, search, http_proxy_exists, http_handle};
pub use self::registry::{modify_owners, yank, OwnersOptions};
pub use self::cargo_fetch::{fetch, get_resolved_packages};
pub use self::cargo_pkgid::pkgid;
pub use self::resolve::{resolve_pkg, resolve_with_previous};
pub use self::cargo_output_metadata::{output_metadata, OutputMetadataOptions, ExportInfo};
mod cargo_clean;
mod cargo_compile;
mod cargo_doc;
mod cargo_fetch;
mod cargo_generate_lockfile;
mod cargo_install;
mod cargo_new;
mod cargo_output_metadata;
mod cargo_package;
mod cargo_pkgid;
mod cargo_read_manifest;
mod cargo_run;
mod cargo_rustc;
mod cargo_test;
mod lockfile;
mod registry;
mod resolve;
|
pub use self::cargo_compile::{CompileFilter, CompileMode};
pub use self::cargo_read_manifest::{read_manifest,read_package,read_packages};
pub use self::cargo_rustc::{compile_targets, Compilation, Layout, Kind, Unit};
|
random_line_split
|
mod.rs
|
mod square;
use gameboy::apu::square::SquareChannel;
const AUDIO_BUFFER_LENGTH: usize = 8192;
pub struct APU {
audio_buffer: Box<[f32]>,
buffer_index: usize,
counter: u32, /* Increments at 4.2 Mhz */
timer: u32, /* Increments at 512 Hz*/
sample_rate: u32, /* Sample per second (Hz) */
square_1: SquareChannel,
square_2: SquareChannel,
}
impl APU {
pub fn new() -> APU {
let buff: [f32; AUDIO_BUFFER_LENGTH] = [0.0_f32; AUDIO_BUFFER_LENGTH];
APU {
audio_buffer: Box::new(buff),
buffer_index: 0,
counter: 0,
timer: 0,
sample_rate: 41000,
square_1: SquareChannel::new(),
square_2: SquareChannel::new(),
}
}
///Get the content of the audio buffer as a slice.
///It's assumed that the caller will copy the data.
pub fn get_audio_buffer(&mut self) -> &[f32] {
let index = self.buffer_index;
self.buffer_index = 0;
&self.audio_buffer[0..index]
}
pub fn emulate_hardware(&mut self, double_speed_mode: bool, div: u16, last_div: u16) {
/*
From what i understand the sound clock is actually the cpu clock divided by 8192
(16,384 in double speed mode) which equals ~512 Hz.
http://gbdev.gg8.se/wiki/articles/Timer_Obscure_Behaviour
*/
if double_speed_mode {
self.counter = self.counter.wrapping_add(2);
}
else {
self.counter = self.counter.wrapping_add(4);
}
/* sample at 512 Hz */
if self.counter % 8192 == 0 {
self.timer = self.timer.wrapping_add(1);
|
let base_time = (self.timer as f32) / 512.0_f32;
let sample_count = self.sample_rate / 512; /* 1 sound frame is 1/512 second */
let samples_generated = self.square_2.sample(
&mut self.audio_buffer[self.buffer_index.. AUDIO_BUFFER_LENGTH],
self.sample_rate,
sample_count,
base_time,
1.0_f32
);
self.buffer_index += samples_generated;
}
/* Falling edge detector for 512 Hz timer driven by divider register */
if (double_speed_mode && (last_div & 16384 == 16) && (div & 16384 == 0)) ||
((double_speed_mode == false) && (last_div & 8192 == 8192) && (div & 8192 == 0)) {
self.square_1.step();
self.square_2.step();
}
}
///Write a byte to the sound registers
///The sound registers are mapped to 0xFF10 - 0xFF3F
///Panics if address is out of range
pub fn write_to_sound_registers(&mut self, io: &mut[u8], address: u16, value: u8) {
match address {
0xFF10...0xFF3F => {
io[(address as usize) - 0xFF10] = value;
match address {
/* Square 1 */
0xFF10 => {
/* NR10: Sweep period, negate, shift */
},
0xFF11 => {
/* NR11: Duty, Length load (64-L) */
//TODO: duty
self.square_1.length = (value & 63) as i8;
},
0xFF12 => {
/* NR12: Starting volume, envelope add mode, period */
self.square_1.set_envelope(value);
},
0xFF13 => {
/* NR13: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_1.frequency = x;
},
0xFF14 => {
/* NR14: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_1.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_1.frequency = x;
},
/* Square 2 */
0xFF16 => {
/* NR21: Duty, Length load (64 - L) */
//TODO: duty
self.square_2.length = (value & 63) as i8;
},
0xFF17 => {
/* NR22: Starting volume, Envelope add mode, period */
self.square_2.set_envelope(value);
},
0xFF18 => {
/* NR23: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_2.frequency = x;
},
0xFF19 => {
/* NR24: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_2.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_2.frequency = x;
},
/* Control registers */
0xFF24 => {
/* NR50: Channel control, on-off, volume */
}
_ => {}
};
}
_ => {
println!("Attempted to write value {} to address {:#4X}.", value, address);
panic!("Invalid address, address must be in the range [0xFF10 - 0xFF3F].")
},
};
}
///Read from the sound registers (0xFF10...0xFF35)
pub fn read_from_sound_registers(&self, io: &[u8], address: u16) -> u8 {
/* TODO */
match address {
_ => 0xFF
}
}
}
|
random_line_split
|
|
mod.rs
|
mod square;
use gameboy::apu::square::SquareChannel;
const AUDIO_BUFFER_LENGTH: usize = 8192;
pub struct APU {
audio_buffer: Box<[f32]>,
buffer_index: usize,
counter: u32, /* Increments at 4.2 Mhz */
timer: u32, /* Increments at 512 Hz*/
sample_rate: u32, /* Sample per second (Hz) */
square_1: SquareChannel,
square_2: SquareChannel,
}
impl APU {
pub fn new() -> APU {
let buff: [f32; AUDIO_BUFFER_LENGTH] = [0.0_f32; AUDIO_BUFFER_LENGTH];
APU {
audio_buffer: Box::new(buff),
buffer_index: 0,
counter: 0,
timer: 0,
sample_rate: 41000,
square_1: SquareChannel::new(),
square_2: SquareChannel::new(),
}
}
///Get the content of the audio buffer as a slice.
///It's assumed that the caller will copy the data.
pub fn get_audio_buffer(&mut self) -> &[f32] {
let index = self.buffer_index;
self.buffer_index = 0;
&self.audio_buffer[0..index]
}
pub fn
|
(&mut self, double_speed_mode: bool, div: u16, last_div: u16) {
/*
From what i understand the sound clock is actually the cpu clock divided by 8192
(16,384 in double speed mode) which equals ~512 Hz.
http://gbdev.gg8.se/wiki/articles/Timer_Obscure_Behaviour
*/
if double_speed_mode {
self.counter = self.counter.wrapping_add(2);
}
else {
self.counter = self.counter.wrapping_add(4);
}
/* sample at 512 Hz */
if self.counter % 8192 == 0 {
self.timer = self.timer.wrapping_add(1);
let base_time = (self.timer as f32) / 512.0_f32;
let sample_count = self.sample_rate / 512; /* 1 sound frame is 1/512 second */
let samples_generated = self.square_2.sample(
&mut self.audio_buffer[self.buffer_index.. AUDIO_BUFFER_LENGTH],
self.sample_rate,
sample_count,
base_time,
1.0_f32
);
self.buffer_index += samples_generated;
}
/* Falling edge detector for 512 Hz timer driven by divider register */
if (double_speed_mode && (last_div & 16384 == 16) && (div & 16384 == 0)) ||
((double_speed_mode == false) && (last_div & 8192 == 8192) && (div & 8192 == 0)) {
self.square_1.step();
self.square_2.step();
}
}
///Write a byte to the sound registers
///The sound registers are mapped to 0xFF10 - 0xFF3F
///Panics if address is out of range
pub fn write_to_sound_registers(&mut self, io: &mut[u8], address: u16, value: u8) {
match address {
0xFF10...0xFF3F => {
io[(address as usize) - 0xFF10] = value;
match address {
/* Square 1 */
0xFF10 => {
/* NR10: Sweep period, negate, shift */
},
0xFF11 => {
/* NR11: Duty, Length load (64-L) */
//TODO: duty
self.square_1.length = (value & 63) as i8;
},
0xFF12 => {
/* NR12: Starting volume, envelope add mode, period */
self.square_1.set_envelope(value);
},
0xFF13 => {
/* NR13: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_1.frequency = x;
},
0xFF14 => {
/* NR14: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_1.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_1.frequency = x;
},
/* Square 2 */
0xFF16 => {
/* NR21: Duty, Length load (64 - L) */
//TODO: duty
self.square_2.length = (value & 63) as i8;
},
0xFF17 => {
/* NR22: Starting volume, Envelope add mode, period */
self.square_2.set_envelope(value);
},
0xFF18 => {
/* NR23: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_2.frequency = x;
},
0xFF19 => {
/* NR24: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_2.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_2.frequency = x;
},
/* Control registers */
0xFF24 => {
/* NR50: Channel control, on-off, volume */
}
_ => {}
};
}
_ => {
println!("Attempted to write value {} to address {:#4X}.", value, address);
panic!("Invalid address, address must be in the range [0xFF10 - 0xFF3F].")
},
};
}
///Read from the sound registers (0xFF10...0xFF35)
pub fn read_from_sound_registers(&self, io: &[u8], address: u16) -> u8 {
/* TODO */
match address {
_ => 0xFF
}
}
}
|
emulate_hardware
|
identifier_name
|
mod.rs
|
mod square;
use gameboy::apu::square::SquareChannel;
const AUDIO_BUFFER_LENGTH: usize = 8192;
pub struct APU {
audio_buffer: Box<[f32]>,
buffer_index: usize,
counter: u32, /* Increments at 4.2 Mhz */
timer: u32, /* Increments at 512 Hz*/
sample_rate: u32, /* Sample per second (Hz) */
square_1: SquareChannel,
square_2: SquareChannel,
}
impl APU {
pub fn new() -> APU {
let buff: [f32; AUDIO_BUFFER_LENGTH] = [0.0_f32; AUDIO_BUFFER_LENGTH];
APU {
audio_buffer: Box::new(buff),
buffer_index: 0,
counter: 0,
timer: 0,
sample_rate: 41000,
square_1: SquareChannel::new(),
square_2: SquareChannel::new(),
}
}
///Get the content of the audio buffer as a slice.
///It's assumed that the caller will copy the data.
pub fn get_audio_buffer(&mut self) -> &[f32] {
let index = self.buffer_index;
self.buffer_index = 0;
&self.audio_buffer[0..index]
}
pub fn emulate_hardware(&mut self, double_speed_mode: bool, div: u16, last_div: u16)
|
let samples_generated = self.square_2.sample(
&mut self.audio_buffer[self.buffer_index.. AUDIO_BUFFER_LENGTH],
self.sample_rate,
sample_count,
base_time,
1.0_f32
);
self.buffer_index += samples_generated;
}
/* Falling edge detector for 512 Hz timer driven by divider register */
if (double_speed_mode && (last_div & 16384 == 16) && (div & 16384 == 0)) ||
((double_speed_mode == false) && (last_div & 8192 == 8192) && (div & 8192 == 0)) {
self.square_1.step();
self.square_2.step();
}
}
///Write a byte to the sound registers
///The sound registers are mapped to 0xFF10 - 0xFF3F
///Panics if address is out of range
pub fn write_to_sound_registers(&mut self, io: &mut[u8], address: u16, value: u8) {
match address {
0xFF10...0xFF3F => {
io[(address as usize) - 0xFF10] = value;
match address {
/* Square 1 */
0xFF10 => {
/* NR10: Sweep period, negate, shift */
},
0xFF11 => {
/* NR11: Duty, Length load (64-L) */
//TODO: duty
self.square_1.length = (value & 63) as i8;
},
0xFF12 => {
/* NR12: Starting volume, envelope add mode, period */
self.square_1.set_envelope(value);
},
0xFF13 => {
/* NR13: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_1.frequency = x;
},
0xFF14 => {
/* NR14: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_1.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_1.frequency = x;
},
/* Square 2 */
0xFF16 => {
/* NR21: Duty, Length load (64 - L) */
//TODO: duty
self.square_2.length = (value & 63) as i8;
},
0xFF17 => {
/* NR22: Starting volume, Envelope add mode, period */
self.square_2.set_envelope(value);
},
0xFF18 => {
/* NR23: Frequency lsb */
let x: u16 = (value as u16) | (((io[0x14] & 7) as u16) << 8);
self.square_2.frequency = x;
},
0xFF19 => {
/* NR24: Trigger, length enable, frequency msb */
//TODO: trigger
self.square_2.length_enable = value & 64 == 1;
let x: u16 = (((value & 7) as u16) << 8) | (io[0x13] as u16);
self.square_2.frequency = x;
},
/* Control registers */
0xFF24 => {
/* NR50: Channel control, on-off, volume */
}
_ => {}
};
}
_ => {
println!("Attempted to write value {} to address {:#4X}.", value, address);
panic!("Invalid address, address must be in the range [0xFF10 - 0xFF3F].")
},
};
}
///Read from the sound registers (0xFF10...0xFF35)
pub fn read_from_sound_registers(&self, io: &[u8], address: u16) -> u8 {
/* TODO */
match address {
_ => 0xFF
}
}
}
|
{
/*
From what i understand the sound clock is actually the cpu clock divided by 8192
(16,384 in double speed mode) which equals ~512 Hz.
http://gbdev.gg8.se/wiki/articles/Timer_Obscure_Behaviour
*/
if double_speed_mode {
self.counter = self.counter.wrapping_add(2);
}
else {
self.counter = self.counter.wrapping_add(4);
}
/* sample at 512 Hz */
if self.counter % 8192 == 0 {
self.timer = self.timer.wrapping_add(1);
let base_time = (self.timer as f32) / 512.0_f32;
let sample_count = self.sample_rate / 512; /* 1 sound frame is 1/512 second */
|
identifier_body
|
issue-23433.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.
// Don't fail if we encounter a NonZero<*T> where T is an unsized type
#![feature(unique)]
use std::ptr::Unique;
fn
|
() {
let mut a = [0u8; 5];
let b: Option<Unique<[u8]>> = unsafe { Some(Unique::new(&mut a)) };
match b {
Some(_) => println!("Got `Some`"),
None => panic!("Unexpected `None`"),
}
}
|
main
|
identifier_name
|
issue-23433.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.
// Don't fail if we encounter a NonZero<*T> where T is an unsized type
#![feature(unique)]
use std::ptr::Unique;
fn main()
|
{
let mut a = [0u8; 5];
let b: Option<Unique<[u8]>> = unsafe { Some(Unique::new(&mut a)) };
match b {
Some(_) => println!("Got `Some`"),
None => panic!("Unexpected `None`"),
}
}
|
identifier_body
|
|
issue-23433.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.
// Don't fail if we encounter a NonZero<*T> where T is an unsized type
#![feature(unique)]
use std::ptr::Unique;
fn main() {
let mut a = [0u8; 5];
let b: Option<Unique<[u8]>> = unsafe { Some(Unique::new(&mut a)) };
|
None => panic!("Unexpected `None`"),
}
}
|
match b {
Some(_) => println!("Got `Some`"),
|
random_line_split
|
extra_assertions.rs
|
//! Macros for defining extra assertions that should only be checked in testing
//! and/or CI when the `testing_only_extra_assertions` feature is enabled.
/// Simple macro that forwards to assert! when using
/// testing_only_extra_assertions.
#[macro_export]
macro_rules! extra_assert {
( $cond:expr ) => {
if cfg!(feature = "testing_only_extra_assertions") {
assert!($cond);
}
};
( $cond:expr, $( $arg:tt )+ ) => {
if cfg!(feature = "testing_only_extra_assertions") {
assert!($cond, $( $arg )* )
}
};
}
/// Simple macro that forwards to assert_eq! when using
/// testing_only_extra_assertions.
#[macro_export]
macro_rules! extra_assert_eq {
|
( $lhs:expr, $rhs:expr, $( $arg:tt )+ ) => {
if cfg!(feature = "testing_only_extra_assertions") {
assert!($lhs, $rhs, $( $arg )* );
}
};
}
|
( $lhs:expr , $rhs:expr ) => {
if cfg!(feature = "testing_only_extra_assertions") {
assert_eq!($lhs, $rhs);
}
};
|
random_line_split
|
backtrace.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32 FIXME #13259
extern crate native;
use std::os;
use std::io::process::Command;
use std::finally::Finally;
use std::str;
#[start]
fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) }
#[inline(never)]
fn
|
() {
fail!()
}
#[inline(never)]
fn double() {
(|| {
fail!("once");
}).finally(|| {
fail!("twice");
})
}
fn runtest(me: &str) {
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
(k.to_string(), v.to_string())
}).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
None => {}
}
env.push(("RUST_BACKTRACE".to_string(), "1".to_string()));
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("foo::h"),
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(!s.contains("stack backtrace") &&!s.contains("foo::h"),
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("double::h"),
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Command::new(me).arg("double-fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
let mut i = 0;
for _ in range(0, 2) {
i += s.slice_from(i + 10).find_str("stack backtrace").unwrap() + 10;
}
assert!(s.slice_from(i + 10).find_str("stack backtrace").is_none(),
"bad output4: {}", s);
}
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1].as_slice() == "fail" {
foo();
} else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
double();
} else {
runtest(args[0].as_slice());
}
}
|
foo
|
identifier_name
|
backtrace.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32 FIXME #13259
extern crate native;
use std::os;
use std::io::process::Command;
use std::finally::Finally;
use std::str;
#[start]
fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) }
#[inline(never)]
fn foo() {
fail!()
}
#[inline(never)]
fn double() {
(|| {
fail!("once");
}).finally(|| {
fail!("twice");
})
}
fn runtest(me: &str) {
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
|
None => {}
}
env.push(("RUST_BACKTRACE".to_string(), "1".to_string()));
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("foo::h"),
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(!s.contains("stack backtrace") &&!s.contains("foo::h"),
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("double::h"),
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Command::new(me).arg("double-fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
let mut i = 0;
for _ in range(0, 2) {
i += s.slice_from(i + 10).find_str("stack backtrace").unwrap() + 10;
}
assert!(s.slice_from(i + 10).find_str("stack backtrace").is_none(),
"bad output4: {}", s);
}
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1].as_slice() == "fail" {
foo();
} else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
double();
} else {
runtest(args[0].as_slice());
}
}
|
(k.to_string(), v.to_string())
}).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
|
random_line_split
|
backtrace.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32 FIXME #13259
extern crate native;
use std::os;
use std::io::process::Command;
use std::finally::Finally;
use std::str;
#[start]
fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) }
#[inline(never)]
fn foo() {
fail!()
}
#[inline(never)]
fn double()
|
fn runtest(me: &str) {
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
(k.to_string(), v.to_string())
}).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
None => {}
}
env.push(("RUST_BACKTRACE".to_string(), "1".to_string()));
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("foo::h"),
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(!s.contains("stack backtrace") &&!s.contains("foo::h"),
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("double::h"),
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Command::new(me).arg("double-fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
let mut i = 0;
for _ in range(0, 2) {
i += s.slice_from(i + 10).find_str("stack backtrace").unwrap() + 10;
}
assert!(s.slice_from(i + 10).find_str("stack backtrace").is_none(),
"bad output4: {}", s);
}
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1].as_slice() == "fail" {
foo();
} else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
double();
} else {
runtest(args[0].as_slice());
}
}
|
{
(|| {
fail!("once");
}).finally(|| {
fail!("twice");
})
}
|
identifier_body
|
backtrace.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32 FIXME #13259
extern crate native;
use std::os;
use std::io::process::Command;
use std::finally::Finally;
use std::str;
#[start]
fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) }
#[inline(never)]
fn foo() {
fail!()
}
#[inline(never)]
fn double() {
(|| {
fail!("once");
}).finally(|| {
fail!("twice");
})
}
fn runtest(me: &str) {
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
(k.to_string(), v.to_string())
}).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
None => {}
}
env.push(("RUST_BACKTRACE".to_string(), "1".to_string()));
// Make sure that the stack trace is printed
let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("foo::h"),
"bad output: {}", s);
// Make sure the stack trace is *not* printed
let mut p = Command::new(me).arg("fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(!s.contains("stack backtrace") &&!s.contains("foo::h"),
"bad output2: {}", s);
// Make sure a stack trace is printed
let mut p = Command::new(me).arg("double-fail").spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
assert!(s.contains("stack backtrace") && s.contains("double::h"),
"bad output3: {}", s);
// Make sure a stack trace isn't printed too many times
let mut p = Command::new(me).arg("double-fail").env(env.as_slice()).spawn().unwrap();
let out = p.wait_with_output().unwrap();
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
let mut i = 0;
for _ in range(0, 2) {
i += s.slice_from(i + 10).find_str("stack backtrace").unwrap() + 10;
}
assert!(s.slice_from(i + 10).find_str("stack backtrace").is_none(),
"bad output4: {}", s);
}
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() >= 2 && args[1].as_slice() == "fail" {
foo();
} else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
double();
} else
|
}
|
{
runtest(args[0].as_slice());
}
|
conditional_block
|
point_bounding_sphere.rs
|
use na::{Identity, Transform};
use point::PointQuery;
use entities::shape::Ball;
use entities::bounding_volume::BoundingSphere;
use math::{Scalar, Point, Vect};
impl<P, M> PointQuery<P, M> for BoundingSphere<P>
where P: Point,
M: Transform<P> {
#[inline]
fn
|
(&self, m: &M, pt: &P, solid: bool) -> P {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
let proj = Ball::new(self.radius()).project_point(&Identity::new(), &ls_pt, solid);
m.transform(&proj) + *self.center().as_vec()
}
#[inline]
fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).distance_to_point(&Identity::new(), &ls_pt)
}
#[inline]
fn contains_point(&self, m: &M, pt: &P) -> bool {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).contains_point(&Identity::new(), &ls_pt)
}
}
|
project_point
|
identifier_name
|
point_bounding_sphere.rs
|
use na::{Identity, Transform};
use point::PointQuery;
use entities::shape::Ball;
use entities::bounding_volume::BoundingSphere;
use math::{Scalar, Point, Vect};
impl<P, M> PointQuery<P, M> for BoundingSphere<P>
where P: Point,
M: Transform<P> {
#[inline]
fn project_point(&self, m: &M, pt: &P, solid: bool) -> P {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
let proj = Ball::new(self.radius()).project_point(&Identity::new(), &ls_pt, solid);
m.transform(&proj) + *self.center().as_vec()
}
#[inline]
fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).distance_to_point(&Identity::new(), &ls_pt)
|
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).contains_point(&Identity::new(), &ls_pt)
}
}
|
}
#[inline]
fn contains_point(&self, m: &M, pt: &P) -> bool {
|
random_line_split
|
point_bounding_sphere.rs
|
use na::{Identity, Transform};
use point::PointQuery;
use entities::shape::Ball;
use entities::bounding_volume::BoundingSphere;
use math::{Scalar, Point, Vect};
impl<P, M> PointQuery<P, M> for BoundingSphere<P>
where P: Point,
M: Transform<P> {
#[inline]
fn project_point(&self, m: &M, pt: &P, solid: bool) -> P {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
let proj = Ball::new(self.radius()).project_point(&Identity::new(), &ls_pt, solid);
m.transform(&proj) + *self.center().as_vec()
}
#[inline]
fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar {
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).distance_to_point(&Identity::new(), &ls_pt)
}
#[inline]
fn contains_point(&self, m: &M, pt: &P) -> bool
|
}
|
{
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec());
Ball::new(self.radius()).contains_point(&Identity::new(), &ls_pt)
}
|
identifier_body
|
from.rs
|
header! {
#[doc="`From` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.1)"]
#[doc=""]
#[doc="The `From` header field contains an Internet email address for a"]
#[doc="human user who controls the requesting user agent. The address ought"]
#[doc="to be machine-usable."]
#[doc="# ABNF"]
#[doc="```plain"]
|
#[doc="# Example"]
#[doc="```"]
#[doc="use hyper::header::{Headers, From};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(From(\"[email protected]\".to_owned()));"]
#[doc="```"]
// FIXME: Maybe use mailbox?
(From, "From") => [String]
test_from {
test_header!(test1, vec![b"[email protected]"]);
}
}
|
#[doc="From = mailbox"]
#[doc="mailbox = <mailbox, see [RFC5322], Section 3.4>"]
#[doc="```"]
#[doc=""]
|
random_line_split
|
testcase.rs
|
#[derive(Debug)]
struct I32(i32);
#[derive(Debug)]
struct I64(i64);
// `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are
// determined, `Sum` is known.
trait Add<Rhs> {
type Sum;
// Use `&self` and `&Rhs` so no changes are made to the originals.
// The return shouldn't be a reference.
fn add(&self, rhs: &Rhs) -> Self::Sum;
}
impl Add<I32> for I32 {
type Sum = I32;
fn add(&self, rhs: &I32) -> Self::Sum { I32(self.0 + rhs.0) }
}
impl Add<I64> for I32 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 as i64 + rhs.0) }
}
impl Add<I32> for I64 {
type Sum = I64;
fn add(&self, rhs: &I32) -> Self::Sum { I64(self.0 + rhs.0 as i64) }
}
impl Add<I64> for I64 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 + rhs.0) }
}
fn
|
() {
let i = I32(12);
let j = I64(9);
println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i));
println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j));
println!("{:?} + {:?} = {:?}", &j, &i, j.add(&i));
println!("{:?} + {:?} = {:?}", &j, &j, j.add(&j));
}
|
main
|
identifier_name
|
testcase.rs
|
#[derive(Debug)]
struct I32(i32);
#[derive(Debug)]
struct I64(i64);
// `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are
// determined, `Sum` is known.
trait Add<Rhs> {
type Sum;
// Use `&self` and `&Rhs` so no changes are made to the originals.
// The return shouldn't be a reference.
fn add(&self, rhs: &Rhs) -> Self::Sum;
}
impl Add<I32> for I32 {
type Sum = I32;
fn add(&self, rhs: &I32) -> Self::Sum { I32(self.0 + rhs.0) }
}
impl Add<I64> for I32 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 as i64 + rhs.0) }
}
impl Add<I32> for I64 {
type Sum = I64;
fn add(&self, rhs: &I32) -> Self::Sum { I64(self.0 + rhs.0 as i64) }
}
impl Add<I64> for I64 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 + rhs.0) }
}
|
println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j));
println!("{:?} + {:?} = {:?}", &j, &i, j.add(&i));
println!("{:?} + {:?} = {:?}", &j, &j, j.add(&j));
}
|
fn main() {
let i = I32(12);
let j = I64(9);
println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i));
|
random_line_split
|
testcase.rs
|
#[derive(Debug)]
struct I32(i32);
#[derive(Debug)]
struct I64(i64);
// `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are
// determined, `Sum` is known.
trait Add<Rhs> {
type Sum;
// Use `&self` and `&Rhs` so no changes are made to the originals.
// The return shouldn't be a reference.
fn add(&self, rhs: &Rhs) -> Self::Sum;
}
impl Add<I32> for I32 {
type Sum = I32;
fn add(&self, rhs: &I32) -> Self::Sum { I32(self.0 + rhs.0) }
}
impl Add<I64> for I32 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 as i64 + rhs.0) }
}
impl Add<I32> for I64 {
type Sum = I64;
fn add(&self, rhs: &I32) -> Self::Sum
|
}
impl Add<I64> for I64 {
type Sum = I64;
fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 + rhs.0) }
}
fn main() {
let i = I32(12);
let j = I64(9);
println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i));
println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j));
println!("{:?} + {:?} = {:?}", &j, &i, j.add(&i));
println!("{:?} + {:?} = {:?}", &j, &j, j.add(&j));
}
|
{ I64(self.0 + rhs.0 as i64) }
|
identifier_body
|
create_state_event_for_key.rs
|
//! [PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}](https://matrix.org/docs/spec/client_server/r0.6.0#put-matrix-client-r0-rooms-roomid-state-eventtype-statekey)
use ruma_api::ruma_api;
use ruma_events::EventType;
use ruma_identifiers::{EventId, RoomId};
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata {
description: "Send a state event to a room associated with a given state key.",
method: PUT,
name: "create_state_event_for_key",
path: "/_matrix/client/r0/rooms/:room_id/state/:event_type/:state_key",
rate_limited: false,
requires_authentication: true,
}
request {
/// The room to set the state in.
#[ruma_api(path)]
pub room_id: RoomId,
/// The type of event to send.
#[ruma_api(path)]
pub event_type: EventType,
|
/// The state_key for the state to send. Defaults to the empty string.
#[ruma_api(path)]
pub state_key: String,
/// The event's content. The type for this field will be updated in a
/// future release, until then you can create a value using
/// `serde_json::value::to_raw_value`.
#[ruma_api(body)]
pub data: Box<RawJsonValue>,
}
response {
/// A unique identifier for the event.
// This is not declared required in r0.6.0, but that was a bug that has now been fixed:
// https://github.com/matrix-org/matrix-doc/pull/2525
pub event_id: EventId,
}
error: crate::Error
}
|
random_line_split
|
|
mod.rs
|
#![cfg(any(target_os = "linux", target_os = "freebsd"))]
#![allow(unused_variables, dead_code)]
use libc;
use api::osmesa::{OsMesaContext, OsMesaCreationError};
use Api;
use ContextError;
use CreationError;
use Event;
use GlAttributes;
use GlContext;
use PixelFormat;
use PixelFormatRequirements;
use CursorState;
use MouseCursor;
use WindowAttributes;
use std::collections::VecDeque;
use std::path::Path;
use std::ptr;
mod ffi;
pub struct Window {
libcaca: ffi::LibCaca,
display: *mut ffi::caca_display_t,
opengl: OsMesaContext,
dither: *mut ffi::caca_dither_t,
}
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
#[inline]
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
pub struct MonitorId;
#[inline]
pub fn get_available_monitors() -> VecDeque<MonitorId> {
VecDeque::new()
}
#[inline]
pub fn get_primary_monitor() -> MonitorId {
MonitorId
}
impl MonitorId {
#[inline]
pub fn get_name(&self) -> Option<String> {
unimplemented!();
}
#[inline]
pub fn get_native_identifier(&self) -> ::native_monitor::NativeMonitorId {
::native_monitor::NativeMonitorId::Unavailable
}
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!();
}
}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
None
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
loop {}
}
}
impl Window {
pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|w| &w.opengl);
let opengl = match OsMesaContext::new(window.dimensions.unwrap_or((800, 600)), pf_reqs,
&opengl)
{
Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported),
Err(OsMesaCreationError::CreationError(e)) => return Err(e),
Ok(c) => c
};
let opengl_dimensions = opengl.get_dimensions();
let libcaca = match ffi::LibCaca::open(&Path::new("libcaca.so.0")) {
Err(_) => return Err(CreationError::NotSupported),
Ok(l) => l
};
let display = unsafe { (libcaca.caca_create_display)(ptr::null_mut()) };
if display.is_null() {
return Err(CreationError::OsError("caca_create_display failed".to_string()));
}
let dither = unsafe {
#[cfg(target_endian = "little")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff, 0xff00, 0xff0000, 0xff000000) }
#[cfg(target_endian = "big")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff000000, 0xff0000, 0xff00, 0xff) }
let masks = get_masks();
(libcaca.caca_create_dither)(32, opengl_dimensions.0 as libc::c_int,
opengl_dimensions.1 as libc::c_int,
opengl_dimensions.0 as libc::c_int * 4,
masks.0, masks.1, masks.2, masks.3)
};
if dither.is_null() {
unsafe { (libcaca.caca_free_display)(display) };
return Err(CreationError::OsError("caca_create_dither failed".to_string()));
}
Ok(Window {
libcaca: libcaca,
display: display,
opengl: opengl,
dither: dither,
})
}
#[inline]
pub fn set_title(&self, title: &str) {
}
#[inline]
pub fn show(&self) {
}
#[inline]
pub fn hide(&self) {
}
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
unimplemented!()
}
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
}
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
Some(self.opengl.get_dimensions())
}
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
#[inline]
pub fn set_inner_size(&self, _x: u32, _y: u32) {
unimplemented!()
}
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
unimplemented!()
}
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
#[inline]
pub fn platform_display(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
unimplemented!();
}
#[inline]
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
#[inline]
pub fn set_cursor(&self, cursor: MouseCursor) {
}
#[inline]
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
Ok(())
}
#[inline]
pub fn hidpi_factor(&self) -> f32 {
1.0
}
#[inline]
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
Ok(())
}
}
impl GlContext for Window {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.opengl.make_current()
}
|
#[inline]
fn is_current(&self) -> bool {
self.opengl.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.opengl.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
unsafe {
let canvas = (self.libcaca.caca_get_canvas)(self.display);
let width = (self.libcaca.caca_get_canvas_width)(canvas);
let height = (self.libcaca.caca_get_canvas_height)(canvas);
let buffer = self.opengl.get_framebuffer().chunks(self.opengl.get_dimensions().0 as usize)
.flat_map(|i| i.iter().cloned()).rev().collect::<Vec<u32>>();
(self.libcaca.caca_dither_bitmap)(canvas, 0, 0, width as libc::c_int,
height as libc::c_int, self.dither,
buffer.as_ptr() as *const _);
(self.libcaca.caca_refresh_display)(self.display);
};
Ok(())
}
#[inline]
fn get_api(&self) -> Api {
self.opengl.get_api()
}
#[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.opengl.get_pixel_format()
}
}
impl Drop for Window {
#[inline]
fn drop(&mut self) {
unsafe {
(self.libcaca.caca_free_dither)(self.dither);
(self.libcaca.caca_free_display)(self.display);
}
}
}
|
random_line_split
|
|
mod.rs
|
#![cfg(any(target_os = "linux", target_os = "freebsd"))]
#![allow(unused_variables, dead_code)]
use libc;
use api::osmesa::{OsMesaContext, OsMesaCreationError};
use Api;
use ContextError;
use CreationError;
use Event;
use GlAttributes;
use GlContext;
use PixelFormat;
use PixelFormatRequirements;
use CursorState;
use MouseCursor;
use WindowAttributes;
use std::collections::VecDeque;
use std::path::Path;
use std::ptr;
mod ffi;
pub struct Window {
libcaca: ffi::LibCaca,
display: *mut ffi::caca_display_t,
opengl: OsMesaContext,
dither: *mut ffi::caca_dither_t,
}
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
#[inline]
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
pub struct MonitorId;
#[inline]
pub fn get_available_monitors() -> VecDeque<MonitorId> {
VecDeque::new()
}
#[inline]
pub fn get_primary_monitor() -> MonitorId {
MonitorId
}
impl MonitorId {
#[inline]
pub fn get_name(&self) -> Option<String> {
unimplemented!();
}
#[inline]
pub fn get_native_identifier(&self) -> ::native_monitor::NativeMonitorId {
::native_monitor::NativeMonitorId::Unavailable
}
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!();
}
}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
None
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
loop {}
}
}
impl Window {
pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|w| &w.opengl);
let opengl = match OsMesaContext::new(window.dimensions.unwrap_or((800, 600)), pf_reqs,
&opengl)
{
Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported),
Err(OsMesaCreationError::CreationError(e)) => return Err(e),
Ok(c) => c
};
let opengl_dimensions = opengl.get_dimensions();
let libcaca = match ffi::LibCaca::open(&Path::new("libcaca.so.0")) {
Err(_) => return Err(CreationError::NotSupported),
Ok(l) => l
};
let display = unsafe { (libcaca.caca_create_display)(ptr::null_mut()) };
if display.is_null() {
return Err(CreationError::OsError("caca_create_display failed".to_string()));
}
let dither = unsafe {
#[cfg(target_endian = "little")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff, 0xff00, 0xff0000, 0xff000000) }
#[cfg(target_endian = "big")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff000000, 0xff0000, 0xff00, 0xff) }
let masks = get_masks();
(libcaca.caca_create_dither)(32, opengl_dimensions.0 as libc::c_int,
opengl_dimensions.1 as libc::c_int,
opengl_dimensions.0 as libc::c_int * 4,
masks.0, masks.1, masks.2, masks.3)
};
if dither.is_null() {
unsafe { (libcaca.caca_free_display)(display) };
return Err(CreationError::OsError("caca_create_dither failed".to_string()));
}
Ok(Window {
libcaca: libcaca,
display: display,
opengl: opengl,
dither: dither,
})
}
#[inline]
pub fn set_title(&self, title: &str) {
}
#[inline]
pub fn show(&self) {
}
#[inline]
pub fn hide(&self) {
}
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
unimplemented!()
}
#[inline]
pub fn set_position(&self, x: i32, y: i32)
|
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
Some(self.opengl.get_dimensions())
}
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
#[inline]
pub fn set_inner_size(&self, _x: u32, _y: u32) {
unimplemented!()
}
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
unimplemented!()
}
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
#[inline]
pub fn platform_display(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
unimplemented!();
}
#[inline]
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
#[inline]
pub fn set_cursor(&self, cursor: MouseCursor) {
}
#[inline]
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
Ok(())
}
#[inline]
pub fn hidpi_factor(&self) -> f32 {
1.0
}
#[inline]
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
Ok(())
}
}
impl GlContext for Window {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.opengl.make_current()
}
#[inline]
fn is_current(&self) -> bool {
self.opengl.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.opengl.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
unsafe {
let canvas = (self.libcaca.caca_get_canvas)(self.display);
let width = (self.libcaca.caca_get_canvas_width)(canvas);
let height = (self.libcaca.caca_get_canvas_height)(canvas);
let buffer = self.opengl.get_framebuffer().chunks(self.opengl.get_dimensions().0 as usize)
.flat_map(|i| i.iter().cloned()).rev().collect::<Vec<u32>>();
(self.libcaca.caca_dither_bitmap)(canvas, 0, 0, width as libc::c_int,
height as libc::c_int, self.dither,
buffer.as_ptr() as *const _);
(self.libcaca.caca_refresh_display)(self.display);
};
Ok(())
}
#[inline]
fn get_api(&self) -> Api {
self.opengl.get_api()
}
#[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.opengl.get_pixel_format()
}
}
impl Drop for Window {
#[inline]
fn drop(&mut self) {
unsafe {
(self.libcaca.caca_free_dither)(self.dither);
(self.libcaca.caca_free_display)(self.display);
}
}
}
|
{
}
|
identifier_body
|
mod.rs
|
#![cfg(any(target_os = "linux", target_os = "freebsd"))]
#![allow(unused_variables, dead_code)]
use libc;
use api::osmesa::{OsMesaContext, OsMesaCreationError};
use Api;
use ContextError;
use CreationError;
use Event;
use GlAttributes;
use GlContext;
use PixelFormat;
use PixelFormatRequirements;
use CursorState;
use MouseCursor;
use WindowAttributes;
use std::collections::VecDeque;
use std::path::Path;
use std::ptr;
mod ffi;
pub struct Window {
libcaca: ffi::LibCaca,
display: *mut ffi::caca_display_t,
opengl: OsMesaContext,
dither: *mut ffi::caca_dither_t,
}
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
#[inline]
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
pub struct MonitorId;
#[inline]
pub fn get_available_monitors() -> VecDeque<MonitorId> {
VecDeque::new()
}
#[inline]
pub fn
|
() -> MonitorId {
MonitorId
}
impl MonitorId {
#[inline]
pub fn get_name(&self) -> Option<String> {
unimplemented!();
}
#[inline]
pub fn get_native_identifier(&self) -> ::native_monitor::NativeMonitorId {
::native_monitor::NativeMonitorId::Unavailable
}
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!();
}
}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
None
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
loop {}
}
}
impl Window {
pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|w| &w.opengl);
let opengl = match OsMesaContext::new(window.dimensions.unwrap_or((800, 600)), pf_reqs,
&opengl)
{
Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported),
Err(OsMesaCreationError::CreationError(e)) => return Err(e),
Ok(c) => c
};
let opengl_dimensions = opengl.get_dimensions();
let libcaca = match ffi::LibCaca::open(&Path::new("libcaca.so.0")) {
Err(_) => return Err(CreationError::NotSupported),
Ok(l) => l
};
let display = unsafe { (libcaca.caca_create_display)(ptr::null_mut()) };
if display.is_null() {
return Err(CreationError::OsError("caca_create_display failed".to_string()));
}
let dither = unsafe {
#[cfg(target_endian = "little")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff, 0xff00, 0xff0000, 0xff000000) }
#[cfg(target_endian = "big")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff000000, 0xff0000, 0xff00, 0xff) }
let masks = get_masks();
(libcaca.caca_create_dither)(32, opengl_dimensions.0 as libc::c_int,
opengl_dimensions.1 as libc::c_int,
opengl_dimensions.0 as libc::c_int * 4,
masks.0, masks.1, masks.2, masks.3)
};
if dither.is_null() {
unsafe { (libcaca.caca_free_display)(display) };
return Err(CreationError::OsError("caca_create_dither failed".to_string()));
}
Ok(Window {
libcaca: libcaca,
display: display,
opengl: opengl,
dither: dither,
})
}
#[inline]
pub fn set_title(&self, title: &str) {
}
#[inline]
pub fn show(&self) {
}
#[inline]
pub fn hide(&self) {
}
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
unimplemented!()
}
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
}
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
Some(self.opengl.get_dimensions())
}
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
#[inline]
pub fn set_inner_size(&self, _x: u32, _y: u32) {
unimplemented!()
}
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
unimplemented!()
}
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
#[inline]
pub fn platform_display(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
unimplemented!();
}
#[inline]
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
#[inline]
pub fn set_cursor(&self, cursor: MouseCursor) {
}
#[inline]
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
Ok(())
}
#[inline]
pub fn hidpi_factor(&self) -> f32 {
1.0
}
#[inline]
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
Ok(())
}
}
impl GlContext for Window {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.opengl.make_current()
}
#[inline]
fn is_current(&self) -> bool {
self.opengl.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.opengl.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
unsafe {
let canvas = (self.libcaca.caca_get_canvas)(self.display);
let width = (self.libcaca.caca_get_canvas_width)(canvas);
let height = (self.libcaca.caca_get_canvas_height)(canvas);
let buffer = self.opengl.get_framebuffer().chunks(self.opengl.get_dimensions().0 as usize)
.flat_map(|i| i.iter().cloned()).rev().collect::<Vec<u32>>();
(self.libcaca.caca_dither_bitmap)(canvas, 0, 0, width as libc::c_int,
height as libc::c_int, self.dither,
buffer.as_ptr() as *const _);
(self.libcaca.caca_refresh_display)(self.display);
};
Ok(())
}
#[inline]
fn get_api(&self) -> Api {
self.opengl.get_api()
}
#[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.opengl.get_pixel_format()
}
}
impl Drop for Window {
#[inline]
fn drop(&mut self) {
unsafe {
(self.libcaca.caca_free_dither)(self.dither);
(self.libcaca.caca_free_display)(self.display);
}
}
}
|
get_primary_monitor
|
identifier_name
|
mod.rs
|
#![cfg(any(target_os = "linux", target_os = "freebsd"))]
#![allow(unused_variables, dead_code)]
use libc;
use api::osmesa::{OsMesaContext, OsMesaCreationError};
use Api;
use ContextError;
use CreationError;
use Event;
use GlAttributes;
use GlContext;
use PixelFormat;
use PixelFormatRequirements;
use CursorState;
use MouseCursor;
use WindowAttributes;
use std::collections::VecDeque;
use std::path::Path;
use std::ptr;
mod ffi;
pub struct Window {
libcaca: ffi::LibCaca,
display: *mut ffi::caca_display_t,
opengl: OsMesaContext,
dither: *mut ffi::caca_dither_t,
}
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
#[inline]
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
pub struct MonitorId;
#[inline]
pub fn get_available_monitors() -> VecDeque<MonitorId> {
VecDeque::new()
}
#[inline]
pub fn get_primary_monitor() -> MonitorId {
MonitorId
}
impl MonitorId {
#[inline]
pub fn get_name(&self) -> Option<String> {
unimplemented!();
}
#[inline]
pub fn get_native_identifier(&self) -> ::native_monitor::NativeMonitorId {
::native_monitor::NativeMonitorId::Unavailable
}
#[inline]
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!();
}
}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
None
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
loop {}
}
}
impl Window {
pub fn new(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<&Window>) -> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|w| &w.opengl);
let opengl = match OsMesaContext::new(window.dimensions.unwrap_or((800, 600)), pf_reqs,
&opengl)
{
Err(OsMesaCreationError::NotSupported) => return Err(CreationError::NotSupported),
Err(OsMesaCreationError::CreationError(e)) => return Err(e),
Ok(c) => c
};
let opengl_dimensions = opengl.get_dimensions();
let libcaca = match ffi::LibCaca::open(&Path::new("libcaca.so.0")) {
Err(_) => return Err(CreationError::NotSupported),
Ok(l) => l
};
let display = unsafe { (libcaca.caca_create_display)(ptr::null_mut()) };
if display.is_null() {
return Err(CreationError::OsError("caca_create_display failed".to_string()));
}
let dither = unsafe {
#[cfg(target_endian = "little")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff, 0xff00, 0xff0000, 0xff000000) }
#[cfg(target_endian = "big")]
fn get_masks() -> (u32, u32, u32, u32) { (0xff000000, 0xff0000, 0xff00, 0xff) }
let masks = get_masks();
(libcaca.caca_create_dither)(32, opengl_dimensions.0 as libc::c_int,
opengl_dimensions.1 as libc::c_int,
opengl_dimensions.0 as libc::c_int * 4,
masks.0, masks.1, masks.2, masks.3)
};
if dither.is_null()
|
Ok(Window {
libcaca: libcaca,
display: display,
opengl: opengl,
dither: dither,
})
}
#[inline]
pub fn set_title(&self, title: &str) {
}
#[inline]
pub fn show(&self) {
}
#[inline]
pub fn hide(&self) {
}
#[inline]
pub fn get_position(&self) -> Option<(i32, i32)> {
unimplemented!()
}
#[inline]
pub fn set_position(&self, x: i32, y: i32) {
}
#[inline]
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
Some(self.opengl.get_dimensions())
}
#[inline]
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
#[inline]
pub fn set_inner_size(&self, _x: u32, _y: u32) {
unimplemented!()
}
#[inline]
pub fn create_window_proxy(&self) -> WindowProxy {
unimplemented!()
}
#[inline]
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
#[inline]
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
#[inline]
pub fn platform_display(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
#[inline]
pub fn get_pixel_format(&self) -> PixelFormat {
unimplemented!();
}
#[inline]
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
#[inline]
pub fn set_cursor(&self, cursor: MouseCursor) {
}
#[inline]
pub fn set_cursor_state(&self, state: CursorState) -> Result<(), String> {
Ok(())
}
#[inline]
pub fn hidpi_factor(&self) -> f32 {
1.0
}
#[inline]
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
Ok(())
}
}
impl GlContext for Window {
#[inline]
unsafe fn make_current(&self) -> Result<(), ContextError> {
self.opengl.make_current()
}
#[inline]
fn is_current(&self) -> bool {
self.opengl.is_current()
}
#[inline]
fn get_proc_address(&self, addr: &str) -> *const () {
self.opengl.get_proc_address(addr)
}
#[inline]
fn swap_buffers(&self) -> Result<(), ContextError> {
unsafe {
let canvas = (self.libcaca.caca_get_canvas)(self.display);
let width = (self.libcaca.caca_get_canvas_width)(canvas);
let height = (self.libcaca.caca_get_canvas_height)(canvas);
let buffer = self.opengl.get_framebuffer().chunks(self.opengl.get_dimensions().0 as usize)
.flat_map(|i| i.iter().cloned()).rev().collect::<Vec<u32>>();
(self.libcaca.caca_dither_bitmap)(canvas, 0, 0, width as libc::c_int,
height as libc::c_int, self.dither,
buffer.as_ptr() as *const _);
(self.libcaca.caca_refresh_display)(self.display);
};
Ok(())
}
#[inline]
fn get_api(&self) -> Api {
self.opengl.get_api()
}
#[inline]
fn get_pixel_format(&self) -> PixelFormat {
self.opengl.get_pixel_format()
}
}
impl Drop for Window {
#[inline]
fn drop(&mut self) {
unsafe {
(self.libcaca.caca_free_dither)(self.dither);
(self.libcaca.caca_free_display)(self.display);
}
}
}
|
{
unsafe { (libcaca.caca_free_display)(display) };
return Err(CreationError::OsError("caca_create_dither failed".to_string()));
}
|
conditional_block
|
encoding.rs
|
//! The `Encoding` struct.
use binemit::CodeOffset;
use isa::constraints::{RecipeConstraints, BranchRange};
use std::fmt;
/// Bits needed to encode an instruction as binary machine code.
///
/// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and
/// encoding *bits*. The recipe determines the native instruction format and the mapping of
/// operands to encoded bits. The encoding bits provide additional information to the recipe,
/// typically parts of the opcode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Encoding {
recipe: u16,
bits: u16,
}
impl Encoding {
/// Create a new `Encoding` containing `(recipe, bits)`.
pub fn new(recipe: u16, bits: u16) -> Encoding {
Encoding { recipe, bits }
}
/// Get the recipe number in this encoding.
pub fn recipe(self) -> usize {
self.recipe as usize
}
/// Get the recipe-specific encoding bits.
pub fn bits(self) -> u16 {
self.bits
}
/// Is this a legal encoding, or the default placeholder?
pub fn is_legal(self) -> bool {
self!= Self::default()
}
}
/// The default encoding is the illegal one.
impl Default for Encoding {
fn default() -> Self {
Self::new(0xffff, 0xffff)
}
}
/// ISA-independent display of an encoding.
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_legal() {
write!(f, "{}#{:02x}", self.recipe, self.bits)
} else {
write!(f, "-")
}
}
}
/// Temporary object that holds enough context to properly display an encoding.
/// This is meant to be created by `EncInfo::display()`.
pub struct DisplayEncoding {
pub encoding: Encoding,
pub recipe_names: &'static [&'static str],
}
impl fmt::Display for DisplayEncoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.encoding.is_legal() {
write!(
f,
"{}#{:02x}",
self.recipe_names[self.encoding.recipe()],
self.encoding.bits
)
} else
|
}
}
/// Code size information for an encoding recipe.
///
/// All encoding recipes correspond to an exact instruction size.
pub struct RecipeSizing {
/// Size in bytes of instructions encoded with this recipe.
pub bytes: u8,
/// Allowed branch range in this recipe, if any.
///
/// All encoding recipes for branches have exact branch range information.
pub branch_range: Option<BranchRange>,
}
/// Information about all the encodings in this ISA.
#[derive(Clone)]
pub struct EncInfo {
/// Constraints on value operands per recipe.
pub constraints: &'static [RecipeConstraints],
/// Code size information per recipe.
pub sizing: &'static [RecipeSizing],
/// Names of encoding recipes.
pub names: &'static [&'static str],
}
impl EncInfo {
/// Get the value operand constraints for `enc` if it is a legal encoding.
pub fn operand_constraints(&self, enc: Encoding) -> Option<&'static RecipeConstraints> {
self.constraints.get(enc.recipe())
}
/// Create an object that can display an ISA-dependent encoding properly.
pub fn display(&self, enc: Encoding) -> DisplayEncoding {
DisplayEncoding {
encoding: enc,
recipe_names: self.names,
}
}
/// Get the exact size in bytes of instructions encoded with `enc`.
///
/// Returns 0 for illegal encodings.
pub fn bytes(&self, enc: Encoding) -> CodeOffset {
self.sizing
.get(enc.recipe())
.map(|s| CodeOffset::from(s.bytes))
.unwrap_or(0)
}
/// Get the branch range that is supported by `enc`, if any.
///
/// This will never return `None` for a legal branch encoding.
pub fn branch_range(&self, enc: Encoding) -> Option<BranchRange> {
self.sizing.get(enc.recipe()).and_then(|s| s.branch_range)
}
}
|
{
write!(f, "-")
}
|
conditional_block
|
encoding.rs
|
//! The `Encoding` struct.
use binemit::CodeOffset;
use isa::constraints::{RecipeConstraints, BranchRange};
use std::fmt;
/// Bits needed to encode an instruction as binary machine code.
///
/// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and
/// encoding *bits*. The recipe determines the native instruction format and the mapping of
/// operands to encoded bits. The encoding bits provide additional information to the recipe,
/// typically parts of the opcode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Encoding {
recipe: u16,
bits: u16,
}
impl Encoding {
/// Create a new `Encoding` containing `(recipe, bits)`.
pub fn new(recipe: u16, bits: u16) -> Encoding {
Encoding { recipe, bits }
}
/// Get the recipe number in this encoding.
pub fn recipe(self) -> usize {
self.recipe as usize
}
/// Get the recipe-specific encoding bits.
pub fn bits(self) -> u16 {
self.bits
}
/// Is this a legal encoding, or the default placeholder?
pub fn is_legal(self) -> bool {
self!= Self::default()
}
}
/// The default encoding is the illegal one.
impl Default for Encoding {
fn default() -> Self {
Self::new(0xffff, 0xffff)
}
}
/// ISA-independent display of an encoding.
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_legal() {
write!(f, "{}#{:02x}", self.recipe, self.bits)
} else {
write!(f, "-")
}
}
}
/// Temporary object that holds enough context to properly display an encoding.
/// This is meant to be created by `EncInfo::display()`.
pub struct DisplayEncoding {
pub encoding: Encoding,
pub recipe_names: &'static [&'static str],
}
impl fmt::Display for DisplayEncoding {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.encoding.is_legal() {
write!(
f,
"{}#{:02x}",
self.recipe_names[self.encoding.recipe()],
self.encoding.bits
)
} else {
write!(f, "-")
}
}
}
/// Code size information for an encoding recipe.
///
/// All encoding recipes correspond to an exact instruction size.
pub struct RecipeSizing {
/// Size in bytes of instructions encoded with this recipe.
pub bytes: u8,
/// Allowed branch range in this recipe, if any.
///
/// All encoding recipes for branches have exact branch range information.
pub branch_range: Option<BranchRange>,
}
/// Information about all the encodings in this ISA.
#[derive(Clone)]
pub struct EncInfo {
/// Constraints on value operands per recipe.
pub constraints: &'static [RecipeConstraints],
/// Code size information per recipe.
pub sizing: &'static [RecipeSizing],
/// Names of encoding recipes.
pub names: &'static [&'static str],
}
impl EncInfo {
/// Get the value operand constraints for `enc` if it is a legal encoding.
pub fn operand_constraints(&self, enc: Encoding) -> Option<&'static RecipeConstraints> {
self.constraints.get(enc.recipe())
}
/// Create an object that can display an ISA-dependent encoding properly.
pub fn display(&self, enc: Encoding) -> DisplayEncoding {
DisplayEncoding {
encoding: enc,
recipe_names: self.names,
}
}
/// Get the exact size in bytes of instructions encoded with `enc`.
///
/// Returns 0 for illegal encodings.
pub fn bytes(&self, enc: Encoding) -> CodeOffset {
self.sizing
.get(enc.recipe())
.map(|s| CodeOffset::from(s.bytes))
.unwrap_or(0)
}
/// Get the branch range that is supported by `enc`, if any.
///
/// This will never return `None` for a legal branch encoding.
pub fn branch_range(&self, enc: Encoding) -> Option<BranchRange> {
self.sizing.get(enc.recipe()).and_then(|s| s.branch_range)
}
}
|
fmt
|
identifier_name
|
encoding.rs
|
//! The `Encoding` struct.
use binemit::CodeOffset;
use isa::constraints::{RecipeConstraints, BranchRange};
use std::fmt;
/// Bits needed to encode an instruction as binary machine code.
///
/// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and
/// encoding *bits*. The recipe determines the native instruction format and the mapping of
/// operands to encoded bits. The encoding bits provide additional information to the recipe,
/// typically parts of the opcode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Encoding {
recipe: u16,
bits: u16,
}
impl Encoding {
/// Create a new `Encoding` containing `(recipe, bits)`.
pub fn new(recipe: u16, bits: u16) -> Encoding {
Encoding { recipe, bits }
}
/// Get the recipe number in this encoding.
pub fn recipe(self) -> usize {
self.recipe as usize
}
/// Get the recipe-specific encoding bits.
pub fn bits(self) -> u16 {
self.bits
}
/// Is this a legal encoding, or the default placeholder?
pub fn is_legal(self) -> bool {
self!= Self::default()
}
}
/// The default encoding is the illegal one.
impl Default for Encoding {
fn default() -> Self {
Self::new(0xffff, 0xffff)
}
}
/// ISA-independent display of an encoding.
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_legal() {
write!(f, "{}#{:02x}", self.recipe, self.bits)
} else {
write!(f, "-")
}
}
}
/// Temporary object that holds enough context to properly display an encoding.
/// This is meant to be created by `EncInfo::display()`.
pub struct DisplayEncoding {
pub encoding: Encoding,
pub recipe_names: &'static [&'static str],
}
impl fmt::Display for DisplayEncoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.encoding.is_legal() {
write!(
f,
"{}#{:02x}",
self.recipe_names[self.encoding.recipe()],
self.encoding.bits
)
} else {
write!(f, "-")
}
}
}
/// Code size information for an encoding recipe.
///
/// All encoding recipes correspond to an exact instruction size.
pub struct RecipeSizing {
/// Size in bytes of instructions encoded with this recipe.
pub bytes: u8,
/// Allowed branch range in this recipe, if any.
///
/// All encoding recipes for branches have exact branch range information.
pub branch_range: Option<BranchRange>,
}
/// Information about all the encodings in this ISA.
#[derive(Clone)]
pub struct EncInfo {
/// Constraints on value operands per recipe.
pub constraints: &'static [RecipeConstraints],
/// Code size information per recipe.
pub sizing: &'static [RecipeSizing],
/// Names of encoding recipes.
pub names: &'static [&'static str],
}
|
pub fn operand_constraints(&self, enc: Encoding) -> Option<&'static RecipeConstraints> {
self.constraints.get(enc.recipe())
}
/// Create an object that can display an ISA-dependent encoding properly.
pub fn display(&self, enc: Encoding) -> DisplayEncoding {
DisplayEncoding {
encoding: enc,
recipe_names: self.names,
}
}
/// Get the exact size in bytes of instructions encoded with `enc`.
///
/// Returns 0 for illegal encodings.
pub fn bytes(&self, enc: Encoding) -> CodeOffset {
self.sizing
.get(enc.recipe())
.map(|s| CodeOffset::from(s.bytes))
.unwrap_or(0)
}
/// Get the branch range that is supported by `enc`, if any.
///
/// This will never return `None` for a legal branch encoding.
pub fn branch_range(&self, enc: Encoding) -> Option<BranchRange> {
self.sizing.get(enc.recipe()).and_then(|s| s.branch_range)
}
}
|
impl EncInfo {
/// Get the value operand constraints for `enc` if it is a legal encoding.
|
random_line_split
|
graph.rs
|
// Copyright (c) 2017 Jason White
|
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use button::build_graph::{BuildGraph, FromRules};
use button::graph::Graphviz;
use button::rules::Rules;
use button::{BuildState, Error, ResultExt};
use crate::opts::GlobalOpts;
use crate::paths;
#[derive(StructOpt, Debug)]
pub struct Graph {
/// Path to the build rules. If not specified, finds "button.json" in the
/// current directory or parent directories.
#[structopt(long = "rules", short = "r", parse(from_os_str))]
rules: Option<PathBuf>,
/// Path to the output file. If not specified, writes to standard output.
#[structopt(long = "output", short = "o", parse(from_os_str))]
output: Option<PathBuf>,
/// Display the cached graph from the previous build. Otherwise, only
/// displays the build graph derived from the build rules.
#[structopt(long = "cached")]
cached: bool,
}
impl Graph {
/// Shows a pretty graph of the build.
pub fn main(self, _global: &GlobalOpts) -> Result<(), Error> {
let rules = paths::rules_or(self.rules)
.context("Failed to find build rules")?;
let build_graph = if self.cached {
let root = rules.parent().unwrap_or_else(|| Path::new("."));
let state_path = root.join(paths::STATE);
let state =
BuildState::from_path(&state_path).with_context(|_| {
format!(
"Failed loading build state from '{}'",
state_path.display()
)
})?;
state.graph
} else {
let rules = Rules::from_path(&rules).with_context(|_| {
format!("Failed loading rules from '{}'", rules.display())
})?;
BuildGraph::from_rules(rules)?
};
if let Some(output) = &self.output {
let mut stream =
io::BufWriter::new(fs::File::create(&output).with_context(
|_| format!("Failed creating '{}'", output.display()),
)?);
build_graph.graphviz(&mut stream)?;
stream.flush() // Flush to catch write errors
} else {
let mut stdout = io::stdout();
build_graph.graphviz(&mut stdout.lock())?;
stdout.flush() // Flush to catch write errors
}
.context("Failed writing GraphViz DOT file")?;
Ok(())
}
}
|
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
|
random_line_split
|
graph.rs
|
// Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use button::build_graph::{BuildGraph, FromRules};
use button::graph::Graphviz;
use button::rules::Rules;
use button::{BuildState, Error, ResultExt};
use crate::opts::GlobalOpts;
use crate::paths;
#[derive(StructOpt, Debug)]
pub struct Graph {
/// Path to the build rules. If not specified, finds "button.json" in the
/// current directory or parent directories.
#[structopt(long = "rules", short = "r", parse(from_os_str))]
rules: Option<PathBuf>,
/// Path to the output file. If not specified, writes to standard output.
#[structopt(long = "output", short = "o", parse(from_os_str))]
output: Option<PathBuf>,
/// Display the cached graph from the previous build. Otherwise, only
/// displays the build graph derived from the build rules.
#[structopt(long = "cached")]
cached: bool,
}
impl Graph {
/// Shows a pretty graph of the build.
pub fn main(self, _global: &GlobalOpts) -> Result<(), Error> {
let rules = paths::rules_or(self.rules)
.context("Failed to find build rules")?;
let build_graph = if self.cached {
let root = rules.parent().unwrap_or_else(|| Path::new("."));
let state_path = root.join(paths::STATE);
let state =
BuildState::from_path(&state_path).with_context(|_| {
format!(
"Failed loading build state from '{}'",
state_path.display()
)
})?;
state.graph
} else {
let rules = Rules::from_path(&rules).with_context(|_| {
format!("Failed loading rules from '{}'", rules.display())
})?;
BuildGraph::from_rules(rules)?
};
if let Some(output) = &self.output
|
else {
let mut stdout = io::stdout();
build_graph.graphviz(&mut stdout.lock())?;
stdout.flush() // Flush to catch write errors
}
.context("Failed writing GraphViz DOT file")?;
Ok(())
}
}
|
{
let mut stream =
io::BufWriter::new(fs::File::create(&output).with_context(
|_| format!("Failed creating '{}'", output.display()),
)?);
build_graph.graphviz(&mut stream)?;
stream.flush() // Flush to catch write errors
}
|
conditional_block
|
graph.rs
|
// Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use structopt::StructOpt;
use button::build_graph::{BuildGraph, FromRules};
use button::graph::Graphviz;
use button::rules::Rules;
use button::{BuildState, Error, ResultExt};
use crate::opts::GlobalOpts;
use crate::paths;
#[derive(StructOpt, Debug)]
pub struct
|
{
/// Path to the build rules. If not specified, finds "button.json" in the
/// current directory or parent directories.
#[structopt(long = "rules", short = "r", parse(from_os_str))]
rules: Option<PathBuf>,
/// Path to the output file. If not specified, writes to standard output.
#[structopt(long = "output", short = "o", parse(from_os_str))]
output: Option<PathBuf>,
/// Display the cached graph from the previous build. Otherwise, only
/// displays the build graph derived from the build rules.
#[structopt(long = "cached")]
cached: bool,
}
impl Graph {
/// Shows a pretty graph of the build.
pub fn main(self, _global: &GlobalOpts) -> Result<(), Error> {
let rules = paths::rules_or(self.rules)
.context("Failed to find build rules")?;
let build_graph = if self.cached {
let root = rules.parent().unwrap_or_else(|| Path::new("."));
let state_path = root.join(paths::STATE);
let state =
BuildState::from_path(&state_path).with_context(|_| {
format!(
"Failed loading build state from '{}'",
state_path.display()
)
})?;
state.graph
} else {
let rules = Rules::from_path(&rules).with_context(|_| {
format!("Failed loading rules from '{}'", rules.display())
})?;
BuildGraph::from_rules(rules)?
};
if let Some(output) = &self.output {
let mut stream =
io::BufWriter::new(fs::File::create(&output).with_context(
|_| format!("Failed creating '{}'", output.display()),
)?);
build_graph.graphviz(&mut stream)?;
stream.flush() // Flush to catch write errors
} else {
let mut stdout = io::stdout();
build_graph.graphviz(&mut stdout.lock())?;
stdout.flush() // Flush to catch write errors
}
.context("Failed writing GraphViz DOT file")?;
Ok(())
}
}
|
Graph
|
identifier_name
|
lib.rs
|
// A rust wrapper to a small subset of TestU01
// (http://simul.iro.umontreal.ca/testu01/tu01.html).
// Copyright (C) 2015 Loรฏc Damien
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! This crate is a wrapper around a small subset of TestU01.
#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate rand;
|
use std::sync::Mutex;
lazy_static! {
/// Lot of TestU01 is inherently non thread-safe, updating/reading global variables without
/// synchronization. This lock is here to protect access to all TestU01 global variables.
static ref GLOBAL_LOCK: Mutex<()> = Mutex::new(());
}
pub mod decorators;
pub mod battery;
pub mod unif01;
pub mod swrite;
|
random_line_split
|
|
std_qsearch.rs
|
//! Implements `StdQsearch` and `StdQsearchResult`.
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use uci::{SetOption, OptionDescription};
use board::*;
use value::*;
use depth::*;
use moves::*;
use evaluator::Evaluator;
use qsearch::{Qsearch, QsearchParams, QsearchResult};
use move_generator::MoveGenerator;
use utils::MoveStack;
/// Implements the `QsearchResult` trait.
#[derive(Clone, Debug)]
pub struct StdQsearchResult {
value: Value,
searched_nodes: u64,
}
impl QsearchResult for StdQsearchResult {
#[inline]
fn new(value: Value, searched_nodes: u64) -> Self {
debug_assert!(VALUE_EVAL_MIN <= value && value <= VALUE_EVAL_MAX);
StdQsearchResult {
value: value,
searched_nodes: searched_nodes,
}
}
#[inline]
fn value(&self) -> Value {
self.value
}
#[inline]
fn searched_nodes(&self) -> u64
|
}
/// Implements the `Qsearch` trait.
///
/// Performs classical quiescence search with stand pat, delta
/// pruning, static exchange evaluation, check evasions, limited
/// checks and recaptures.
pub struct StdQsearch<T: MoveGenerator> {
phantom: PhantomData<T>,
}
impl<T: MoveGenerator> Qsearch for StdQsearch<T> {
type MoveGenerator = T;
type QsearchResult = StdQsearchResult;
fn qsearch(params: QsearchParams<Self::MoveGenerator>) -> Self::QsearchResult {
debug_assert!(DEPTH_MIN <= params.depth && params.depth <= 0);
debug_assert!(params.lower_bound >= VALUE_MIN);
debug_assert!(params.upper_bound <= VALUE_MAX);
debug_assert!(params.lower_bound < params.upper_bound);
thread_local!(
static MOVE_STACK: UnsafeCell<MoveStack> = UnsafeCell::new(MoveStack::new())
);
let mut searched_nodes = 0;
let value = MOVE_STACK.with(|s| unsafe {
qsearch(params.position,
params.lower_bound,
params.upper_bound,
params.static_eval,
0,
-params.depth,
&mut *s.get(),
&mut searched_nodes)
});
StdQsearchResult::new(value, searched_nodes)
}
}
impl<T: MoveGenerator> SetOption for StdQsearch<T> {
fn options() -> Vec<(&'static str, OptionDescription)> {
T::options()
}
fn set_option(name: &str, value: &str) {
T::set_option(name, value)
}
}
/// A classical recursive quiescence search implementation.
fn qsearch<T: MoveGenerator>(position: &mut T,
mut lower_bound: Value, // alpha
upper_bound: Value, // beta
mut stand_pat: Value, // position's static evaluation
mut recapture_squares: Bitboard,
ply: i8, // the reached `qsearch` depth
move_stack: &mut MoveStack,
searched_nodes: &mut u64)
-> Value {
debug_assert!(lower_bound < upper_bound);
debug_assert!(stand_pat == VALUE_UNKNOWN ||
stand_pat == position.evaluator().evaluate(position.board()));
const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];
let is_check = position.is_check();
// At the beginning of quiescence, position's static evaluation
// (`stand_pat`) is used to establish a lower bound on the
// result. We assume that even if none of the forcing moves can
// improve on the stand pat, there will be at least one "quiet"
// move that will at least preserve the stand pat value. (Note
// that this assumption is not true if the the side to move is in
// check, because in this case all possible check evasions will be
// tried.)
if is_check {
// Position's static evaluation is useless when in check.
stand_pat = lower_bound;
} else if stand_pat == VALUE_UNKNOWN {
stand_pat = position.evaluator().evaluate(position.board());
}
if stand_pat >= upper_bound {
return stand_pat;
}
if stand_pat > lower_bound {
lower_bound = stand_pat;
}
let obligatory_material_gain = (lower_bound as isize) - (stand_pat as isize) -
(PIECE_VALUES[KNIGHT] - 4 * PIECE_VALUES[PAWN] / 3) as isize;
// Generate all forcing moves. (Include checks only during the
// first ply.)
move_stack.save();
position.generate_forcing(ply <= 0, move_stack);
// Consider the generated moves one by one. See if any of them
// can raise the lower bound.
'trymoves: while let Some(m) = move_stack.pull_best() {
let move_type = m.move_type();
let dest_square_bb = 1 << m.dest_square();
let captured_piece = m.captured_piece();
// Decide whether to try the move. Check evasions,
// en-passant captures (for them SEE is often wrong), and
// mandatory recaptures are always tried. (In order to
// correct SEE errors due to pinned and overloaded pieces,
// at least one mandatory recapture is always tried at the
// destination squares of previous moves.) For all other
// moves, a static exchange evaluation is performed to
// decide if the move should be tried.
if!is_check && move_type!= MOVE_ENPASSANT && recapture_squares & dest_square_bb == 0 {
match position.evaluate_move(m) {
// A losing move -- do not try it.
x if x < 0 => continue 'trymoves,
// An even exchange -- try it only during the first few plys.
0 if ply >= 2 && captured_piece < PIECE_NONE => continue 'trymoves,
// A safe or winning move -- try it always.
_ => (),
}
}
// Try the move.
if position.do_move(m).is_some() {
// If the move does not give check, ensure that
// the immediate material gain from the move is
// big enough.
if!position.is_check() {
let material_gain = if move_type == MOVE_PROMOTION {
PIECE_VALUES[captured_piece] +
PIECE_VALUES[Move::piece_from_aux_data(m.aux_data())] -
PIECE_VALUES[PAWN]
} else {
unsafe { *PIECE_VALUES.get_unchecked(captured_piece) }
};
if (material_gain as isize) < obligatory_material_gain {
position.undo_move(m);
continue 'trymoves;
}
}
// Recursively call `qsearch`.
*searched_nodes += 1;
let value = -qsearch(position,
-upper_bound,
-lower_bound,
VALUE_UNKNOWN,
recapture_squares ^ dest_square_bb,
ply + 1,
move_stack,
searched_nodes);
position.undo_move(m);
// Update the lower bound.
if value >= upper_bound {
lower_bound = value;
break 'trymoves;
}
if value > lower_bound {
lower_bound = value;
}
// Mark that a recapture at this square has been tried.
recapture_squares &=!dest_square_bb;
}
}
move_stack.restore();
// Return the determined lower bound. (We should make sure
// that the returned value is between `VALUE_EVAL_MIN` and
// `VALUE_EVAL_MAX`, regardless of the initial bounds passed
// to `qsearch`. If we do not take this precautions, the
// search algorithm will abstain from checkmating the
// opponent, seeking the huge material gain that `qsearch`
// promised.)
match lower_bound {
x if x < VALUE_EVAL_MIN => VALUE_EVAL_MIN,
x if x > VALUE_EVAL_MAX => VALUE_EVAL_MAX,
x => x,
}
}
#[cfg(test)]
mod tests {
use board::*;
use value::*;
use move_generator::*;
use stock::{SimpleEvaluator, StdMoveGenerator};
use utils::MoveStack;
type P = StdMoveGenerator<SimpleEvaluator>;
#[test]
fn qsearch() {
use super::qsearch;
let mut s = MoveStack::new();
let d = 32;
let fen = "8/8/8/8/6k1/6P1/8/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/6k1/6P1/8/5bK1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) > 225 - d);
let fen = "8/8/8/8/5pkp/6P1/5P1P/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/5pkp/6P1/5PKP/8 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4p3/2N1P2B/3P1N2/PPP2PPP/R2QKB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4N3/4P2B/3P1N2/PPP2PPP/R2QKB1R b - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "rn2kbnr/ppppqppp/8/4p3/2N1P1b1/3P1N2/PPP2PPP/R1BKQB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/8/7k/7q/7K w - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -10000, 10000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -10000);
}
}
|
{
self.searched_nodes
}
|
identifier_body
|
std_qsearch.rs
|
//! Implements `StdQsearch` and `StdQsearchResult`.
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use uci::{SetOption, OptionDescription};
use board::*;
use value::*;
use depth::*;
use moves::*;
use evaluator::Evaluator;
use qsearch::{Qsearch, QsearchParams, QsearchResult};
use move_generator::MoveGenerator;
use utils::MoveStack;
/// Implements the `QsearchResult` trait.
#[derive(Clone, Debug)]
pub struct StdQsearchResult {
value: Value,
searched_nodes: u64,
}
impl QsearchResult for StdQsearchResult {
#[inline]
fn new(value: Value, searched_nodes: u64) -> Self {
debug_assert!(VALUE_EVAL_MIN <= value && value <= VALUE_EVAL_MAX);
StdQsearchResult {
value: value,
searched_nodes: searched_nodes,
}
}
#[inline]
fn value(&self) -> Value {
self.value
}
#[inline]
fn searched_nodes(&self) -> u64 {
self.searched_nodes
}
}
/// Implements the `Qsearch` trait.
///
/// Performs classical quiescence search with stand pat, delta
/// pruning, static exchange evaluation, check evasions, limited
/// checks and recaptures.
pub struct StdQsearch<T: MoveGenerator> {
phantom: PhantomData<T>,
}
impl<T: MoveGenerator> Qsearch for StdQsearch<T> {
type MoveGenerator = T;
type QsearchResult = StdQsearchResult;
fn qsearch(params: QsearchParams<Self::MoveGenerator>) -> Self::QsearchResult {
debug_assert!(DEPTH_MIN <= params.depth && params.depth <= 0);
debug_assert!(params.lower_bound >= VALUE_MIN);
debug_assert!(params.upper_bound <= VALUE_MAX);
debug_assert!(params.lower_bound < params.upper_bound);
thread_local!(
static MOVE_STACK: UnsafeCell<MoveStack> = UnsafeCell::new(MoveStack::new())
);
let mut searched_nodes = 0;
let value = MOVE_STACK.with(|s| unsafe {
qsearch(params.position,
params.lower_bound,
params.upper_bound,
params.static_eval,
0,
-params.depth,
&mut *s.get(),
&mut searched_nodes)
});
StdQsearchResult::new(value, searched_nodes)
}
}
impl<T: MoveGenerator> SetOption for StdQsearch<T> {
fn options() -> Vec<(&'static str, OptionDescription)> {
T::options()
}
fn set_option(name: &str, value: &str) {
T::set_option(name, value)
}
}
/// A classical recursive quiescence search implementation.
fn qsearch<T: MoveGenerator>(position: &mut T,
mut lower_bound: Value, // alpha
upper_bound: Value, // beta
mut stand_pat: Value, // position's static evaluation
mut recapture_squares: Bitboard,
ply: i8, // the reached `qsearch` depth
move_stack: &mut MoveStack,
searched_nodes: &mut u64)
-> Value {
debug_assert!(lower_bound < upper_bound);
debug_assert!(stand_pat == VALUE_UNKNOWN ||
stand_pat == position.evaluator().evaluate(position.board()));
const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];
let is_check = position.is_check();
// At the beginning of quiescence, position's static evaluation
// (`stand_pat`) is used to establish a lower bound on the
// result. We assume that even if none of the forcing moves can
// improve on the stand pat, there will be at least one "quiet"
// move that will at least preserve the stand pat value. (Note
// that this assumption is not true if the the side to move is in
// check, because in this case all possible check evasions will be
// tried.)
if is_check {
// Position's static evaluation is useless when in check.
stand_pat = lower_bound;
} else if stand_pat == VALUE_UNKNOWN {
stand_pat = position.evaluator().evaluate(position.board());
}
if stand_pat >= upper_bound {
return stand_pat;
}
if stand_pat > lower_bound {
lower_bound = stand_pat;
}
let obligatory_material_gain = (lower_bound as isize) - (stand_pat as isize) -
(PIECE_VALUES[KNIGHT] - 4 * PIECE_VALUES[PAWN] / 3) as isize;
// Generate all forcing moves. (Include checks only during the
// first ply.)
move_stack.save();
position.generate_forcing(ply <= 0, move_stack);
// Consider the generated moves one by one. See if any of them
// can raise the lower bound.
'trymoves: while let Some(m) = move_stack.pull_best() {
let move_type = m.move_type();
let dest_square_bb = 1 << m.dest_square();
let captured_piece = m.captured_piece();
// Decide whether to try the move. Check evasions,
// en-passant captures (for them SEE is often wrong), and
// mandatory recaptures are always tried. (In order to
// correct SEE errors due to pinned and overloaded pieces,
// at least one mandatory recapture is always tried at the
// destination squares of previous moves.) For all other
// moves, a static exchange evaluation is performed to
// decide if the move should be tried.
if!is_check && move_type!= MOVE_ENPASSANT && recapture_squares & dest_square_bb == 0
|
// Try the move.
if position.do_move(m).is_some() {
// If the move does not give check, ensure that
// the immediate material gain from the move is
// big enough.
if!position.is_check() {
let material_gain = if move_type == MOVE_PROMOTION {
PIECE_VALUES[captured_piece] +
PIECE_VALUES[Move::piece_from_aux_data(m.aux_data())] -
PIECE_VALUES[PAWN]
} else {
unsafe { *PIECE_VALUES.get_unchecked(captured_piece) }
};
if (material_gain as isize) < obligatory_material_gain {
position.undo_move(m);
continue 'trymoves;
}
}
// Recursively call `qsearch`.
*searched_nodes += 1;
let value = -qsearch(position,
-upper_bound,
-lower_bound,
VALUE_UNKNOWN,
recapture_squares ^ dest_square_bb,
ply + 1,
move_stack,
searched_nodes);
position.undo_move(m);
// Update the lower bound.
if value >= upper_bound {
lower_bound = value;
break 'trymoves;
}
if value > lower_bound {
lower_bound = value;
}
// Mark that a recapture at this square has been tried.
recapture_squares &=!dest_square_bb;
}
}
move_stack.restore();
// Return the determined lower bound. (We should make sure
// that the returned value is between `VALUE_EVAL_MIN` and
// `VALUE_EVAL_MAX`, regardless of the initial bounds passed
// to `qsearch`. If we do not take this precautions, the
// search algorithm will abstain from checkmating the
// opponent, seeking the huge material gain that `qsearch`
// promised.)
match lower_bound {
x if x < VALUE_EVAL_MIN => VALUE_EVAL_MIN,
x if x > VALUE_EVAL_MAX => VALUE_EVAL_MAX,
x => x,
}
}
#[cfg(test)]
mod tests {
use board::*;
use value::*;
use move_generator::*;
use stock::{SimpleEvaluator, StdMoveGenerator};
use utils::MoveStack;
type P = StdMoveGenerator<SimpleEvaluator>;
#[test]
fn qsearch() {
use super::qsearch;
let mut s = MoveStack::new();
let d = 32;
let fen = "8/8/8/8/6k1/6P1/8/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/6k1/6P1/8/5bK1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) > 225 - d);
let fen = "8/8/8/8/5pkp/6P1/5P1P/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/5pkp/6P1/5PKP/8 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4p3/2N1P2B/3P1N2/PPP2PPP/R2QKB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4N3/4P2B/3P1N2/PPP2PPP/R2QKB1R b - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "rn2kbnr/ppppqppp/8/4p3/2N1P1b1/3P1N2/PPP2PPP/R1BKQB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/8/7k/7q/7K w - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -10000, 10000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -10000);
}
}
|
{
match position.evaluate_move(m) {
// A losing move -- do not try it.
x if x < 0 => continue 'trymoves,
// An even exchange -- try it only during the first few plys.
0 if ply >= 2 && captured_piece < PIECE_NONE => continue 'trymoves,
// A safe or winning move -- try it always.
_ => (),
}
}
|
conditional_block
|
std_qsearch.rs
|
//! Implements `StdQsearch` and `StdQsearchResult`.
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use uci::{SetOption, OptionDescription};
use board::*;
use value::*;
use depth::*;
use moves::*;
use evaluator::Evaluator;
use qsearch::{Qsearch, QsearchParams, QsearchResult};
use move_generator::MoveGenerator;
use utils::MoveStack;
/// Implements the `QsearchResult` trait.
#[derive(Clone, Debug)]
pub struct StdQsearchResult {
value: Value,
searched_nodes: u64,
}
impl QsearchResult for StdQsearchResult {
#[inline]
fn new(value: Value, searched_nodes: u64) -> Self {
debug_assert!(VALUE_EVAL_MIN <= value && value <= VALUE_EVAL_MAX);
StdQsearchResult {
value: value,
searched_nodes: searched_nodes,
}
}
#[inline]
fn value(&self) -> Value {
self.value
}
#[inline]
fn searched_nodes(&self) -> u64 {
self.searched_nodes
}
}
/// Implements the `Qsearch` trait.
///
/// Performs classical quiescence search with stand pat, delta
/// pruning, static exchange evaluation, check evasions, limited
/// checks and recaptures.
pub struct StdQsearch<T: MoveGenerator> {
phantom: PhantomData<T>,
}
impl<T: MoveGenerator> Qsearch for StdQsearch<T> {
type MoveGenerator = T;
type QsearchResult = StdQsearchResult;
fn qsearch(params: QsearchParams<Self::MoveGenerator>) -> Self::QsearchResult {
debug_assert!(DEPTH_MIN <= params.depth && params.depth <= 0);
debug_assert!(params.lower_bound >= VALUE_MIN);
debug_assert!(params.upper_bound <= VALUE_MAX);
debug_assert!(params.lower_bound < params.upper_bound);
thread_local!(
static MOVE_STACK: UnsafeCell<MoveStack> = UnsafeCell::new(MoveStack::new())
);
let mut searched_nodes = 0;
let value = MOVE_STACK.with(|s| unsafe {
qsearch(params.position,
params.lower_bound,
params.upper_bound,
params.static_eval,
0,
-params.depth,
&mut *s.get(),
&mut searched_nodes)
});
StdQsearchResult::new(value, searched_nodes)
}
}
impl<T: MoveGenerator> SetOption for StdQsearch<T> {
fn options() -> Vec<(&'static str, OptionDescription)> {
T::options()
}
fn set_option(name: &str, value: &str) {
T::set_option(name, value)
}
}
/// A classical recursive quiescence search implementation.
fn qsearch<T: MoveGenerator>(position: &mut T,
mut lower_bound: Value, // alpha
upper_bound: Value, // beta
mut stand_pat: Value, // position's static evaluation
mut recapture_squares: Bitboard,
ply: i8, // the reached `qsearch` depth
move_stack: &mut MoveStack,
searched_nodes: &mut u64)
-> Value {
debug_assert!(lower_bound < upper_bound);
debug_assert!(stand_pat == VALUE_UNKNOWN ||
stand_pat == position.evaluator().evaluate(position.board()));
const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];
let is_check = position.is_check();
// At the beginning of quiescence, position's static evaluation
// (`stand_pat`) is used to establish a lower bound on the
// result. We assume that even if none of the forcing moves can
// improve on the stand pat, there will be at least one "quiet"
// move that will at least preserve the stand pat value. (Note
// that this assumption is not true if the the side to move is in
// check, because in this case all possible check evasions will be
// tried.)
if is_check {
// Position's static evaluation is useless when in check.
stand_pat = lower_bound;
} else if stand_pat == VALUE_UNKNOWN {
stand_pat = position.evaluator().evaluate(position.board());
}
if stand_pat >= upper_bound {
return stand_pat;
}
if stand_pat > lower_bound {
lower_bound = stand_pat;
}
let obligatory_material_gain = (lower_bound as isize) - (stand_pat as isize) -
(PIECE_VALUES[KNIGHT] - 4 * PIECE_VALUES[PAWN] / 3) as isize;
// Generate all forcing moves. (Include checks only during the
// first ply.)
move_stack.save();
position.generate_forcing(ply <= 0, move_stack);
// Consider the generated moves one by one. See if any of them
// can raise the lower bound.
'trymoves: while let Some(m) = move_stack.pull_best() {
let move_type = m.move_type();
let dest_square_bb = 1 << m.dest_square();
let captured_piece = m.captured_piece();
// Decide whether to try the move. Check evasions,
// en-passant captures (for them SEE is often wrong), and
// mandatory recaptures are always tried. (In order to
// correct SEE errors due to pinned and overloaded pieces,
// at least one mandatory recapture is always tried at the
// destination squares of previous moves.) For all other
// moves, a static exchange evaluation is performed to
// decide if the move should be tried.
if!is_check && move_type!= MOVE_ENPASSANT && recapture_squares & dest_square_bb == 0 {
match position.evaluate_move(m) {
// A losing move -- do not try it.
x if x < 0 => continue 'trymoves,
// An even exchange -- try it only during the first few plys.
0 if ply >= 2 && captured_piece < PIECE_NONE => continue 'trymoves,
// A safe or winning move -- try it always.
_ => (),
}
}
// Try the move.
if position.do_move(m).is_some() {
// If the move does not give check, ensure that
// the immediate material gain from the move is
// big enough.
if!position.is_check() {
let material_gain = if move_type == MOVE_PROMOTION {
PIECE_VALUES[captured_piece] +
PIECE_VALUES[Move::piece_from_aux_data(m.aux_data())] -
PIECE_VALUES[PAWN]
} else {
unsafe { *PIECE_VALUES.get_unchecked(captured_piece) }
};
if (material_gain as isize) < obligatory_material_gain {
position.undo_move(m);
continue 'trymoves;
}
}
// Recursively call `qsearch`.
*searched_nodes += 1;
let value = -qsearch(position,
-upper_bound,
-lower_bound,
VALUE_UNKNOWN,
recapture_squares ^ dest_square_bb,
ply + 1,
move_stack,
searched_nodes);
position.undo_move(m);
// Update the lower bound.
if value >= upper_bound {
lower_bound = value;
break 'trymoves;
}
if value > lower_bound {
lower_bound = value;
}
// Mark that a recapture at this square has been tried.
recapture_squares &=!dest_square_bb;
}
}
move_stack.restore();
// Return the determined lower bound. (We should make sure
// that the returned value is between `VALUE_EVAL_MIN` and
// `VALUE_EVAL_MAX`, regardless of the initial bounds passed
// to `qsearch`. If we do not take this precautions, the
// search algorithm will abstain from checkmating the
// opponent, seeking the huge material gain that `qsearch`
// promised.)
match lower_bound {
x if x < VALUE_EVAL_MIN => VALUE_EVAL_MIN,
x if x > VALUE_EVAL_MAX => VALUE_EVAL_MAX,
x => x,
}
}
#[cfg(test)]
mod tests {
use board::*;
use value::*;
use move_generator::*;
use stock::{SimpleEvaluator, StdMoveGenerator};
use utils::MoveStack;
type P = StdMoveGenerator<SimpleEvaluator>;
#[test]
fn qsearch() {
use super::qsearch;
let mut s = MoveStack::new();
let d = 32;
let fen = "8/8/8/8/6k1/6P1/8/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
|
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) > 225 - d);
let fen = "8/8/8/8/5pkp/6P1/5P1P/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/5pkp/6P1/5PKP/8 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4p3/2N1P2B/3P1N2/PPP2PPP/R2QKB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4N3/4P2B/3P1N2/PPP2PPP/R2QKB1R b - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "rn2kbnr/ppppqppp/8/4p3/2N1P1b1/3P1N2/PPP2PPP/R1BKQB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/8/7k/7q/7K w - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -10000, 10000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -10000);
}
}
|
let fen = "8/8/8/8/6k1/6P1/8/5bK1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
|
random_line_split
|
std_qsearch.rs
|
//! Implements `StdQsearch` and `StdQsearchResult`.
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use uci::{SetOption, OptionDescription};
use board::*;
use value::*;
use depth::*;
use moves::*;
use evaluator::Evaluator;
use qsearch::{Qsearch, QsearchParams, QsearchResult};
use move_generator::MoveGenerator;
use utils::MoveStack;
/// Implements the `QsearchResult` trait.
#[derive(Clone, Debug)]
pub struct StdQsearchResult {
value: Value,
searched_nodes: u64,
}
impl QsearchResult for StdQsearchResult {
#[inline]
fn new(value: Value, searched_nodes: u64) -> Self {
debug_assert!(VALUE_EVAL_MIN <= value && value <= VALUE_EVAL_MAX);
StdQsearchResult {
value: value,
searched_nodes: searched_nodes,
}
}
#[inline]
fn value(&self) -> Value {
self.value
}
#[inline]
fn searched_nodes(&self) -> u64 {
self.searched_nodes
}
}
/// Implements the `Qsearch` trait.
///
/// Performs classical quiescence search with stand pat, delta
/// pruning, static exchange evaluation, check evasions, limited
/// checks and recaptures.
pub struct StdQsearch<T: MoveGenerator> {
phantom: PhantomData<T>,
}
impl<T: MoveGenerator> Qsearch for StdQsearch<T> {
type MoveGenerator = T;
type QsearchResult = StdQsearchResult;
fn qsearch(params: QsearchParams<Self::MoveGenerator>) -> Self::QsearchResult {
debug_assert!(DEPTH_MIN <= params.depth && params.depth <= 0);
debug_assert!(params.lower_bound >= VALUE_MIN);
debug_assert!(params.upper_bound <= VALUE_MAX);
debug_assert!(params.lower_bound < params.upper_bound);
thread_local!(
static MOVE_STACK: UnsafeCell<MoveStack> = UnsafeCell::new(MoveStack::new())
);
let mut searched_nodes = 0;
let value = MOVE_STACK.with(|s| unsafe {
qsearch(params.position,
params.lower_bound,
params.upper_bound,
params.static_eval,
0,
-params.depth,
&mut *s.get(),
&mut searched_nodes)
});
StdQsearchResult::new(value, searched_nodes)
}
}
impl<T: MoveGenerator> SetOption for StdQsearch<T> {
fn options() -> Vec<(&'static str, OptionDescription)> {
T::options()
}
fn
|
(name: &str, value: &str) {
T::set_option(name, value)
}
}
/// A classical recursive quiescence search implementation.
fn qsearch<T: MoveGenerator>(position: &mut T,
mut lower_bound: Value, // alpha
upper_bound: Value, // beta
mut stand_pat: Value, // position's static evaluation
mut recapture_squares: Bitboard,
ply: i8, // the reached `qsearch` depth
move_stack: &mut MoveStack,
searched_nodes: &mut u64)
-> Value {
debug_assert!(lower_bound < upper_bound);
debug_assert!(stand_pat == VALUE_UNKNOWN ||
stand_pat == position.evaluator().evaluate(position.board()));
const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];
let is_check = position.is_check();
// At the beginning of quiescence, position's static evaluation
// (`stand_pat`) is used to establish a lower bound on the
// result. We assume that even if none of the forcing moves can
// improve on the stand pat, there will be at least one "quiet"
// move that will at least preserve the stand pat value. (Note
// that this assumption is not true if the the side to move is in
// check, because in this case all possible check evasions will be
// tried.)
if is_check {
// Position's static evaluation is useless when in check.
stand_pat = lower_bound;
} else if stand_pat == VALUE_UNKNOWN {
stand_pat = position.evaluator().evaluate(position.board());
}
if stand_pat >= upper_bound {
return stand_pat;
}
if stand_pat > lower_bound {
lower_bound = stand_pat;
}
let obligatory_material_gain = (lower_bound as isize) - (stand_pat as isize) -
(PIECE_VALUES[KNIGHT] - 4 * PIECE_VALUES[PAWN] / 3) as isize;
// Generate all forcing moves. (Include checks only during the
// first ply.)
move_stack.save();
position.generate_forcing(ply <= 0, move_stack);
// Consider the generated moves one by one. See if any of them
// can raise the lower bound.
'trymoves: while let Some(m) = move_stack.pull_best() {
let move_type = m.move_type();
let dest_square_bb = 1 << m.dest_square();
let captured_piece = m.captured_piece();
// Decide whether to try the move. Check evasions,
// en-passant captures (for them SEE is often wrong), and
// mandatory recaptures are always tried. (In order to
// correct SEE errors due to pinned and overloaded pieces,
// at least one mandatory recapture is always tried at the
// destination squares of previous moves.) For all other
// moves, a static exchange evaluation is performed to
// decide if the move should be tried.
if!is_check && move_type!= MOVE_ENPASSANT && recapture_squares & dest_square_bb == 0 {
match position.evaluate_move(m) {
// A losing move -- do not try it.
x if x < 0 => continue 'trymoves,
// An even exchange -- try it only during the first few plys.
0 if ply >= 2 && captured_piece < PIECE_NONE => continue 'trymoves,
// A safe or winning move -- try it always.
_ => (),
}
}
// Try the move.
if position.do_move(m).is_some() {
// If the move does not give check, ensure that
// the immediate material gain from the move is
// big enough.
if!position.is_check() {
let material_gain = if move_type == MOVE_PROMOTION {
PIECE_VALUES[captured_piece] +
PIECE_VALUES[Move::piece_from_aux_data(m.aux_data())] -
PIECE_VALUES[PAWN]
} else {
unsafe { *PIECE_VALUES.get_unchecked(captured_piece) }
};
if (material_gain as isize) < obligatory_material_gain {
position.undo_move(m);
continue 'trymoves;
}
}
// Recursively call `qsearch`.
*searched_nodes += 1;
let value = -qsearch(position,
-upper_bound,
-lower_bound,
VALUE_UNKNOWN,
recapture_squares ^ dest_square_bb,
ply + 1,
move_stack,
searched_nodes);
position.undo_move(m);
// Update the lower bound.
if value >= upper_bound {
lower_bound = value;
break 'trymoves;
}
if value > lower_bound {
lower_bound = value;
}
// Mark that a recapture at this square has been tried.
recapture_squares &=!dest_square_bb;
}
}
move_stack.restore();
// Return the determined lower bound. (We should make sure
// that the returned value is between `VALUE_EVAL_MIN` and
// `VALUE_EVAL_MAX`, regardless of the initial bounds passed
// to `qsearch`. If we do not take this precautions, the
// search algorithm will abstain from checkmating the
// opponent, seeking the huge material gain that `qsearch`
// promised.)
match lower_bound {
x if x < VALUE_EVAL_MIN => VALUE_EVAL_MIN,
x if x > VALUE_EVAL_MAX => VALUE_EVAL_MAX,
x => x,
}
}
#[cfg(test)]
mod tests {
use board::*;
use value::*;
use move_generator::*;
use stock::{SimpleEvaluator, StdMoveGenerator};
use utils::MoveStack;
type P = StdMoveGenerator<SimpleEvaluator>;
#[test]
fn qsearch() {
use super::qsearch;
let mut s = MoveStack::new();
let d = 32;
let fen = "8/8/8/8/6k1/6P1/8/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/6k1/6P1/8/5bK1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) > 225 - d);
let fen = "8/8/8/8/5pkp/6P1/5P1P/6K1 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/5pkp/6P1/5PKP/8 b - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4p3/2N1P2B/3P1N2/PPP2PPP/R2QKB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "r1bqkbnr/pppp2pp/2n2p2/4N3/4P2B/3P1N2/PPP2PPP/R2QKB1R b - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -100 + d);
let fen = "rn2kbnr/ppppqppp/8/4p3/2N1P1b1/3P1N2/PPP2PPP/R1BKQB1R w - - 5 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0).abs() <= d);
let fen = "8/8/8/8/8/7k/7q/7K w - - 0 1";
let board = Board::from_fen(fen).ok().unwrap();
let mut p = P::from_board(board).ok().unwrap();
assert!(qsearch(&mut p, -10000, 10000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) <= -10000);
}
}
|
set_option
|
identifier_name
|
polygon.rs
|
use image::{GenericImage, ImageBuffer};
use definitions::Image;
use std::cmp::{min, max};
use std::f32;
use std::i32;
use drawing::draw_if_in_bounds;
use drawing::line::draw_line_segment_mut;
/// A 2D point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T: Copy + PartialEq + Eq> {
x: T,
y: T,
}
impl<T: Copy + PartialEq + Eq> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x: x, y: y }
}
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon<I>(image: &I, poly: &[Point<i32>], color: I::Pixel) -> Image<I::Pixel>
where
I: GenericImage,
I::Pixel:'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_convex_polygon_mut(&mut out, poly, color);
out
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon_mut<I>(image: &mut I, poly: &[Point<i32>], color: I::Pixel)
where
I: GenericImage,
I::Pixel:'static,
{
if poly.len() == 0 {
return;
}
if poly[0] == poly[poly.len() - 1] {
panic!(
"First point {:?} == last point {:?}",
poly[0],
poly[poly.len() - 1]
);
}
let mut y_min = i32::MAX;
let mut y_max = i32::MIN;
for p in poly {
y_min = min(y_min, p.y);
y_max = max(y_max, p.y);
}
let (width, height) = image.dimensions();
// Intersect polygon vertical range with image bounds
y_min = max(0, min(y_min, height as i32 - 1));
y_max = max(0, min(y_max, height as i32 - 1));
let mut closed = Vec::with_capacity(poly.len() + 1);
for p in poly {
closed.push(*p);
}
closed.push(poly[0]);
let edges: Vec<&[Point<i32>]> = closed.windows(2).collect();
let mut intersections: Vec<i32> = Vec::new();
for y in y_min..y_max + 1 {
for edge in &edges {
let p0 = edge[0];
let p1 = edge[1];
if p0.y <= y && p1.y >= y || p1.y <= y && p0.y >= y
|
}
intersections.sort();
let mut i = 0;
loop {
// Handle points where multiple lines intersect
while i + 1 < intersections.len() && intersections[i] == intersections[i + 1] {
i += 1;
}
if i >= intersections.len() {
break;
}
if i + 1 == intersections.len() {
draw_if_in_bounds(image, intersections[i], y, color);
break;
}
let from = max(0, min(intersections[i], width as i32 - 1));
let to = max(0, min(intersections[i + 1], width as i32 - 1));
for x in from..to + 1 {
image.put_pixel(x as u32, y as u32, color);
}
i += 2;
}
intersections.clear();
}
for edge in &edges {
let start = (edge[0].x as f32, edge[0].y as f32);
let end = (edge[1].x as f32, edge[1].y as f32);
draw_line_segment_mut(image, start, end, color);
}
}
|
{
// Need to handle horizontal lines specially
if p0.y == p1.y {
intersections.push(p0.x);
intersections.push(p1.x);
} else {
let fraction = (y - p0.y) as f32 / (p1.y - p0.y) as f32;
let inter = p0.x as f32 + fraction * (p1.x - p0.x) as f32;
intersections.push(inter.round() as i32);
}
}
|
conditional_block
|
polygon.rs
|
use image::{GenericImage, ImageBuffer};
use definitions::Image;
use std::cmp::{min, max};
use std::f32;
use std::i32;
use drawing::draw_if_in_bounds;
use drawing::line::draw_line_segment_mut;
/// A 2D point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T: Copy + PartialEq + Eq> {
x: T,
y: T,
}
impl<T: Copy + PartialEq + Eq> Point<T> {
|
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x: x, y: y }
}
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon<I>(image: &I, poly: &[Point<i32>], color: I::Pixel) -> Image<I::Pixel>
where
I: GenericImage,
I::Pixel:'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_convex_polygon_mut(&mut out, poly, color);
out
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon_mut<I>(image: &mut I, poly: &[Point<i32>], color: I::Pixel)
where
I: GenericImage,
I::Pixel:'static,
{
if poly.len() == 0 {
return;
}
if poly[0] == poly[poly.len() - 1] {
panic!(
"First point {:?} == last point {:?}",
poly[0],
poly[poly.len() - 1]
);
}
let mut y_min = i32::MAX;
let mut y_max = i32::MIN;
for p in poly {
y_min = min(y_min, p.y);
y_max = max(y_max, p.y);
}
let (width, height) = image.dimensions();
// Intersect polygon vertical range with image bounds
y_min = max(0, min(y_min, height as i32 - 1));
y_max = max(0, min(y_max, height as i32 - 1));
let mut closed = Vec::with_capacity(poly.len() + 1);
for p in poly {
closed.push(*p);
}
closed.push(poly[0]);
let edges: Vec<&[Point<i32>]> = closed.windows(2).collect();
let mut intersections: Vec<i32> = Vec::new();
for y in y_min..y_max + 1 {
for edge in &edges {
let p0 = edge[0];
let p1 = edge[1];
if p0.y <= y && p1.y >= y || p1.y <= y && p0.y >= y {
// Need to handle horizontal lines specially
if p0.y == p1.y {
intersections.push(p0.x);
intersections.push(p1.x);
} else {
let fraction = (y - p0.y) as f32 / (p1.y - p0.y) as f32;
let inter = p0.x as f32 + fraction * (p1.x - p0.x) as f32;
intersections.push(inter.round() as i32);
}
}
}
intersections.sort();
let mut i = 0;
loop {
// Handle points where multiple lines intersect
while i + 1 < intersections.len() && intersections[i] == intersections[i + 1] {
i += 1;
}
if i >= intersections.len() {
break;
}
if i + 1 == intersections.len() {
draw_if_in_bounds(image, intersections[i], y, color);
break;
}
let from = max(0, min(intersections[i], width as i32 - 1));
let to = max(0, min(intersections[i + 1], width as i32 - 1));
for x in from..to + 1 {
image.put_pixel(x as u32, y as u32, color);
}
i += 2;
}
intersections.clear();
}
for edge in &edges {
let start = (edge[0].x as f32, edge[0].y as f32);
let end = (edge[1].x as f32, edge[1].y as f32);
draw_line_segment_mut(image, start, end, color);
}
}
|
/// Construct a point at (x, y).
|
random_line_split
|
polygon.rs
|
use image::{GenericImage, ImageBuffer};
use definitions::Image;
use std::cmp::{min, max};
use std::f32;
use std::i32;
use drawing::draw_if_in_bounds;
use drawing::line::draw_line_segment_mut;
/// A 2D point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T: Copy + PartialEq + Eq> {
x: T,
y: T,
}
impl<T: Copy + PartialEq + Eq> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T>
|
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon<I>(image: &I, poly: &[Point<i32>], color: I::Pixel) -> Image<I::Pixel>
where
I: GenericImage,
I::Pixel:'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_convex_polygon_mut(&mut out, poly, color);
out
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon_mut<I>(image: &mut I, poly: &[Point<i32>], color: I::Pixel)
where
I: GenericImage,
I::Pixel:'static,
{
if poly.len() == 0 {
return;
}
if poly[0] == poly[poly.len() - 1] {
panic!(
"First point {:?} == last point {:?}",
poly[0],
poly[poly.len() - 1]
);
}
let mut y_min = i32::MAX;
let mut y_max = i32::MIN;
for p in poly {
y_min = min(y_min, p.y);
y_max = max(y_max, p.y);
}
let (width, height) = image.dimensions();
// Intersect polygon vertical range with image bounds
y_min = max(0, min(y_min, height as i32 - 1));
y_max = max(0, min(y_max, height as i32 - 1));
let mut closed = Vec::with_capacity(poly.len() + 1);
for p in poly {
closed.push(*p);
}
closed.push(poly[0]);
let edges: Vec<&[Point<i32>]> = closed.windows(2).collect();
let mut intersections: Vec<i32> = Vec::new();
for y in y_min..y_max + 1 {
for edge in &edges {
let p0 = edge[0];
let p1 = edge[1];
if p0.y <= y && p1.y >= y || p1.y <= y && p0.y >= y {
// Need to handle horizontal lines specially
if p0.y == p1.y {
intersections.push(p0.x);
intersections.push(p1.x);
} else {
let fraction = (y - p0.y) as f32 / (p1.y - p0.y) as f32;
let inter = p0.x as f32 + fraction * (p1.x - p0.x) as f32;
intersections.push(inter.round() as i32);
}
}
}
intersections.sort();
let mut i = 0;
loop {
// Handle points where multiple lines intersect
while i + 1 < intersections.len() && intersections[i] == intersections[i + 1] {
i += 1;
}
if i >= intersections.len() {
break;
}
if i + 1 == intersections.len() {
draw_if_in_bounds(image, intersections[i], y, color);
break;
}
let from = max(0, min(intersections[i], width as i32 - 1));
let to = max(0, min(intersections[i + 1], width as i32 - 1));
for x in from..to + 1 {
image.put_pixel(x as u32, y as u32, color);
}
i += 2;
}
intersections.clear();
}
for edge in &edges {
let start = (edge[0].x as f32, edge[0].y as f32);
let end = (edge[1].x as f32, edge[1].y as f32);
draw_line_segment_mut(image, start, end, color);
}
}
|
{
Point::<T> { x: x, y: y }
}
|
identifier_body
|
polygon.rs
|
use image::{GenericImage, ImageBuffer};
use definitions::Image;
use std::cmp::{min, max};
use std::f32;
use std::i32;
use drawing::draw_if_in_bounds;
use drawing::line::draw_line_segment_mut;
/// A 2D point.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Point<T: Copy + PartialEq + Eq> {
x: T,
y: T,
}
impl<T: Copy + PartialEq + Eq> Point<T> {
/// Construct a point at (x, y).
pub fn new(x: T, y: T) -> Point<T> {
Point::<T> { x: x, y: y }
}
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn
|
<I>(image: &I, poly: &[Point<i32>], color: I::Pixel) -> Image<I::Pixel>
where
I: GenericImage,
I::Pixel:'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_convex_polygon_mut(&mut out, poly, color);
out
}
/// Draws as much of a filled convex polygon as lies within image bounds. The provided
/// list of points should be an open path, i.e. the first and last points must not be equal.
/// An implicit edge is added from the last to the first point in the slice.
///
/// Does not validate that input is convex.
pub fn draw_convex_polygon_mut<I>(image: &mut I, poly: &[Point<i32>], color: I::Pixel)
where
I: GenericImage,
I::Pixel:'static,
{
if poly.len() == 0 {
return;
}
if poly[0] == poly[poly.len() - 1] {
panic!(
"First point {:?} == last point {:?}",
poly[0],
poly[poly.len() - 1]
);
}
let mut y_min = i32::MAX;
let mut y_max = i32::MIN;
for p in poly {
y_min = min(y_min, p.y);
y_max = max(y_max, p.y);
}
let (width, height) = image.dimensions();
// Intersect polygon vertical range with image bounds
y_min = max(0, min(y_min, height as i32 - 1));
y_max = max(0, min(y_max, height as i32 - 1));
let mut closed = Vec::with_capacity(poly.len() + 1);
for p in poly {
closed.push(*p);
}
closed.push(poly[0]);
let edges: Vec<&[Point<i32>]> = closed.windows(2).collect();
let mut intersections: Vec<i32> = Vec::new();
for y in y_min..y_max + 1 {
for edge in &edges {
let p0 = edge[0];
let p1 = edge[1];
if p0.y <= y && p1.y >= y || p1.y <= y && p0.y >= y {
// Need to handle horizontal lines specially
if p0.y == p1.y {
intersections.push(p0.x);
intersections.push(p1.x);
} else {
let fraction = (y - p0.y) as f32 / (p1.y - p0.y) as f32;
let inter = p0.x as f32 + fraction * (p1.x - p0.x) as f32;
intersections.push(inter.round() as i32);
}
}
}
intersections.sort();
let mut i = 0;
loop {
// Handle points where multiple lines intersect
while i + 1 < intersections.len() && intersections[i] == intersections[i + 1] {
i += 1;
}
if i >= intersections.len() {
break;
}
if i + 1 == intersections.len() {
draw_if_in_bounds(image, intersections[i], y, color);
break;
}
let from = max(0, min(intersections[i], width as i32 - 1));
let to = max(0, min(intersections[i + 1], width as i32 - 1));
for x in from..to + 1 {
image.put_pixel(x as u32, y as u32, color);
}
i += 2;
}
intersections.clear();
}
for edge in &edges {
let start = (edge[0].x as f32, edge[0].y as f32);
let end = (edge[1].x as f32, edge[1].y as f32);
draw_line_segment_mut(image, start, end, color);
}
}
|
draw_convex_polygon
|
identifier_name
|
access_control_allow_origin.rs
|
use std::fmt::{self, Display};
use header::{Header, HeaderFormat};
/// The `Access-Control-Allow-Origin` response header,
/// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header)
///
/// The `Access-Control-Allow-Origin` header indicates whether a resource
/// can be shared based by returning the value of the Origin request header,
/// "*", or "null" in the response.
///
/// # ABNF
/// ```plain
/// Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"
/// ```
///
/// # Example values
/// * `null`
/// * `*`
/// * `http://google.com/`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowOrigin::Any
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowOrigin::Null,
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
|
/// Allow all origins
Any,
/// A hidden origin
Null,
/// Allow one particular origin
Value(String),
}
impl Header for AccessControlAllowOrigin {
fn header_name() -> &'static str {
"Access-Control-Allow-Origin"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<AccessControlAllowOrigin> {
if raw.len()!= 1 {
return Err(::Error::Header)
}
let value = unsafe { raw.get_unchecked(0) };
Ok(match &value[..] {
b"*" => AccessControlAllowOrigin::Any,
b"null" => AccessControlAllowOrigin::Null,
_ => AccessControlAllowOrigin::Value(try!(String::from_utf8(value.clone())))
})
}
}
impl HeaderFormat for AccessControlAllowOrigin {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AccessControlAllowOrigin::Any => f.write_str("*"),
AccessControlAllowOrigin::Null => f.write_str("null"),
AccessControlAllowOrigin::Value(ref url) => Display::fmt(url, f),
}
}
}
impl Display for AccessControlAllowOrigin {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.fmt_header(f)
}
}
#[cfg(test)]
mod test_access_control_allow_orgin {
use header::*;
use super::AccessControlAllowOrigin as HeaderField;
test_header!(test1, vec![b"null"]);
test_header!(test2, vec![b"*"]);
test_header!(test3, vec![b"http://google.com/"]);
}
|
/// AccessControlAllowOrigin::Value("http://hyper.rs".to_owned())
/// );
/// ```
#[derive(Clone, PartialEq, Debug)]
pub enum AccessControlAllowOrigin {
|
random_line_split
|
access_control_allow_origin.rs
|
use std::fmt::{self, Display};
use header::{Header, HeaderFormat};
/// The `Access-Control-Allow-Origin` response header,
/// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header)
///
/// The `Access-Control-Allow-Origin` header indicates whether a resource
/// can be shared based by returning the value of the Origin request header,
/// "*", or "null" in the response.
///
/// # ABNF
/// ```plain
/// Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"
/// ```
///
/// # Example values
/// * `null`
/// * `*`
/// * `http://google.com/`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowOrigin::Any
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowOrigin::Null,
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AccessControlAllowOrigin};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowOrigin::Value("http://hyper.rs".to_owned())
/// );
/// ```
#[derive(Clone, PartialEq, Debug)]
pub enum AccessControlAllowOrigin {
/// Allow all origins
Any,
/// A hidden origin
Null,
/// Allow one particular origin
Value(String),
}
impl Header for AccessControlAllowOrigin {
fn header_name() -> &'static str {
"Access-Control-Allow-Origin"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<AccessControlAllowOrigin> {
if raw.len()!= 1 {
return Err(::Error::Header)
}
let value = unsafe { raw.get_unchecked(0) };
Ok(match &value[..] {
b"*" => AccessControlAllowOrigin::Any,
b"null" => AccessControlAllowOrigin::Null,
_ => AccessControlAllowOrigin::Value(try!(String::from_utf8(value.clone())))
})
}
}
impl HeaderFormat for AccessControlAllowOrigin {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AccessControlAllowOrigin::Any => f.write_str("*"),
AccessControlAllowOrigin::Null => f.write_str("null"),
AccessControlAllowOrigin::Value(ref url) => Display::fmt(url, f),
}
}
}
impl Display for AccessControlAllowOrigin {
fn
|
(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.fmt_header(f)
}
}
#[cfg(test)]
mod test_access_control_allow_orgin {
use header::*;
use super::AccessControlAllowOrigin as HeaderField;
test_header!(test1, vec![b"null"]);
test_header!(test2, vec![b"*"]);
test_header!(test3, vec![b"http://google.com/"]);
}
|
fmt
|
identifier_name
|
uppercase_test.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>>
*/
mod uppercase;
use uppercase::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn hello() {
let input = include_str!("uppercase/fixtures/hello.txt");
let expected = include_str!("uppercase/fixtures/hello.expected");
test_fixture(transform_fixture, "hello.txt", "uppercase/fixtures/hello.expected", input, expected);
}
#[test]
fn world()
|
{
let input = include_str!("uppercase/fixtures/world.txt");
let expected = include_str!("uppercase/fixtures/world.expected");
test_fixture(transform_fixture, "world.txt", "uppercase/fixtures/world.expected", input, expected);
}
|
identifier_body
|
|
uppercase_test.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>>
*/
mod uppercase;
use uppercase::transform_fixture;
use fixture_tests::test_fixture;
|
let expected = include_str!("uppercase/fixtures/hello.expected");
test_fixture(transform_fixture, "hello.txt", "uppercase/fixtures/hello.expected", input, expected);
}
#[test]
fn world() {
let input = include_str!("uppercase/fixtures/world.txt");
let expected = include_str!("uppercase/fixtures/world.expected");
test_fixture(transform_fixture, "world.txt", "uppercase/fixtures/world.expected", input, expected);
}
|
#[test]
fn hello() {
let input = include_str!("uppercase/fixtures/hello.txt");
|
random_line_split
|
uppercase_test.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>>
*/
mod uppercase;
use uppercase::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn hello() {
let input = include_str!("uppercase/fixtures/hello.txt");
let expected = include_str!("uppercase/fixtures/hello.expected");
test_fixture(transform_fixture, "hello.txt", "uppercase/fixtures/hello.expected", input, expected);
}
#[test]
fn
|
() {
let input = include_str!("uppercase/fixtures/world.txt");
let expected = include_str!("uppercase/fixtures/world.expected");
test_fixture(transform_fixture, "world.txt", "uppercase/fixtures/world.expected", input, expected);
}
|
world
|
identifier_name
|
slice-panic-1.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 that if a slicing expr[..] fails, the correct cleanups happen.
use std::thread;
struct Foo;
static mut DTOR_COUNT: int = 0;
impl Drop for Foo {
fn drop(&mut self)
|
}
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
{ unsafe { DTOR_COUNT += 1; } }
|
identifier_body
|
slice-panic-1.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 that if a slicing expr[..] fails, the correct cleanups happen.
use std::thread;
struct Foo;
static mut DTOR_COUNT: int = 0;
impl Drop for Foo {
fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } }
}
fn
|
() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
foo
|
identifier_name
|
slice-panic-1.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 that if a slicing expr[..] fails, the correct cleanups happen.
use std::thread;
struct Foo;
static mut DTOR_COUNT: int = 0;
impl Drop for Foo {
fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } }
}
fn foo() {
let x: &[_] = &[Foo, Foo];
&x[3..4];
}
|
fn main() {
let _ = thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
|
random_line_split
|
|
main.rs
|
extern mod actor;
extern mod std;
use actor::actor::{Actor, SurviveOrDie, Survive, Die};
use actor::system::{System};
use std::comm::{SharedChan};
enum PingPongMsg { Ping, Pong, }
struct PingPong {
counter: uint,
master: SharedChan<bool>,
}
impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg, C> for
PingPong {
fn on_receive(&mut self, msg: PingPongMsg, chan: &C) -> SurviveOrDie {
match msg { Ping => chan.send(Pong), Pong => chan.send(Ping) }
self.counter -= 1;
if (self.counter == 0u) { self.master.send(true); return Die };
Survive
}
}
fn new_pingpong(args: (uint, SharedChan<bool>)) -> PingPong {
let (counter, master) = args;
PingPong{counter: counter, master: master,}
}
fn
|
() {
let mut system = System::new();
let (master_port, master_chan): (Port<bool>, Chan<bool>) = stream();
let master_chan = SharedChan::new(master_chan);
let (port1, chan1): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
let (port2, chan2): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
chan1.send(Ping);
system.add_actor_from_port_and_chan(port1, chan2,
(10u, master_chan.clone()),
new_pingpong);
system.add_actor_from_port_and_chan(port2, chan1,
(10u, master_chan.clone()),
new_pingpong);
// Both actors must terminate
assert_eq!(true, master_port.recv());
assert_eq!(true, master_port.recv());
}
|
main
|
identifier_name
|
main.rs
|
extern mod actor;
extern mod std;
use actor::actor::{Actor, SurviveOrDie, Survive, Die};
use actor::system::{System};
use std::comm::{SharedChan};
enum PingPongMsg { Ping, Pong, }
struct PingPong {
counter: uint,
master: SharedChan<bool>,
}
impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg, C> for
PingPong {
fn on_receive(&mut self, msg: PingPongMsg, chan: &C) -> SurviveOrDie {
match msg { Ping => chan.send(Pong), Pong => chan.send(Ping) }
self.counter -= 1;
if (self.counter == 0u) { self.master.send(true); return Die };
Survive
}
}
fn new_pingpong(args: (uint, SharedChan<bool>)) -> PingPong
|
fn main() {
let mut system = System::new();
let (master_port, master_chan): (Port<bool>, Chan<bool>) = stream();
let master_chan = SharedChan::new(master_chan);
let (port1, chan1): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
let (port2, chan2): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
chan1.send(Ping);
system.add_actor_from_port_and_chan(port1, chan2,
(10u, master_chan.clone()),
new_pingpong);
system.add_actor_from_port_and_chan(port2, chan1,
(10u, master_chan.clone()),
new_pingpong);
// Both actors must terminate
assert_eq!(true, master_port.recv());
assert_eq!(true, master_port.recv());
}
|
{
let (counter, master) = args;
PingPong{counter: counter, master: master,}
}
|
identifier_body
|
main.rs
|
extern mod actor;
extern mod std;
use actor::actor::{Actor, SurviveOrDie, Survive, Die};
use actor::system::{System};
use std::comm::{SharedChan};
enum PingPongMsg { Ping, Pong, }
struct PingPong {
counter: uint,
master: SharedChan<bool>,
}
impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg, C> for
PingPong {
fn on_receive(&mut self, msg: PingPongMsg, chan: &C) -> SurviveOrDie {
match msg { Ping => chan.send(Pong), Pong => chan.send(Ping) }
self.counter -= 1;
if (self.counter == 0u) { self.master.send(true); return Die };
Survive
}
}
fn new_pingpong(args: (uint, SharedChan<bool>)) -> PingPong {
let (counter, master) = args;
PingPong{counter: counter, master: master,}
}
fn main() {
let mut system = System::new();
let (master_port, master_chan): (Port<bool>, Chan<bool>) = stream();
let master_chan = SharedChan::new(master_chan);
let (port1, chan1): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
let (port2, chan2): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream();
chan1.send(Ping);
system.add_actor_from_port_and_chan(port1, chan2,
(10u, master_chan.clone()),
new_pingpong);
|
assert_eq!(true, master_port.recv());
}
|
system.add_actor_from_port_and_chan(port2, chan1,
(10u, master_chan.clone()),
new_pingpong);
// Both actors must terminate
assert_eq!(true , master_port.recv());
|
random_line_split
|
mission_select.rs
|
use voodoo::window::{Point, Window};
use game_state::{UiState, ModelView};
const TITLE: [&'static str; 6] = [
"โโโโโโโ โโโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโโโโ โโโ",
"โโโโโโโโโโโโโโโโ โโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โโโโ",
"โโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโ โโโโโโโโโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโ โโโ",
"โโโ โโโโโโโโโโโโโโ โโโ โโโโโโ โโโ โโโโโโโโโโ โโโ",
];
pub enum UiEvent {
KeyPressed,
Tick,
}
pub enum Transition {
Ui(UiState),
Level(usize),
}
pub struct State {
window: Window,
}
impl State {
pub fn new(window: Window) -> State {
State {
window: window,
}
}
}
impl ::std::fmt::Debug for State {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "mission_select::State")
}
}
pub fn next(_state: &mut State, event: UiEvent, _mv: &mut ModelView) -> Transition {
use self::UiEvent::*;
match event {
KeyPressed => Transition::Level(0),
Tick => Transition::Ui(UiState::Unselected),
}
}
pub fn display(mission_state: &mut State, compositor: &mut ::voodoo::compositor::Compositor, _mv: &mut ModelView) {
for (offset, line) in TITLE.iter().enumerate() {
mission_state.window.print_at(Point::new(13, 6 + offset as u16), *line);
}
mission_state.window.print_at(Point::new(30, 14), "PRESS ANY KEY TO BEGIN");
mission_state.window.print_at(Point
|
::new(33, 15), "PRESS Q TO QUIT");
mission_state.window.refresh(compositor);
}
|
identifier_body
|
|
mission_select.rs
|
use voodoo::window::{Point, Window};
use game_state::{UiState, ModelView};
const TITLE: [&'static str; 6] = [
"โโโโโโโ โโโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโโโโ โโโ",
"โโโโโโโโโโโโโโโโ โโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โโโโ",
"โโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโ โโโโโโโโโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโ โโโ",
"โโโ โโโโโโโโโโโโโโ โโโ โโโโโโ โโโ โโโโโโโโโโ โโโ",
];
pub enum UiEvent {
KeyPressed,
Tick,
}
pub enum Transition {
Ui(UiState),
Level(usize),
}
pub struct State {
window: Window,
}
impl State {
pub fn new(window: Window) -> State {
State {
window: window,
}
}
}
impl ::std::fmt::Debug for State {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "mission_select::State")
}
}
pub fn next(_state: &mut State, event: UiEvent, _mv: &mut ModelView) -> Transition {
use self::UiEvent::*;
match event {
KeyPressed => Transition::Level(0),
Tick => Transition::Ui(UiState::Unselected),
}
}
pub fn display(mission_state: &mut Stat
|
compositor: &mut ::voodoo::compositor::Compositor, _mv: &mut ModelView) {
for (offset, line) in TITLE.iter().enumerate() {
mission_state.window.print_at(Point::new(13, 6 + offset as u16), *line);
}
mission_state.window.print_at(Point::new(30, 14), "PRESS ANY KEY TO BEGIN");
mission_state.window.print_at(Point::new(33, 15), "PRESS Q TO QUIT");
mission_state.window.refresh(compositor);
}
|
e,
|
identifier_name
|
mission_select.rs
|
use voodoo::window::{Point, Window};
use game_state::{UiState, ModelView};
const TITLE: [&'static str; 6] = [
"โโโโโโโ โโโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโโโโ โโโ",
"โโโโโโโโโโโโโโโโ โโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โโโโ",
"โโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโโโโโโโโโโโโโ โโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโ",
"โโ โโโโโโโโโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโ โโโ",
"โโโ โโโโโโโโโโโโโโ โโโ โโโโโโ โโโ โโโโโโโโโโ โโโ",
];
|
pub enum Transition {
Ui(UiState),
Level(usize),
}
pub struct State {
window: Window,
}
impl State {
pub fn new(window: Window) -> State {
State {
window: window,
}
}
}
impl ::std::fmt::Debug for State {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "mission_select::State")
}
}
pub fn next(_state: &mut State, event: UiEvent, _mv: &mut ModelView) -> Transition {
use self::UiEvent::*;
match event {
KeyPressed => Transition::Level(0),
Tick => Transition::Ui(UiState::Unselected),
}
}
pub fn display(mission_state: &mut State, compositor: &mut ::voodoo::compositor::Compositor, _mv: &mut ModelView) {
for (offset, line) in TITLE.iter().enumerate() {
mission_state.window.print_at(Point::new(13, 6 + offset as u16), *line);
}
mission_state.window.print_at(Point::new(30, 14), "PRESS ANY KEY TO BEGIN");
mission_state.window.print_at(Point::new(33, 15), "PRESS Q TO QUIT");
mission_state.window.refresh(compositor);
}
|
pub enum UiEvent {
KeyPressed,
Tick,
}
|
random_line_split
|
io.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.
pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
#[cfg(test)]
#[allow(dead_code)] // not used on emscripten
pub mod test {
use path::{Path, PathBuf};
use env;
use rand::{self, RngCore};
use fs;
pub struct TempDir(PathBuf);
impl TempDir {
pub fn join(&self, path: &str) -> PathBuf {
let TempDir(ref p) = *self;
p.join(path)
}
pub fn path<'a>(&'a self) -> &'a Path {
let TempDir(ref p) = *self;
p
}
}
impl Drop for TempDir {
fn
|
(&mut self) {
// Gee, seeing how we're testing the fs module I sure hope that we
// at least implement this correctly!
let TempDir(ref p) = *self;
fs::remove_dir_all(p).unwrap();
}
}
pub fn tmpdir() -> TempDir {
let p = env::temp_dir();
let mut r = rand::thread_rng();
let ret = p.join(&format!("rust-{}", r.next_u32()));
fs::create_dir(&ret).unwrap();
TempDir(ret)
}
}
|
drop
|
identifier_name
|
io.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
|
#[cfg(test)]
#[allow(dead_code)] // not used on emscripten
pub mod test {
use path::{Path, PathBuf};
use env;
use rand::{self, RngCore};
use fs;
pub struct TempDir(PathBuf);
impl TempDir {
pub fn join(&self, path: &str) -> PathBuf {
let TempDir(ref p) = *self;
p.join(path)
}
pub fn path<'a>(&'a self) -> &'a Path {
let TempDir(ref p) = *self;
p
}
}
impl Drop for TempDir {
fn drop(&mut self) {
// Gee, seeing how we're testing the fs module I sure hope that we
// at least implement this correctly!
let TempDir(ref p) = *self;
fs::remove_dir_all(p).unwrap();
}
}
pub fn tmpdir() -> TempDir {
let p = env::temp_dir();
let mut r = rand::thread_rng();
let ret = p.join(&format!("rust-{}", r.next_u32()));
fs::create_dir(&ret).unwrap();
TempDir(ret)
}
}
|
// <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.
pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
|
random_line_split
|
io.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.
pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
#[cfg(test)]
#[allow(dead_code)] // not used on emscripten
pub mod test {
use path::{Path, PathBuf};
use env;
use rand::{self, RngCore};
use fs;
pub struct TempDir(PathBuf);
impl TempDir {
pub fn join(&self, path: &str) -> PathBuf {
let TempDir(ref p) = *self;
p.join(path)
}
pub fn path<'a>(&'a self) -> &'a Path
|
}
impl Drop for TempDir {
fn drop(&mut self) {
// Gee, seeing how we're testing the fs module I sure hope that we
// at least implement this correctly!
let TempDir(ref p) = *self;
fs::remove_dir_all(p).unwrap();
}
}
pub fn tmpdir() -> TempDir {
let p = env::temp_dir();
let mut r = rand::thread_rng();
let ret = p.join(&format!("rust-{}", r.next_u32()));
fs::create_dir(&ret).unwrap();
TempDir(ret)
}
}
|
{
let TempDir(ref p) = *self;
p
}
|
identifier_body
|
debug.rs
|
//! Tests for our own Debug implementation.
//!
//! The tests check against expected output. This may be a bit fragile, but it is likely OK for
//! actual use.
use prost::alloc::{format, string::String};
// Borrow some types from other places.
#[cfg(feature = "std")]
use crate::message_encoding::Basic;
use crate::message_encoding::BasicEnumeration;
/// Some real-life message
#[test]
#[cfg(feature = "std")]
fn basic() {
let mut basic = Basic::default();
assert_eq!(
format!("{:?}", basic),
"Basic { \
int32: 0, \
bools: [], \
string: \"\", \
optional_string: None, \
enumeration: ZERO, \
enumeration_map: {}, \
string_map: {}, \
enumeration_btree_map: {}, \
string_btree_map: {}, \
oneof: None \
}"
);
basic
.enumeration_map
.insert(0, BasicEnumeration::TWO as i32);
basic.enumeration = 42;
assert_eq!(
format!("{:?}", basic),
"Basic { \
int32: 0, \
bools: [], \
string: \"\", \
optional_string: None, \
enumeration: 42, \
enumeration_map: {0: TWO}, \
string_map: {}, \
enumeration_btree_map: {}, \
string_btree_map: {}, \
oneof: None \
}"
);
}
/*
TODO(danburkert/prost#56):
/// A special case with a tuple struct
#[test]
fn tuple_struct() {
#[derive(Clone, PartialEq, Message)]
struct NewType(
#[prost(enumeration="BasicEnumeration", tag="5")]
i32,
);
assert_eq!(format!("{:?}", NewType(BasicEnumeration::TWO as i32)), "NewType(TWO)");
assert_eq!(format!("{:?}", NewType(42)), "NewType(42)");
|
}
*/
#[derive(Clone, PartialEq, prost::Oneof)]
pub enum OneofWithEnum {
#[prost(int32, tag = "8")]
Int(i32),
#[prost(string, tag = "9")]
String(String),
#[prost(enumeration = "BasicEnumeration", tag = "10")]
Enumeration(i32),
}
#[derive(Clone, PartialEq, prost::Message)]
struct MessageWithOneof {
#[prost(oneof = "OneofWithEnum", tags = "8, 9, 10")]
of: Option<OneofWithEnum>,
}
/// Enumerations inside oneofs
#[test]
fn oneof_with_enum() {
let msg = MessageWithOneof {
of: Some(OneofWithEnum::Enumeration(BasicEnumeration::TWO as i32)),
};
assert_eq!(
format!("{:?}", msg),
"MessageWithOneof { of: Some(Enumeration(TWO)) }"
);
}
|
random_line_split
|
|
debug.rs
|
//! Tests for our own Debug implementation.
//!
//! The tests check against expected output. This may be a bit fragile, but it is likely OK for
//! actual use.
use prost::alloc::{format, string::String};
// Borrow some types from other places.
#[cfg(feature = "std")]
use crate::message_encoding::Basic;
use crate::message_encoding::BasicEnumeration;
/// Some real-life message
#[test]
#[cfg(feature = "std")]
fn basic() {
let mut basic = Basic::default();
assert_eq!(
format!("{:?}", basic),
"Basic { \
int32: 0, \
bools: [], \
string: \"\", \
optional_string: None, \
enumeration: ZERO, \
enumeration_map: {}, \
string_map: {}, \
enumeration_btree_map: {}, \
string_btree_map: {}, \
oneof: None \
}"
);
basic
.enumeration_map
.insert(0, BasicEnumeration::TWO as i32);
basic.enumeration = 42;
assert_eq!(
format!("{:?}", basic),
"Basic { \
int32: 0, \
bools: [], \
string: \"\", \
optional_string: None, \
enumeration: 42, \
enumeration_map: {0: TWO}, \
string_map: {}, \
enumeration_btree_map: {}, \
string_btree_map: {}, \
oneof: None \
}"
);
}
/*
TODO(danburkert/prost#56):
/// A special case with a tuple struct
#[test]
fn tuple_struct() {
#[derive(Clone, PartialEq, Message)]
struct NewType(
#[prost(enumeration="BasicEnumeration", tag="5")]
i32,
);
assert_eq!(format!("{:?}", NewType(BasicEnumeration::TWO as i32)), "NewType(TWO)");
assert_eq!(format!("{:?}", NewType(42)), "NewType(42)");
}
*/
#[derive(Clone, PartialEq, prost::Oneof)]
pub enum OneofWithEnum {
#[prost(int32, tag = "8")]
Int(i32),
#[prost(string, tag = "9")]
String(String),
#[prost(enumeration = "BasicEnumeration", tag = "10")]
Enumeration(i32),
}
#[derive(Clone, PartialEq, prost::Message)]
struct
|
{
#[prost(oneof = "OneofWithEnum", tags = "8, 9, 10")]
of: Option<OneofWithEnum>,
}
/// Enumerations inside oneofs
#[test]
fn oneof_with_enum() {
let msg = MessageWithOneof {
of: Some(OneofWithEnum::Enumeration(BasicEnumeration::TWO as i32)),
};
assert_eq!(
format!("{:?}", msg),
"MessageWithOneof { of: Some(Enumeration(TWO)) }"
);
}
|
MessageWithOneof
|
identifier_name
|
iter.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Iterator utilities.
use std::iter::Iterator;
/// Non-short-circuiting version of `Zip`. See `longest_zip()` for details.
pub struct LongestZip<A, B> {
a: A,
b: B,
}
impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator {
type Item = (Option<A::Item>, Option<B::Item>);
fn next(&mut self) -> Option<Self::Item> {
let v_a = self.a.next();
let v_b = self.b.next();
if v_a.is_some() || v_b.is_some() {
return Some((v_a, v_b));
} else
|
}
}
/// Returns an iterator which simulataneously walks over two other iterators until _both_ of
/// them are exhausted. It is similar to `zip()` method of `Iterator`, but it does not stop
/// when one of the iterators in exhausted.
///
/// Example:
/// ```
/// assert_eq!(longest_zip(&[1, 2, 3], &[5, 6]).collect::<Vec<_>>(),
/// &[
/// (Some(&1), Some(&5)),
/// (Some(&2), Some(&6)),
/// (Some(&3), None)
/// ]);
/// ```
pub fn longest_zip<A, B>(iter1: A, iter2: B) -> LongestZip<A::IntoIter, B::IntoIter>
where A: IntoIterator, B: IntoIterator
{
LongestZip { a: iter1.into_iter(), b: iter2.into_iter() }
}
|
{
return None;
}
|
conditional_block
|
iter.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Iterator utilities.
use std::iter::Iterator;
/// Non-short-circuiting version of `Zip`. See `longest_zip()` for details.
pub struct
|
<A, B> {
a: A,
b: B,
}
impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator {
type Item = (Option<A::Item>, Option<B::Item>);
fn next(&mut self) -> Option<Self::Item> {
let v_a = self.a.next();
let v_b = self.b.next();
if v_a.is_some() || v_b.is_some() {
return Some((v_a, v_b));
} else {
return None;
}
}
}
/// Returns an iterator which simulataneously walks over two other iterators until _both_ of
/// them are exhausted. It is similar to `zip()` method of `Iterator`, but it does not stop
/// when one of the iterators in exhausted.
///
/// Example:
/// ```
/// assert_eq!(longest_zip(&[1, 2, 3], &[5, 6]).collect::<Vec<_>>(),
/// &[
/// (Some(&1), Some(&5)),
/// (Some(&2), Some(&6)),
/// (Some(&3), None)
/// ]);
/// ```
pub fn longest_zip<A, B>(iter1: A, iter2: B) -> LongestZip<A::IntoIter, B::IntoIter>
where A: IntoIterator, B: IntoIterator
{
LongestZip { a: iter1.into_iter(), b: iter2.into_iter() }
}
|
LongestZip
|
identifier_name
|
iter.rs
|
// Copyright (c) 2016, ilammy
//
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
//! Iterator utilities.
use std::iter::Iterator;
/// Non-short-circuiting version of `Zip`. See `longest_zip()` for details.
pub struct LongestZip<A, B> {
a: A,
b: B,
}
impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator {
type Item = (Option<A::Item>, Option<B::Item>);
fn next(&mut self) -> Option<Self::Item> {
let v_a = self.a.next();
let v_b = self.b.next();
if v_a.is_some() || v_b.is_some() {
return Some((v_a, v_b));
} else {
return None;
}
}
}
/// Returns an iterator which simulataneously walks over two other iterators until _both_ of
/// them are exhausted. It is similar to `zip()` method of `Iterator`, but it does not stop
/// when one of the iterators in exhausted.
///
/// Example:
/// ```
/// assert_eq!(longest_zip(&[1, 2, 3], &[5, 6]).collect::<Vec<_>>(),
/// &[
/// (Some(&1), Some(&5)),
/// (Some(&2), Some(&6)),
/// (Some(&3), None)
/// ]);
/// ```
pub fn longest_zip<A, B>(iter1: A, iter2: B) -> LongestZip<A::IntoIter, B::IntoIter>
where A: IntoIterator, B: IntoIterator
|
{
LongestZip { a: iter1.into_iter(), b: iter2.into_iter() }
}
|
identifier_body
|
|
iter.rs
|
// Copyright (c) 2016, ilammy
//
|
//! Iterator utilities.
use std::iter::Iterator;
/// Non-short-circuiting version of `Zip`. See `longest_zip()` for details.
pub struct LongestZip<A, B> {
a: A,
b: B,
}
impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator {
type Item = (Option<A::Item>, Option<B::Item>);
fn next(&mut self) -> Option<Self::Item> {
let v_a = self.a.next();
let v_b = self.b.next();
if v_a.is_some() || v_b.is_some() {
return Some((v_a, v_b));
} else {
return None;
}
}
}
/// Returns an iterator which simulataneously walks over two other iterators until _both_ of
/// them are exhausted. It is similar to `zip()` method of `Iterator`, but it does not stop
/// when one of the iterators in exhausted.
///
/// Example:
/// ```
/// assert_eq!(longest_zip(&[1, 2, 3], &[5, 6]).collect::<Vec<_>>(),
/// &[
/// (Some(&1), Some(&5)),
/// (Some(&2), Some(&6)),
/// (Some(&3), None)
/// ]);
/// ```
pub fn longest_zip<A, B>(iter1: A, iter2: B) -> LongestZip<A::IntoIter, B::IntoIter>
where A: IntoIterator, B: IntoIterator
{
LongestZip { a: iter1.into_iter(), b: iter2.into_iter() }
}
|
// Licensed under MIT license (see LICENSE file in the root directory).
// This file may be copied, distributed, and modified only in accordance
// with the terms specified by this license.
|
random_line_split
|
no_0216_combination_sum_iii.rs
|
struct Solution;
impl Solution {
pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(k, n, 1, &mut vec![], &mut ans);
ans
}
fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>)
|
use super::*;
#[test]
fn test_combination_sum3() {
assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]);
assert_eq!(
Solution::combination_sum3(3, 9),
vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]]
);
}
}
|
{
if k == 0 && n == 0 && tmp.len() > 0 {
ans.push(tmp.clone());
return;
}
for i in start..=9 {
// ๅ้ข็้ฝๆฏ n ๅคงไบ๏ผไธ็จๅ่ฎก็ฎไบใ
if i > n {
break;
}
tmp.push(i);
Self::helper(k - 1, n - i, i + 1, tmp, ans);
tmp.pop();
}
}
}
#[cfg(test)]
mod tests {
|
identifier_body
|
no_0216_combination_sum_iii.rs
|
struct Solution;
impl Solution {
pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(k, n, 1, &mut vec![], &mut ans);
ans
}
fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if k == 0 && n == 0 && tmp.len() > 0
|
for i in start..=9 {
// ๅ้ข็้ฝๆฏ n ๅคงไบ๏ผไธ็จๅ่ฎก็ฎไบใ
if i > n {
break;
}
tmp.push(i);
Self::helper(k - 1, n - i, i + 1, tmp, ans);
tmp.pop();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_combination_sum3() {
assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]);
assert_eq!(
Solution::combination_sum3(3, 9),
vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]]
);
}
}
|
{
ans.push(tmp.clone());
return;
}
|
conditional_block
|
no_0216_combination_sum_iii.rs
|
struct
|
;
impl Solution {
pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
Self::helper(k, n, 1, &mut vec![], &mut ans);
ans
}
fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if k == 0 && n == 0 && tmp.len() > 0 {
ans.push(tmp.clone());
return;
}
for i in start..=9 {
// ๅ้ข็้ฝๆฏ n ๅคงไบ๏ผไธ็จๅ่ฎก็ฎไบใ
if i > n {
break;
}
tmp.push(i);
Self::helper(k - 1, n - i, i + 1, tmp, ans);
tmp.pop();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_combination_sum3() {
assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]);
assert_eq!(
Solution::combination_sum3(3, 9),
vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]]
);
}
}
|
Solution
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.