<commit_before>//! S3 bindings for Rust
#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
// use hyper::header::Headers;
use hyper::client::Response;
use std::io::Read;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/s3.rs"));

pub struct S3Helper<'a> {
	client: S3Client<'a>
}

impl<'a> S3Helper<'a> {
	pub fn new(credentials:&'a AWSCredentials, region:&'a str) -> S3Helper<'a> {
		S3Helper { client: S3Client::new(credentials, region) }
	}

	pub fn list_buckets(&self) -> Result<ListBucketsOutput, AWSError> {
		self.client.list_buckets()
	}

	/// Creates bucket in default us-east-1/us-standard region.
	pub fn create_bucket(&self, bucket_name: &str) -> Result<CreateBucketOutput, AWSError> {
		// TODO: refactor to call create_bucket_in_region
		let mut request = CreateBucketRequest::default();
		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	/// Creates bucket in specified region.
	// TODO: enum for region?
	pub fn create_bucket_in_region(&self, bucket_name: &str, region: &str) -> Result<CreateBucketOutput, AWSError> {
		// TODO: refactor to call create_bucket with location specified
		let mut request = CreateBucketRequest::default();
		// create_bucket_configuration needs to be specified.  It's of type Option<CreateBucketConfiguration>.
		let create_config = CreateBucketConfiguration {location_constraint: region.to_string()};
		request.create_bucket_configuration = Some(create_config);

		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_bucket(&self, bucket_name: &str) -> Result<(), AWSError> {
		let mut request = DeleteBucketRequest::default();
		request.bucket = bucket_name.to_string();
		println!("Deleting bucket");
		let result = self.client.delete_bucket(&request);
		println!("Result is {:?}", result);
		result
	}

	pub fn get_object(&self, bucket_name: &str, object_name: &str) ->  Result<GetObjectOutput, AWSError> {
		let mut request = GetObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.get_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn put_object(&self, bucket_name: &str, object_name: &str, object_as_bytes: &Vec<u8>) ->  Result<PutObjectOutput, AWSError> {
		let mut request = PutObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		request.body = Some(object_as_bytes.clone()); // this needs to be refactored to pass a reference
		let result = self.client.put_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_object(&self, bucket_name: &str, object_name: &str) ->  Result<DeleteObjectOutput, AWSError> {
		let mut request = DeleteObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.delete_object(&request);
		println!("Result is {:?}", result);
		result
	}
}

#[cfg(test)]
mod tests {
	use xml::reader::*;
	use std::io::BufReader;
	use std::fs::File;
	use super::ListBucketsOutputParser;
	use xmlutil::*;

	#[test]
	fn list_buckets_happy_path() {
		let file = File::open("tests/sample-data/s3_get_buckets.xml").unwrap();
	    let file = BufReader::new(file);
	    let mut my_parser  = EventReader::new(file);
	    let my_stack = my_parser.events().peekable();
	    let mut reader = XmlResponseFromFile::new(my_stack);
		reader.next(); // xml start node
		let result = ListBucketsOutputParser::parse_xml("ListAllMyBucketsResult", &mut reader);

		match result {
			Err(_) => panic!("Couldn't parse list_buckets"),
			Ok(_) => return,
		}
	}
}
<commit_msg>Refactors default S3 bucket creation.<commit_after>//! S3 bindings for Rust
#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
// use hyper::header::Headers;
use hyper::client::Response;
use std::io::Read;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/s3.rs"));

pub struct S3Helper<'a> {
	client: S3Client<'a>
}

impl<'a> S3Helper<'a> {
	pub fn new(credentials:&'a AWSCredentials, region:&'a str) -> S3Helper<'a> {
		S3Helper { client: S3Client::new(credentials, region) }
	}

	pub fn list_buckets(&self) -> Result<ListBucketsOutput, AWSError> {
		self.client.list_buckets()
	}

	/// Creates bucket in default us-east-1/us-standard region.
	pub fn create_bucket(&self, bucket_name: &str) -> Result<CreateBucketOutput, AWSError> {
		self.create_bucket_in_region(bucket_name, "")
	}

	/// Creates bucket in specified region.
	// TODO: enum for region?
	pub fn create_bucket_in_region(&self, bucket_name: &str, region: &str) -> Result<CreateBucketOutput, AWSError> {
		let mut request = CreateBucketRequest::default();

		// not specified means us-standard, no need to specify anything for calling AWS:
		if region.len() > 0 {
			let create_config = CreateBucketConfiguration {location_constraint: region.to_string()};
			request.create_bucket_configuration = Some(create_config);
		}

		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_bucket(&self, bucket_name: &str) -> Result<(), AWSError> {
		let mut request = DeleteBucketRequest::default();
		request.bucket = bucket_name.to_string();
		println!("Deleting bucket");
		let result = self.client.delete_bucket(&request);
		println!("Result is {:?}", result);
		result
	}

	pub fn get_object(&self, bucket_name: &str, object_name: &str) ->  Result<GetObjectOutput, AWSError> {
		let mut request = GetObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.get_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn put_object(&self, bucket_name: &str, object_name: &str, object_as_bytes: &Vec<u8>) ->  Result<PutObjectOutput, AWSError> {
		let mut request = PutObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		request.body = Some(object_as_bytes.clone()); // this needs to be refactored to pass a reference
		let result = self.client.put_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_object(&self, bucket_name: &str, object_name: &str) ->  Result<DeleteObjectOutput, AWSError> {
		let mut request = DeleteObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.delete_object(&request);
		println!("Result is {:?}", result);
		result
	}
}

#[cfg(test)]
mod tests {
	use xml::reader::*;
	use std::io::BufReader;
	use std::fs::File;
	use super::ListBucketsOutputParser;
	use xmlutil::*;

	#[test]
	fn list_buckets_happy_path() {
		let file = File::open("tests/sample-data/s3_get_buckets.xml").unwrap();
	    let file = BufReader::new(file);
	    let mut my_parser  = EventReader::new(file);
	    let my_stack = my_parser.events().peekable();
	    let mut reader = XmlResponseFromFile::new(my_stack);
		reader.next(); // xml start node
		let result = ListBucketsOutputParser::parse_xml("ListAllMyBucketsResult", &mut reader);

		match result {
			Err(_) => panic!("Couldn't parse list_buckets"),
			Ok(_) => return,
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>start rust version<commit_after>#[derive(Debug)]
struct Tree {
    enter: Node,
    left: Option<Box<Tree>>,
    right: Option<Box<Tree>>,
}

//for red-black tree
#[derive(Debug)]
enum Color {
    Black,
    Red,
    White,
}

#[derive(Debug)]
struct Node {
    val: i32,
    color: Color,
}

impl Node {
    fn new(v: &i32) -> Node {
        Node {
            val: *v,
            color: Color::White,
        }
    }
}

impl Tree {
    fn new(v: &i32) -> Tree {
        Tree {
            enter: Node::new(v),
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, v: &i32) {
        let target = if *v > self.enter.val {
            &mut self.right
        } else {
            &mut self.left
        };

        match target {
            Some(next) => next.insert(v),
            None => {
                let new_node = Node::new(v);
                let new_tree = Tree {
                    enter: new_node,
                    left: None,
                    right: None,
                };
                *target = Some(Box::new(new_tree));
            }
        }
    }
}

fn main() {}
<|endoftext|>


<commit_before>use diesel::*;
use schema::*;

#[test]
fn association_where_struct_name_doesnt_match_table_name() {
    #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
    #[belongs_to(Post)]
    #[table_name="comments"]
    struct OtherComment {
        id: i32,
        post_id: i32
    }

    let connection = connection_with_sean_and_tess_in_users_table();

    let sean = find_user_by_name("Sean", &connection);
    let post: Post = insert(&sean.new_post("Hello", None)).into(posts::table)
        .get_result(&connection).unwrap();
    insert(&NewComment(post.id, "comment")).into(comments::table)
        .execute(&connection).unwrap();

    let comment_text = OtherComment::belonging_to(&post).select(comments::text)
        .first::<String>(&connection);
    assert_eq!(Ok("comment".into()), comment_text);
}

#[test]
fn association_where_parent_and_child_have_underscores() {
    #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
    #[has_many(special_comments)]
    #[belongs_to(User)]
    struct SpecialPost {
        id: i32,
        user_id: i32,
        title: String
    }

    #[insertable_into(special_posts)]
    struct NewSpecialPost {
        user_id: i32,
        title: String
    }

    impl SpecialPost {
        fn new(user_id: i32, title: &str) -> NewSpecialPost {
            NewSpecialPost {
                user_id: user_id,
                title: title.to_owned()
            }
        }
    }

    #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
    #[belongs_to(SpecialPost)]
    struct SpecialComment {
        id: i32,
        special_post_id: i32,
    }

    impl SpecialComment {
        fn new(special_post_id: i32) -> NewSpecialComment {
            NewSpecialComment {
                special_post_id: special_post_id
            }
        }
    }

    #[insertable_into(special_comments)]
    struct NewSpecialComment {
        special_post_id: i32
    }

    let connection = connection_with_sean_and_tess_in_users_table();

    let sean = find_user_by_name("Sean", &connection);
    let new_post = SpecialPost::new(sean.id, "title");
    let special_post: SpecialPost = insert(&new_post).into(special_posts::table)
        .get_result(&connection).unwrap();
    let new_comment = SpecialComment::new(special_post.id);
    insert(&new_comment).into(special_comments::table)
        .execute(&connection).unwrap();

    let comment: SpecialComment = SpecialComment::belonging_to(&special_post)
        .first(&connection).unwrap();

    assert_eq!(special_post.id, comment.special_post_id);
}

// This module has no test functions, as it's only to test compilation.
mod associations_can_have_nullable_foreign_keys {
    #![allow(dead_code)]
    use diesel::prelude::*;

    table! {
        foos{
            id -> Integer,
        }
    }

    table! {
        bars {
            id -> Integer,
            foo_id -> Nullable<Integer>,
        }
    }
    // This test has no assertions, as it is for compilation purposes only.
    #[has_many(bars)]
    #[derive(Identifiable)]
    pub struct Foo {
        id: i32,
    }

    #[belongs_to(Foo)]
    #[derive(Identifiable)]
    pub struct Bar {
        id: i32,
        foo_id: Option<i32>,
    }
}

// This module has no test functions, as it's only to test compilation.
mod multiple_lifetimes_in_insertable_struct_definition {
    #![allow(dead_code)]
    use schema::posts;

    #[insertable_into(posts)]
    pub struct MyPost<'a> {
        title: &'a str,
        body: &'a str,
    }
}

mod lifetimes_with_names_other_than_a {
    #![allow(dead_code)]
    use schema::posts;

    #[insertable_into(posts)]
    pub struct MyPost<'a, 'b> {
        id: i32,
        title: &'b str,
        body: &'a str,
    }
}
<commit_msg>Remove a failing test<commit_after>use diesel::*;
use schema::*;

// FIXME: Bring this test back once we can figure out how to allow multiple structs
// on the same table to use `#[belongs_to]` without overlapping the `SelectableExpression`
// impls
// #[test]
// fn association_where_struct_name_doesnt_match_table_name() {
//     #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
//     #[belongs_to(Post)]
//     #[table_name(comments)]
//     struct OtherComment {
//         id: i32,
//         post_id: i32
//     }

//     let connection = connection_with_sean_and_tess_in_users_table();

//     let sean = find_user_by_name("Sean", &connection);
//     let post: Post = insert(&sean.new_post("Hello", None)).into(posts::table)
//         .get_result(&connection).unwrap();
//     insert(&NewComment(post.id, "comment")).into(comments::table)
//         .execute(&connection).unwrap();

//     let comment_text = OtherComment::belonging_to(&post).select(special_comments::text)
//         .first::<String>(&connection);
//     assert_eq!(Ok("comment".into()), comment_text);
// }

#[test]
fn association_where_parent_and_child_have_underscores() {
    #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
    #[has_many(special_comments)]
    #[belongs_to(User)]
    struct SpecialPost {
        id: i32,
        user_id: i32,
        title: String
    }

    #[insertable_into(special_posts)]
    struct NewSpecialPost {
        user_id: i32,
        title: String
    }

    impl SpecialPost {
        fn new(user_id: i32, title: &str) -> NewSpecialPost {
            NewSpecialPost {
                user_id: user_id,
                title: title.to_owned()
            }
        }
    }

    #[derive(PartialEq, Eq, Debug, Clone, Queryable, Identifiable)]
    #[belongs_to(SpecialPost)]
    struct SpecialComment {
        id: i32,
        special_post_id: i32,
    }

    impl SpecialComment {
        fn new(special_post_id: i32) -> NewSpecialComment {
            NewSpecialComment {
                special_post_id: special_post_id
            }
        }
    }

    #[insertable_into(special_comments)]
    struct NewSpecialComment {
        special_post_id: i32
    }

    let connection = connection_with_sean_and_tess_in_users_table();

    let sean = find_user_by_name("Sean", &connection);
    let new_post = SpecialPost::new(sean.id, "title");
    let special_post: SpecialPost = insert(&new_post).into(special_posts::table)
        .get_result(&connection).unwrap();
    let new_comment = SpecialComment::new(special_post.id);
    insert(&new_comment).into(special_comments::table)
        .execute(&connection).unwrap();

    let comment: SpecialComment = SpecialComment::belonging_to(&special_post)
        .first(&connection).unwrap();

    assert_eq!(special_post.id, comment.special_post_id);
}

// This module has no test functions, as it's only to test compilation.
mod associations_can_have_nullable_foreign_keys {
    #![allow(dead_code)]
    use diesel::prelude::*;

    table! {
        foos{
            id -> Integer,
        }
    }

    table! {
        bars {
            id -> Integer,
            foo_id -> Nullable<Integer>,
        }
    }
    // This test has no assertions, as it is for compilation purposes only.
    #[has_many(bars)]
    #[derive(Identifiable)]
    pub struct Foo {
        id: i32,
    }

    #[belongs_to(Foo)]
    #[derive(Identifiable)]
    pub struct Bar {
        id: i32,
        foo_id: Option<i32>,
    }
}

// This module has no test functions, as it's only to test compilation.
mod multiple_lifetimes_in_insertable_struct_definition {
    #![allow(dead_code)]
    use schema::posts;

    #[insertable_into(posts)]
    pub struct MyPost<'a> {
        title: &'a str,
        body: &'a str,
    }
}

mod lifetimes_with_names_other_than_a {
    #![allow(dead_code)]
    use schema::posts;

    #[insertable_into(posts)]
    pub struct MyPost<'a, 'b> {
        id: i32,
        title: &'b str,
        body: &'a str,
    }
}
<|endoftext|>


<commit_before>//! HTTP Server
use std::io::{Listener, EndOfFile, BufferedReader, BufferedWriter};
use std::io::net::ip::{IpAddr, Port, SocketAddr};
use std::os;
use std::sync::{Arc, TaskPool};
use std::thread::{Builder, JoinGuard};

pub use self::request::Request;
pub use self::response::Response;

pub use net::{Fresh, Streaming};

use HttpError::HttpIoError;
use {HttpResult};
use header::Connection;
use header::ConnectionOption::{Close, KeepAlive};
use net::{NetworkListener, NetworkStream, NetworkAcceptor,
          HttpAcceptor, HttpListener};
use version::HttpVersion::{Http10, Http11};

pub mod request;
pub mod response;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server<L = HttpListener> {
    ip: IpAddr,
    port: Port,
    listener: L,
}

macro_rules! try_option(
    ($e:expr) => {{
        match $e {
            Some(v) => v,
            None => return None
        }
    }}
);

impl Server<HttpListener> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn http(ip: IpAddr, port: Port) -> Server {
        Server::with_listener(ip, port, HttpListener::Http)
    }
    /// Creates a new server that will handler `HttpStreams`s using a TLS connection.
    pub fn https(ip: IpAddr, port: Port, cert: Path, key: Path) -> Server {
        Server::with_listener(ip, port, HttpListener::Https(cert, key))
    }
}

impl<
L: NetworkListener<Acceptor=A> + Send,
A: NetworkAcceptor<Stream=S> + Send,
S: NetworkStream + Clone + Send> Server<L> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn with_listener(ip: IpAddr, port: Port, listener: L) -> Server<L> {
        Server {
            ip: ip,
            port: port,
            listener: listener,
        }
    }

    /// Binds to a socket, and starts handling connections using a task pool.
    pub fn listen_threads<H: Handler>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> {
        debug!("binding to {:?}:{:?}", self.ip, self.port);
        let acceptor = try!(self.listener.listen((self.ip, self.port)));
        let socket = try!(acceptor.socket_name());

        let mut captured = acceptor.clone();
        let guard = Builder::new().name("hyper acceptor".to_string()).scoped(move || {
            let handler = Arc::new(handler);
            debug!("threads = {:?}", threads);
            let pool = TaskPool::new(threads);
            for conn in captured.incoming() {
                match conn {
                    Ok(mut stream) => {
                        debug!("Incoming stream");
                        let handler = handler.clone();
                        pool.execute(move || {
                            let addr = match stream.peer_name() {
                                Ok(addr) => addr,
                                Err(e) => {
                                    error!("Peer Name error: {:?}", e);
                                    return;
                                }
                            };
                            let mut rdr = BufferedReader::new(stream.clone());
                            let mut wrt = BufferedWriter::new(stream);

                            let mut keep_alive = true;
                            while keep_alive {
                                let mut res = Response::new(&mut wrt);
                                let req = match Request::new(&mut rdr, addr) {
                                    Ok(req) => req,
                                    Err(e@HttpIoError(_)) => {
                                        debug!("ioerror in keepalive loop = {:?}", e);
                                        return;
                                    }
                                    Err(e) => {
                                        //TODO: send a 400 response
                                        error!("request error = {:?}", e);
                                        return;
                                    }
                                };

                                keep_alive = match (req.version, req.headers.get::<Connection>()) {
                                    (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
                                    (Http11, Some(conn)) if conn.contains(&Close)  => false,
                                    _ => true
                                };
                                res.version = req.version;
                                handler.handle(req, res);
                                debug!("keep_alive = {:?}", keep_alive);
                            }

                        });
                    },
                    Err(ref e) if e.kind == EndOfFile => {
                        debug!("server closed");
                        break;
                    },
                    Err(e) => {
                        error!("Connection failed: {}", e);
                        continue;
                    }
                }
            }
        });

        Ok(Listening {
            acceptor: acceptor,
            guard: Some(guard),
            socket: socket,
        })
    }

    /// Binds to a socket and starts handling connections.
    pub fn listen<H: Handler>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> {
        self.listen_threads(handler, os::num_cpus() * 5 / 4)
    }

}

/// A listening server, which can later be closed.
pub struct Listening<A = HttpAcceptor> {
    acceptor: A,
    guard: Option<JoinGuard<'static, ()>>,
    /// The socket addresses that the server is bound to.
    pub socket: SocketAddr,
}

impl<A: NetworkAcceptor> Listening<A> {
    /// Causes the current thread to wait for this listening to complete.
    pub fn await(&mut self) {
        if let Some(guard) = self.guard.take() {
            let _ = guard.join();
        }
    }

    /// Stop the server from listening to its socket address.
    pub fn close(&mut self) -> HttpResult<()> {
        debug!("closing server");
        try!(self.acceptor.close());
        Ok(())
    }
}

/// A handler that can handle incoming requests for a server.
pub trait Handler: Sync + Send {
    /// Receives a `Request`/`Response` pair, and should perform some action on them.
    ///
    /// This could reading from the request, and writing to the response.
    fn handle(&self, Request, Response<Fresh>);
}

impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send {
    fn handle(&self, req: Request, res: Response<Fresh>) {
        (*self)(req, res)
    }
}
<commit_msg>refactor(server): Add explicit lifetime annotations for Handler trait<commit_after>//! HTTP Server
use std::io::{Listener, EndOfFile, BufferedReader, BufferedWriter};
use std::io::net::ip::{IpAddr, Port, SocketAddr};
use std::os;
use std::sync::{Arc, TaskPool};
use std::thread::{Builder, JoinGuard};

pub use self::request::Request;
pub use self::response::Response;

pub use net::{Fresh, Streaming};

use HttpError::HttpIoError;
use {HttpResult};
use header::Connection;
use header::ConnectionOption::{Close, KeepAlive};
use net::{NetworkListener, NetworkStream, NetworkAcceptor,
          HttpAcceptor, HttpListener};
use version::HttpVersion::{Http10, Http11};

pub mod request;
pub mod response;

/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server<L = HttpListener> {
    ip: IpAddr,
    port: Port,
    listener: L,
}

macro_rules! try_option(
    ($e:expr) => {{
        match $e {
            Some(v) => v,
            None => return None
        }
    }}
);

impl Server<HttpListener> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn http(ip: IpAddr, port: Port) -> Server {
        Server::with_listener(ip, port, HttpListener::Http)
    }
    /// Creates a new server that will handler `HttpStreams`s using a TLS connection.
    pub fn https(ip: IpAddr, port: Port, cert: Path, key: Path) -> Server {
        Server::with_listener(ip, port, HttpListener::Https(cert, key))
    }
}

impl<
L: NetworkListener<Acceptor=A> + Send,
A: NetworkAcceptor<Stream=S> + Send,
S: NetworkStream + Clone + Send> Server<L> {
    /// Creates a new server that will handle `HttpStream`s.
    pub fn with_listener(ip: IpAddr, port: Port, listener: L) -> Server<L> {
        Server {
            ip: ip,
            port: port,
            listener: listener,
        }
    }

    /// Binds to a socket, and starts handling connections using a task pool.
    pub fn listen_threads<H: Handler>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> {
        debug!("binding to {:?}:{:?}", self.ip, self.port);
        let acceptor = try!(self.listener.listen((self.ip, self.port)));
        let socket = try!(acceptor.socket_name());

        let mut captured = acceptor.clone();
        let guard = Builder::new().name("hyper acceptor".to_string()).scoped(move || {
            let handler = Arc::new(handler);
            debug!("threads = {:?}", threads);
            let pool = TaskPool::new(threads);
            for conn in captured.incoming() {
                match conn {
                    Ok(mut stream) => {
                        debug!("Incoming stream");
                        let handler = handler.clone();
                        pool.execute(move || {
                            let addr = match stream.peer_name() {
                                Ok(addr) => addr,
                                Err(e) => {
                                    error!("Peer Name error: {:?}", e);
                                    return;
                                }
                            };
                            let mut rdr = BufferedReader::new(stream.clone());
                            let mut wrt = BufferedWriter::new(stream);

                            let mut keep_alive = true;
                            while keep_alive {
                                let mut res = Response::new(&mut wrt);
                                let req = match Request::new(&mut rdr, addr) {
                                    Ok(req) => req,
                                    Err(e@HttpIoError(_)) => {
                                        debug!("ioerror in keepalive loop = {:?}", e);
                                        return;
                                    }
                                    Err(e) => {
                                        //TODO: send a 400 response
                                        error!("request error = {:?}", e);
                                        return;
                                    }
                                };

                                keep_alive = match (req.version, req.headers.get::<Connection>()) {
                                    (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
                                    (Http11, Some(conn)) if conn.contains(&Close)  => false,
                                    _ => true
                                };
                                res.version = req.version;
                                handler.handle(req, res);
                                debug!("keep_alive = {:?}", keep_alive);
                            }

                        });
                    },
                    Err(ref e) if e.kind == EndOfFile => {
                        debug!("server closed");
                        break;
                    },
                    Err(e) => {
                        error!("Connection failed: {}", e);
                        continue;
                    }
                }
            }
        });

        Ok(Listening {
            acceptor: acceptor,
            guard: Some(guard),
            socket: socket,
        })
    }

    /// Binds to a socket and starts handling connections.
    pub fn listen<H: Handler>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> {
        self.listen_threads(handler, os::num_cpus() * 5 / 4)
    }

}

/// A listening server, which can later be closed.
pub struct Listening<A = HttpAcceptor> {
    acceptor: A,
    guard: Option<JoinGuard<'static, ()>>,
    /// The socket addresses that the server is bound to.
    pub socket: SocketAddr,
}

impl<A: NetworkAcceptor> Listening<A> {
    /// Causes the current thread to wait for this listening to complete.
    pub fn await(&mut self) {
        if let Some(guard) = self.guard.take() {
            let _ = guard.join();
        }
    }

    /// Stop the server from listening to its socket address.
    pub fn close(&mut self) -> HttpResult<()> {
        debug!("closing server");
        try!(self.acceptor.close());
        Ok(())
    }
}

/// A handler that can handle incoming requests for a server.
pub trait Handler: Sync + Send {
    /// Receives a `Request`/`Response` pair, and should perform some action on them.
    ///
    /// This could reading from the request, and writing to the response.
    fn handle<'a>(&'a self, Request<'a>, Response<'a, Fresh>);
}

impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send {
    fn handle(&self, req: Request, res: Response<Fresh>) {
        (*self)(req, res)
    }
}
<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before>use std::any::Any;

/// The result yielded to the `Future::schedule` callback which indicates the
/// final result of a future.
///
/// Like `io::Result`, this is just a typedef around `Result<T, PollError<E>>`
/// and simply avoids writing lots all over the place.
pub type PollResult<T, E> = Result<T, PollError<E>>;

/// Possible errors that a future can be resolved with
pub enum PollError<E> {
    /// Generic payload indicating that a future has resolved with a custom
    /// error (e.g. an I/O error). This is the standard error that will likely
    /// come up the most.
    Other(E),

    /// Indicates that this future somewhere along the way panicked and the
    /// payload was captured in a `Box<Any+Send>` here.
    Panicked(Box<Any + Send>),
}

impl<E> PollError<E> {
    /// Maps data contained in this error with the provided closure.
    ///
    /// Note that the closure is not guaranteed to be called as not all variants
    /// of a `PollError` have data to call it with.
    pub fn map<F: FnOnce(E) -> E2, E2>(self, f: F) -> PollError<E2> {
        match self {
            PollError::Panicked(e) => PollError::Panicked(e),
            PollError::Other(e) => PollError::Other(f(e)),
        }
    }
}
<commit_msg>Add a PollError::unwrap method<commit_after>use std::any::Any;
use std::panic;

/// The result yielded to the `Future::schedule` callback which indicates the
/// final result of a future.
///
/// Like `io::Result`, this is just a typedef around `Result<T, PollError<E>>`
/// and simply avoids writing lots all over the place.
pub type PollResult<T, E> = Result<T, PollError<E>>;

/// Possible errors that a future can be resolved with
pub enum PollError<E> {
    /// Generic payload indicating that a future has resolved with a custom
    /// error (e.g. an I/O error). This is the standard error that will likely
    /// come up the most.
    Other(E),

    /// Indicates that this future somewhere along the way panicked and the
    /// payload was captured in a `Box<Any+Send>` here.
    Panicked(Box<Any + Send>),
}

impl<E> PollError<E> {
    /// Maps data contained in this error with the provided closure.
    ///
    /// Note that the closure is not guaranteed to be called as not all variants
    /// of a `PollError` have data to call it with.
    pub fn map<F: FnOnce(E) -> E2, E2>(self, f: F) -> PollError<E2> {
        match self {
            PollError::Panicked(e) => PollError::Panicked(e),
            PollError::Other(e) => PollError::Other(f(e)),
        }
    }

    /// Unwraps the `E` from this `PollError<E>`, propagating a panic if it
    /// represents a panicked result.
    ///
    /// Note that the closure is not guaranteed to be called as not all variants
    /// of a `PollError` have data to call it with.
    pub fn unwrap(self) -> E {
        match self {
            PollError::Other(e) => e,
            PollError::Panicked(e) => panic::resume_unwind(e),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>When a message from an unknown channel is received, attempt to get info about it<commit_after><|endoftext|>


<commit_before><commit_msg>Added test for attributes on parens hir folder<commit_after>// 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.

#![feature(stmt_expr_attributes)]

fn main() {

    // Test that attributes on parens get concatenated
    // in the expected order in the hir folder.

    #[deny(non_snake_case)] (
        #![allow(non_snake_case)]
        {
            let X = 0;
            let _ = X;
        }
    );

    #[allow(non_snake_case)] (
        #![deny(non_snake_case)]
        {
            let X = 0; //~ ERROR snake case name
            let _ = X;
        }
    );

}
<|endoftext|>


<commit_before><commit_msg>Forgot to add CPU feature detection code last revision.<commit_after>pub enum Feature {
    Baseline,
    MMX,
    SSE,
    SSE2,
    SSE3,
    SSSE3,
    SSE41,
    SSE42,
    OSXSAVE,
    AVX,
    AVX2
}

static EBX: uint = 1;
static ECX: uint = 2;
static EDX: uint = 3;
macro_rules! feature(
    ($p_eax:expr : $p_ecx:expr, $reg:expr, $bit:expr) => (
        {
            let mut regs = [0u32, ..4];
            unsafe { do_cpuid($p_eax, $p_ecx, regs.as_mut_ptr()); }

            regs[$reg] & (1 << $bit) != 0
        }
    );

    ($reg:expr $bit:expr) => (
        feature!(1:0, $reg, $bit)
    )
)

pub fn cpu_supports(feature: Feature) -> bool {
    match feature {
        Baseline => true,
        MMX => feature!(EDX 23),
        SSE => feature!(EDX 25),
        SSE2 => feature!(EDX 26),
        SSE3 => feature!(ECX 0),
        SSSE3 => feature!(ECX 9),
        SSE41 => feature!(ECX 19),
        SSE42 => feature!(ECX 20),
        OSXSAVE => feature!(ECX 27),
        AVX => {
            // Requires that OS support for XSAVE be in use and enabled for AVX
            cpu_supports(OSXSAVE)
            && (unsafe { do_xgetbv(0) & 6 } == 6)
            && feature!(ECX 28)
        }
        AVX2 => {
            // Need OS support for AVX and AVX2 feature flag
            cpu_supports(AVX) && feature!(7:0, EBX, 5)
        }
    }
}

// Inline assembly appears to handle this poorly. Easier just to let a C compiler do it.
#[link(name = "cpuid", kind = "static")]
extern "C" {
    fn do_cpuid(eax: u32, ecx: u32, outputs: *mut u32);
    fn do_xgetbv(ecx: u32) -> u64;
}

<|endoftext|>


<commit_before>//! A simple parser for a tiny subset of CSS.
//!
//! To support more CSS syntax, it would probably be easiest to replace this
//! hand-rolled parser with one based on a library or parser generator.

use std::ascii::OwnedAsciiExt; // for `into_ascii_lower`
use std::str::FromStr;
use std::num::FromStrRadix;

// Data structures:

#[deriving(Show)]
pub struct Stylesheet {
    pub rules: Vec<Rule>,
}

#[deriving(Show)]
pub struct Rule {
    pub selectors: Vec<Selector>,
    pub declarations: Vec<Declaration>,
}

#[deriving(Show)]
pub enum Selector {
    Simple(SimpleSelector),
}

#[deriving(Show)]
pub struct SimpleSelector {
    pub tag_name: Option<String>,
    pub id: Option<String>,
    pub class: Vec<String>,
}

#[deriving(Show)]
pub struct Declaration {
    pub name: String,
    pub value: Value,
}

#[deriving(Show, Clone, PartialEq)]
pub enum Value {
    Keyword(String),
    Length(f32, Unit),
    ColorValue(Color),
}

#[deriving(Show, Clone, PartialEq)]
pub enum Unit {
    Px,
}

#[deriving(Show, Clone, PartialEq, Default)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Copy for Color {}

pub type Specificity = (uint, uint, uint);

impl Selector {
    pub fn specificity(&self) -> Specificity {
        // http://www.w3.org/TR/selectors/#specificity
        let Selector::Simple(ref simple) = *self;
        let a = simple.id.iter().len();
        let b = simple.class.len();
        let c = simple.tag_name.iter().len();
        (a, b, c)
    }
}

impl Value {
    /// Return the size of a length in px, or zero for non-lengths.
    pub fn to_px(&self) -> f32 {
        match *self {
            Value::Length(f, Unit::Px) => f,
            _ => 0.0
        }
    }
}

/// Parse a whole CSS stylesheet.
pub fn parse(source: String) -> Stylesheet {
    let mut parser = Parser { pos: 0u, input: source };
    Stylesheet { rules: parser.parse_rules() }
}

struct Parser {
    pos: uint,
    input: String,
}

impl Parser {
    /// Parse a list of rule sets, separated by optional whitespace.
    fn parse_rules(&mut self) -> Vec<Rule> {
        let mut rules = Vec::new();
        loop {
            self.consume_whitespace();
            if self.eof() { break }
            rules.push(self.parse_rule());
        }
        return rules;
    }

    /// Parse a rule set: `<selectors> { <declarations> }`.
    fn parse_rule(&mut self) -> Rule {
        Rule {
            selectors: self.parse_selectors(),
            declarations: self.parse_declarations(),
        }
    }

    /// Parse a comma-separated list of selectors.
    fn parse_selectors(&mut self) -> Vec<Selector> {
        let mut selectors = Vec::new();
        loop {
            selectors.push(Selector::Simple(self.parse_simple_selector()));
            self.consume_whitespace();
            match self.next_char() {
                ',' => { self.consume_char(); self.consume_whitespace(); }
                '{' => break,
                c   => panic!("Unexpected character {} in selector list", c)
            }
        }
        // Return selectors with highest specificity first, for use in matching.
        selectors.sort_by(|a,b| b.specificity().cmp(&a.specificity()));
        return selectors;
    }

    /// Parse one simple selector, e.g.: `type#id.class1.class2.class3`
    fn parse_simple_selector(&mut self) -> SimpleSelector {
        let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
        while !self.eof() {
            match self.next_char() {
                '#' => {
                    self.consume_char();
                    selector.id = Some(self.parse_identifier());
                }
                '.' => {
                    self.consume_char();
                    selector.class.push(self.parse_identifier());
                }
                '*' => {
                    // universal selector
                    self.consume_char();
                }
                c if valid_identifier_char(c) => {
                    selector.tag_name = Some(self.parse_identifier());
                }
                _ => break
            }
        }
        return selector;
    }

    /// Parse a list of declarations enclosed in `{ ... }`.
    fn parse_declarations(&mut self) -> Vec<Declaration> {
        assert!(self.consume_char() == '{');
        let mut declarations = Vec::new();
        loop {
            self.consume_whitespace();
            if self.next_char() == '}' {
                self.consume_char();
                break;
            }
            declarations.push(self.parse_declaration());
        }
        return declarations;
    }

    /// Parse one `<property>: <value>;` declaration.
    fn parse_declaration(&mut self) -> Declaration {
        let property_name = self.parse_identifier();
        self.consume_whitespace();
        assert!(self.consume_char() == ':');
        self.consume_whitespace();
        let value = self.parse_value();
        self.consume_whitespace();
        assert!(self.consume_char() == ';');

        Declaration {
            name: property_name,
            value: value,
        }
    }

    // Methods for parsing values:

    fn parse_value(&mut self) -> Value {
        match self.next_char() {
            '0'...'9' => self.parse_length(),
            '#' => self.parse_color(),
            _ => Value::Keyword(self.parse_identifier())
        }
    }

    fn parse_length(&mut self) -> Value {
        Value::Length(self.parse_float(), self.parse_unit())
    }

    fn parse_float(&mut self) -> f32 {
        let s = self.consume_while(|c| match c {
            '0'...'9' | '.' => true,
            _ => false
        });
        let f: Option<f32> = FromStr::from_str(s.as_slice());
        f.unwrap()
    }

    fn parse_unit(&mut self) -> Unit {
        match self.parse_identifier().into_ascii_lower().as_slice() {
            "px" => Unit::Px,
            _ => panic!("unrecognized unit")
        }
    }

    fn parse_color(&mut self) -> Value {
        assert!(self.consume_char() == '#');
        Value::ColorValue(Color {
            r: self.parse_hex_pair(),
            g: self.parse_hex_pair(),
            b: self.parse_hex_pair(),
            a: 255 })
    }

    /// Parse two hexadecimal digits.
    fn parse_hex_pair(&mut self) -> u8 {
        let s = self.input.as_slice().slice(self.pos, self.pos + 2);
        self.pos = self.pos + 2;
        FromStrRadix::from_str_radix(s, 0x10).unwrap()
    }

    /// Parse a property name or keyword.
    fn parse_identifier(&mut self) -> String {
        self.consume_while(valid_identifier_char)
    }

    /// Consume and discard zero or more whitespace characters.
    fn consume_whitespace(&mut self) {
        self.consume_while(|c| c.is_whitespace());
    }

    /// Consume characters until `test` returns false.
    fn consume_while(&mut self, test: |char| -> bool) -> String {
        let mut result = String::new();
        while !self.eof() && test(self.next_char()) {
            result.push(self.consume_char());
        }
        return result;
    }

    /// Return the current character, and advance self.pos to the next character.
    fn consume_char(&mut self) -> char {
        let range = self.input.as_slice().char_range_at(self.pos);
        self.pos = range.next;
        return range.ch;
    }

    /// Read the current character without consuming it.
    fn next_char(&self) -> char {
        self.input.as_slice().char_at(self.pos)
    }

    /// Return true if all input is consumed.
    fn eof(&self) -> bool {
        self.pos >= self.input.len()
    }
}

fn valid_identifier_char(c: char) -> bool {
    match c {
        'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' => true, // TODO: Include U+00A0 and higher.
        _ => false,
    }
}
<commit_msg>Update to new into_ascii_lowercase<commit_after>//! A simple parser for a tiny subset of CSS.
//!
//! To support more CSS syntax, it would probably be easiest to replace this
//! hand-rolled parser with one based on a library or parser generator.

use std::ascii::OwnedAsciiExt; // for `into_ascii_lowercase`
use std::str::FromStr;
use std::num::FromStrRadix;

// Data structures:

#[deriving(Show)]
pub struct Stylesheet {
    pub rules: Vec<Rule>,
}

#[deriving(Show)]
pub struct Rule {
    pub selectors: Vec<Selector>,
    pub declarations: Vec<Declaration>,
}

#[deriving(Show)]
pub enum Selector {
    Simple(SimpleSelector),
}

#[deriving(Show)]
pub struct SimpleSelector {
    pub tag_name: Option<String>,
    pub id: Option<String>,
    pub class: Vec<String>,
}

#[deriving(Show)]
pub struct Declaration {
    pub name: String,
    pub value: Value,
}

#[deriving(Show, Clone, PartialEq)]
pub enum Value {
    Keyword(String),
    Length(f32, Unit),
    ColorValue(Color),
}

#[deriving(Show, Clone, PartialEq)]
pub enum Unit {
    Px,
}

#[deriving(Show, Clone, PartialEq, Default)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Copy for Color {}

pub type Specificity = (uint, uint, uint);

impl Selector {
    pub fn specificity(&self) -> Specificity {
        // http://www.w3.org/TR/selectors/#specificity
        let Selector::Simple(ref simple) = *self;
        let a = simple.id.iter().len();
        let b = simple.class.len();
        let c = simple.tag_name.iter().len();
        (a, b, c)
    }
}

impl Value {
    /// Return the size of a length in px, or zero for non-lengths.
    pub fn to_px(&self) -> f32 {
        match *self {
            Value::Length(f, Unit::Px) => f,
            _ => 0.0
        }
    }
}

/// Parse a whole CSS stylesheet.
pub fn parse(source: String) -> Stylesheet {
    let mut parser = Parser { pos: 0u, input: source };
    Stylesheet { rules: parser.parse_rules() }
}

struct Parser {
    pos: uint,
    input: String,
}

impl Parser {
    /// Parse a list of rule sets, separated by optional whitespace.
    fn parse_rules(&mut self) -> Vec<Rule> {
        let mut rules = Vec::new();
        loop {
            self.consume_whitespace();
            if self.eof() { break }
            rules.push(self.parse_rule());
        }
        return rules;
    }

    /// Parse a rule set: `<selectors> { <declarations> }`.
    fn parse_rule(&mut self) -> Rule {
        Rule {
            selectors: self.parse_selectors(),
            declarations: self.parse_declarations(),
        }
    }

    /// Parse a comma-separated list of selectors.
    fn parse_selectors(&mut self) -> Vec<Selector> {
        let mut selectors = Vec::new();
        loop {
            selectors.push(Selector::Simple(self.parse_simple_selector()));
            self.consume_whitespace();
            match self.next_char() {
                ',' => { self.consume_char(); self.consume_whitespace(); }
                '{' => break,
                c   => panic!("Unexpected character {} in selector list", c)
            }
        }
        // Return selectors with highest specificity first, for use in matching.
        selectors.sort_by(|a,b| b.specificity().cmp(&a.specificity()));
        return selectors;
    }

    /// Parse one simple selector, e.g.: `type#id.class1.class2.class3`
    fn parse_simple_selector(&mut self) -> SimpleSelector {
        let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
        while !self.eof() {
            match self.next_char() {
                '#' => {
                    self.consume_char();
                    selector.id = Some(self.parse_identifier());
                }
                '.' => {
                    self.consume_char();
                    selector.class.push(self.parse_identifier());
                }
                '*' => {
                    // universal selector
                    self.consume_char();
                }
                c if valid_identifier_char(c) => {
                    selector.tag_name = Some(self.parse_identifier());
                }
                _ => break
            }
        }
        return selector;
    }

    /// Parse a list of declarations enclosed in `{ ... }`.
    fn parse_declarations(&mut self) -> Vec<Declaration> {
        assert!(self.consume_char() == '{');
        let mut declarations = Vec::new();
        loop {
            self.consume_whitespace();
            if self.next_char() == '}' {
                self.consume_char();
                break;
            }
            declarations.push(self.parse_declaration());
        }
        return declarations;
    }

    /// Parse one `<property>: <value>;` declaration.
    fn parse_declaration(&mut self) -> Declaration {
        let property_name = self.parse_identifier();
        self.consume_whitespace();
        assert!(self.consume_char() == ':');
        self.consume_whitespace();
        let value = self.parse_value();
        self.consume_whitespace();
        assert!(self.consume_char() == ';');

        Declaration {
            name: property_name,
            value: value,
        }
    }

    // Methods for parsing values:

    fn parse_value(&mut self) -> Value {
        match self.next_char() {
            '0'...'9' => self.parse_length(),
            '#' => self.parse_color(),
            _ => Value::Keyword(self.parse_identifier())
        }
    }

    fn parse_length(&mut self) -> Value {
        Value::Length(self.parse_float(), self.parse_unit())
    }

    fn parse_float(&mut self) -> f32 {
        let s = self.consume_while(|c| match c {
            '0'...'9' | '.' => true,
            _ => false
        });
        let f: Option<f32> = FromStr::from_str(s.as_slice());
        f.unwrap()
    }

    fn parse_unit(&mut self) -> Unit {
        match self.parse_identifier().into_ascii_lowercase().as_slice() {
            "px" => Unit::Px,
            _ => panic!("unrecognized unit")
        }
    }

    fn parse_color(&mut self) -> Value {
        assert!(self.consume_char() == '#');
        Value::ColorValue(Color {
            r: self.parse_hex_pair(),
            g: self.parse_hex_pair(),
            b: self.parse_hex_pair(),
            a: 255 })
    }

    /// Parse two hexadecimal digits.
    fn parse_hex_pair(&mut self) -> u8 {
        let s = self.input.as_slice().slice(self.pos, self.pos + 2);
        self.pos = self.pos + 2;
        FromStrRadix::from_str_radix(s, 0x10).unwrap()
    }

    /// Parse a property name or keyword.
    fn parse_identifier(&mut self) -> String {
        self.consume_while(valid_identifier_char)
    }

    /// Consume and discard zero or more whitespace characters.
    fn consume_whitespace(&mut self) {
        self.consume_while(|c| c.is_whitespace());
    }

    /// Consume characters until `test` returns false.
    fn consume_while(&mut self, test: |char| -> bool) -> String {
        let mut result = String::new();
        while !self.eof() && test(self.next_char()) {
            result.push(self.consume_char());
        }
        return result;
    }

    /// Return the current character, and advance self.pos to the next character.
    fn consume_char(&mut self) -> char {
        let range = self.input.as_slice().char_range_at(self.pos);
        self.pos = range.next;
        return range.ch;
    }

    /// Read the current character without consuming it.
    fn next_char(&self) -> char {
        self.input.as_slice().char_at(self.pos)
    }

    /// Return true if all input is consumed.
    fn eof(&self) -> bool {
        self.pos >= self.input.len()
    }
}

fn valid_identifier_char(c: char) -> bool {
    match c {
        'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' => true, // TODO: Include U+00A0 and higher.
        _ => false,
    }
}
<|endoftext|>


<commit_before>#![allow(unstable)]

extern crate ansi_term;
extern crate number_prefix;
extern crate unicode;
extern crate users;

use std::io::FileType;
use std::io::fs;
use std::os::{args, set_exit_status};

use dir::Dir;
use file::File;
use options::Options;
use options::Error::*;

pub mod column;
pub mod dir;
pub mod file;
pub mod filetype;
pub mod options;
pub mod output;
pub mod term;

fn exa(options: &Options) {
    let mut dirs: Vec<String> = vec![];
    let mut files: Vec<File> = vec![];

    // It's only worth printing out directory names if the user supplied
    // more than one of them.
    let mut print_dir_names = false;

    // Separate the user-supplied paths into directories and files.
    // Files are shown first, and then each directory is expanded
    // and listed second.
    for file in options.path_strings() {
        let path = Path::new(file);
        match fs::stat(&path) {
            Ok(stat) => {
                if !options.list_dirs && stat.kind == FileType::Directory {
                    dirs.push(file.clone());
                }
                else {
                    // May as well reuse the stat result from earlier
                    // instead of just using File::from_path().
                    files.push(File::with_stat(stat, &path, None));
                }
            }
            Err(e) => println!("{}: {}", file, e),
        }

        print_dir_names = true;
    }

    let mut first = files.is_empty();

    if !files.is_empty() {
        options.view.view(files);
    }

    for dir_name in dirs.iter() {
        if first {
            first = false;
        }
        else {
            print!("\n");
        }

        match Dir::readdir(Path::new(dir_name.clone())) {
            Ok(dir) => {
                let unsorted_files = dir.files();
                let files: Vec<File> = options.transform_files(unsorted_files);

                if print_dir_names {
                    println!("{}:", dir_name);
                }

                options.view.view(files);
            }
            Err(e) => {
                println!("{}: {}", dir_name, e);
                return;
            }
        };
    }
}

fn main() {
    let args: Vec<String> = args();

    match Options::getopts(args.tail()) {
        Ok(options) => exa(&options),
        Err(Help(text)) => {
            println!("{}", text);
            set_exit_status(2);
        },
        Err(InvalidOptions(e)) => {
            println!("{}", e);
            set_exit_status(3);
        },
        Err(Conflict(a, b)) => {
            println!("Option --{} conflicts with option {}", a, b);
            set_exit_status(3);
        },
        Err(Useless(a, false, b)) => {
            println!("Option --{} is useless without option --{}", a, b);
            set_exit_status(3);
        },
        Err(Useless(a, true, b)) => {
            println!("Option --{} is useless given option --{}", a, b);
            set_exit_status(3);
        },
    };
}
<commit_msg>Fix header-printing logic<commit_after>#![allow(unstable)]

extern crate ansi_term;
extern crate number_prefix;
extern crate unicode;
extern crate users;

use std::io::FileType;
use std::io::fs;
use std::os::{args, set_exit_status};

use dir::Dir;
use file::File;
use options::Options;
use options::Error::*;

pub mod column;
pub mod dir;
pub mod file;
pub mod filetype;
pub mod options;
pub mod output;
pub mod term;

fn exa(options: &Options) {
    let mut dirs: Vec<String> = vec![];
    let mut files: Vec<File> = vec![];

    // It's only worth printing out directory names if the user supplied
    // more than one of them.
    let mut count = 0;

    // Separate the user-supplied paths into directories and files.
    // Files are shown first, and then each directory is expanded
    // and listed second.
    for file in options.path_strings() {
        let path = Path::new(file);
        match fs::stat(&path) {
            Ok(stat) => {
                if !options.list_dirs && stat.kind == FileType::Directory {
                    dirs.push(file.clone());
                }
                else {
                    // May as well reuse the stat result from earlier
                    // instead of just using File::from_path().
                    files.push(File::with_stat(stat, &path, None));
                }
            }
            Err(e) => println!("{}: {}", file, e),
        }

        count += 1;
    }

    let mut first = files.is_empty();

    if !files.is_empty() {
        options.view.view(files);
    }

    for dir_name in dirs.iter() {
        if first {
            first = false;
        }
        else {
            print!("\n");
        }

        match Dir::readdir(Path::new(dir_name.clone())) {
            Ok(dir) => {
                let unsorted_files = dir.files();
                let files: Vec<File> = options.transform_files(unsorted_files);

                if count > 1 {
                    println!("{}:", dir_name);
                }

                options.view.view(files);
            }
            Err(e) => {
                println!("{}: {}", dir_name, e);
                return;
            }
        };
    }
}

fn main() {
    let args: Vec<String> = args();

    match Options::getopts(args.tail()) {
        Ok(options) => exa(&options),
        Err(Help(text)) => {
            println!("{}", text);
            set_exit_status(2);
        },
        Err(InvalidOptions(e)) => {
            println!("{}", e);
            set_exit_status(3);
        },
        Err(Conflict(a, b)) => {
            println!("Option --{} conflicts with option {}", a, b);
            set_exit_status(3);
        },
        Err(Useless(a, false, b)) => {
            println!("Option --{} is useless without option --{}", a, b);
            set_exit_status(3);
        },
        Err(Useless(a, true, b)) => {
            println!("Option --{} is useless given option --{}", a, b);
            set_exit_status(3);
        },
    };
}
<|endoftext|>


<commit_before><commit_msg>Update to work with new visibility defaults.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement session expiry.<commit_after><|endoftext|>


<commit_before><commit_msg>Add UnitOps macro. May want to detect if negation should be implemented for the given type.<commit_after><|endoftext|>


<commit_before><commit_msg>Hide quirks module from docs, fix #311.<commit_after><|endoftext|>


<commit_before><commit_msg>`IXAudio2`<commit_after><|endoftext|>


<commit_before>#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/7853871?s=128", html_favicon_url = "https://avatars0.githubusercontent.com/u/7853871?s=256", html_root_url = "http://ironframework.io/core/cookie")]
#![crate_id = "cookie"]
#![deny(missing_doc)]
#![feature(phase)]

//! Cookie parsing/setting middleware for the [iron](https://github.com/iron/iron) framework.

extern crate time;
extern crate rustc;
extern crate regex;
#[phase(plugin)] extern crate regex_macros;
extern crate url;
extern crate serialize;
extern crate iron;
extern crate http;
extern crate crypto = "rust-crypto";

pub use parser::CookieParser;
pub use response::SetCookie;
pub use cookie::Cookie;
pub use response::headers::HeaderCollection;

pub mod parser;
pub mod response;
pub mod cookie;
<commit_msg>(doc) Added doc attributes.<commit_after>#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/7853871?s=128", html_favicon_url = "https://avatars0.githubusercontent.com/u/7853871?s=256", html_root_url = "http://ironframework.io/core/cookie")]
#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/7853871?s=128", html_favicon_url = "https://avatars0.githubusercontent.com/u/7853871?s=256", html_root_url = "http://ironframework.io/core/cookie")]
#![crate_id = "cookie"]
#![deny(missing_doc)]
#![feature(phase)]

//! Cookie parsing/setting middleware for the [iron](https://github.com/iron/iron) framework.

extern crate time;
extern crate rustc;
extern crate regex;
#[phase(plugin)] extern crate regex_macros;
extern crate url;
extern crate serialize;
extern crate iron;
extern crate http;
extern crate crypto = "rust-crypto";

pub use parser::CookieParser;
pub use response::SetCookie;
pub use cookie::Cookie;
pub use response::headers::HeaderCollection;

pub mod parser;
pub mod response;
pub mod cookie;
<|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::GetOutputMatrix()`<commit_after><|endoftext|>


<commit_before><commit_msg>Mod before utils.<commit_after><|endoftext|>


<commit_before>extern crate sdl2;

use sdl2::pixels::Color;
use std::thread;

pub fn ralf() {
    println!("ralf");
    let sdl_context = sdl2::init().unwrap();
    let timer = sdl_context.timer().unwrap();
    let mut event_pump = sdl_context.event_pump().unwrap();
    let video = sdl_context.video().unwrap();

    let window = video.window("Ruffel", 800, 600)
        .position_centered().opengl()
        .build().unwrap();

    let mut renderer = window.renderer()
        .accelerated()
        .build().unwrap();

    let done = false;
    while !done {
        renderer.set_draw_color(Color::RGB(0, 0, 0));
        renderer.clear();
        renderer.present();

        thread::sleep_ms(1/60);
        for event in event_pump.poll_iter() {
        }
    }
    println!("finish");
}
<commit_msg>Window events<commit_after>extern crate sdl2;

use sdl2::pixels::Color;
use sdl2::event::Event::*;
use sdl2::keyboard::Keycode::*;
use std::thread;

pub fn ralf() {
    println!("ralf");
    let sdl_context = sdl2::init().unwrap();
    let timer = sdl_context.timer().unwrap();
    let mut event_pump = sdl_context.event_pump().unwrap();
    let video = sdl_context.video().unwrap();

    let window = video.window("Ruffel", 800, 600)
        .position_centered().opengl()
        .build().unwrap();

    let mut renderer = window.renderer()
        .accelerated()
        .build().unwrap();

    let mut done = false;
    while !done {
        renderer.set_draw_color(Color::RGB(0, 0, 0));
        renderer.clear();
        renderer.present();

        thread::sleep_ms(1/60);
        for event in event_pump.poll_iter() {
            match event {
                Quit { .. } => done = true,
                KeyDown { keycode, .. } => match keycode {
                    Some(Escape) => done = true,
                    _ => {}
                },
                _ => {}
            }
        }
    }
    println!("finish");
}
<|endoftext|>


<commit_before><commit_msg>Implement using a generic wrapper and support `Arc` and `Aweak` (aka `sync::Weak`).<commit_after><|endoftext|>


<commit_before><commit_msg>Missing file.<commit_after>
// Do I really want sdl2? It can render an image to the screen but what about
// to a file?

use std::path::Path;

use sdl2;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
use sdl2::render::{Renderer, Texture};
use sdl2_image::{self, LoadTexture, LoadSurface, INIT_PNG, INIT_JPG};
use sdl2_ttf;
use sdl2_ttf::Font;

pub struct BasicWindow {
    pub sdl_context: sdl2::Sdl,
    pub video_subsystem: sdl2::VideoSubsystem,
    pub timer_subsystem: sdl2::TimerSubsystem,
    pub window: sdl2::video::Window,
    pub ttf_context: sdl2_ttf::Sdl2TtfContext,
}

pub fn init(window_title: &str, width: u32, height: u32) -> BasicWindow {

    let sdl_context: sdl2::Sdl = sdl2::init().unwrap();

    let video_subsystem: sdl2::VideoSubsystem = sdl_context.video().unwrap();

    let timer_subsystem = sdl_context.timer().unwrap();

    let mut window_builder: sdl2::video::WindowBuilder = video_subsystem.window(window_title,
                                                                                width,
                                                                                height);

    let window: sdl2::video::Window = window_builder.position_centered().opengl().build().unwrap();

    sdl2_image::init(INIT_PNG | INIT_JPG).unwrap();
    let ttf_context = sdl2_ttf::init().ok().expect("Failed to init true type fonts");

    BasicWindow {
        sdl_context: sdl_context,
        video_subsystem: video_subsystem,
        timer_subsystem: timer_subsystem,
        window: window,
        ttf_context: ttf_context,
    }
}
<|endoftext|>


<commit_before><commit_msg>Refactor some code between InputSocket/OutputSocket.<commit_after><|endoftext|>


<commit_before><commit_msg>list4<commit_after>use std::fmt;
use List::{Cons, Nil};
use std::sync::Arc;

#[derive(PartialEq, Clone)]
enum List<T> {
  Cons(T, Arc<List<T>>),
  Nil
}

impl<T> fmt::Display for List<T> where T : fmt::Display {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match *self {
      Cons(ref head, ref tail) =>
        {
          write!(f, "{head} :: ", head = head);
          write!(f, "{tail} ", tail = tail)
        }
      Nil => write!(f, "Nil")
    }
  }
}

fn flat_map<T, U>(list: &List<T>, f: &Fn(T) -> List<U>) -> List<U> where T: Copy, T: Sized, T: Copy, T: PartialEq, U: Copy, U: Sized, U: PartialEq {
  match *list {
    Cons(ref head, ref tail) => concat(&f(*head), flat_map(tail, f)),
    Nil => Nil
  }
}

fn concat<T>(list: &List<T>, b: List<T>) -> List<T> where T: Copy, T: Sized {
  fold_right(list, b, &|x, y| Cons(x, Arc::new(y)))
}

fn fold_right<T, U>(list: &List<T>, result: U, f: &Fn(T, U) -> U) -> U where T: Copy, T: Sized {
  match *list {
    Cons(ref head, ref tail) =>
      f(*head, fold_right(tail, result, f)),
    Nil => result
  }
}

fn fold_left<T, U>(list: &List<T>, result: U, f: &Fn(U, T) -> U) -> U where T: Copy, T: Sized {
  match *list {
    Cons(ref head, ref tail) => fold_left(tail, f(result, *head), f),
    Nil => result
  }
}

fn map<T, U>(list: &List<T>, f: &Fn(T) -> U) -> List<U> where T: Copy , U: Copy {
  fold_right(list, Nil, &|x, y| Cons(f(x), Arc::new(y)))
}

fn new_list<T>(args: Vec<T>) -> List<T> where T: Copy {
  let mut vec = args;
  let mut x: List<T> = Nil;
  while vec.len() > 0 {
    match vec.pop() {
      Some(e) => x = Cons(e, Arc::new(x)),
      None => {}
    }
  }
  x
}

fn main() {
  let list = new_list(vec![1, 2, 3, 4, 5]);
  println!("{list}", list = flat_map(&list, &|x| new_list(vec![x, x])));
}
<|endoftext|>


<commit_before><commit_msg>closure reform<commit_after><|endoftext|>


<commit_before><commit_msg>Moved tests to its own file<commit_after>#![feature(globs)]
extern crate rdb;
use rdb::*;
use std::io::MemReader;

#[test]
fn test_read_length() {
    assert_eq!(
        LengthEncoded::LE(0, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x0)))
        );

    assert_eq!(
        LengthEncoded::LE(16383, false),
        read_length_with_encoding(&mut MemReader::new(vec!(0x7f, 0xff)))
        );

    assert_eq!(
        LengthEncoded::LE(4294967295, false),
        read_length_with_encoding(&mut MemReader::new(
                vec!(0x80, 0xff, 0xff, 0xff, 0xff)))
        );

    assert_eq!(
        LengthEncoded::LE(0, true),
        read_length_with_encoding(&mut MemReader::new(vec!(0xC0))));
}

#[test]
fn test_read_blob() {
    assert_eq!(
        vec!(0x61, 0x62, 0x63, 0x64),
        read_blob(&mut MemReader::new(vec!(4, 0x61, 0x62, 0x63, 0x64))));
}

#[test]
fn test_verify_version() {
    assert_eq!(
        true,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x33))));

    assert_eq!(
        false,
        verify_version(&mut MemReader::new(vec!(0x30, 0x30, 0x30, 0x3a))));
}

#[test]
fn test_verify_magic() {
    assert_eq!(
        true,
        verify_magic(&mut MemReader::new(vec!(0x52, 0x45, 0x44, 0x49, 0x53))));

    assert_eq!(
        false,
        verify_magic(&mut MemReader::new(vec!(0x51, 0x0, 0x0, 0x0, 0x0))));
}
<|endoftext|>


<commit_before><commit_msg>Checking that the Field alias attribute is working as expected<commit_after><|endoftext|>


<commit_before><commit_msg>add raw test<commit_after>extern crate memcache;

#[test]
fn test_raw() {
    let client = memcache::connect("localhost", 2333).unwrap();
    client.set_raw("foo", &[0x1u8, 0x2u8, 0x3u8], 0, 42).unwrap();

    let (value, flags) = client.get_raw("foo").unwrap();
    println!("values: {:?}", value);
    assert!(value == &[0x1i8, 0x2i8, 0x3i8]);
    assert!(flags == 42);
}
<|endoftext|>


<commit_before>//! Functions for altering and converting the color of pixelbufs
use num:: {
    NumCast,
    Float,
};

use std::default::Default;
use std::marker::Reflect;

use color::{Luma, Rgba};
use buffer::{ImageBuffer, Pixel};
use traits::Primitive;
use image::GenericImage;
use math::utils::clamp;
use math::nq;

/// Convert the supplied image to grayscale
// TODO: is the 'static bound on `I` really required? Can we avoid it?
pub fn grayscale<'a, I: GenericImage + 'static>(image: &I)
    -> ImageBuffer<Luma<<I::Pixel as Pixel>::Subpixel>, Vec<<I::Pixel as Pixel>::Subpixel>>
    where I::Pixel: 'static,
          <I::Pixel as Pixel>::Subpixel: Default + 'static + Reflect {
    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    for y in (0..height) {
        for x in (0..width) {
            let p = image.get_pixel(x, y).to_luma();
            out.put_pixel(x, y, p);
        }
    }

    out
}

/// Invert each pixel within the supplied image
/// This function operates in place.
pub fn invert<I: GenericImage>(image: &mut I) {
    let (width, height) = image.dimensions();

    for y in (0..height) {
        for x in (0..width) {
            let mut p = image.get_pixel(x, y);
            p.invert();

            image.put_pixel(x, y, p);
        }
    }
}

/// Adjust the contrast of the supplied image
/// ```contrast``` is the amount to adjust the contrast by.
/// Negative values decrease the contrast and positive values increase the contrast.
// TODO: Do we really need the 'static bound on `I`? Can we avoid it?
pub fn contrast<I, P, S>(image: &I, contrast: f32)
    -> ImageBuffer<P, Vec<S>>
    where I: GenericImage<Pixel=P> + 'static,
          P: Pixel<Subpixel=S> + 'static,
          S: Primitive + 'static {

    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    let max: S = Primitive::max_value();
    let max: f32 = NumCast::from(max).unwrap();

    let percent = ((100.0 + contrast) / 100.0).powi(2);

    for y in (0..height) {
        for x in (0..width) {
            let f = image.get_pixel(x, y).map(|b| {
                let c: f32 = NumCast::from(b).unwrap();

                let d = ((c / max - 0.5) * percent  + 0.5) * max;
                let e = clamp(d, 0.0, max);

                NumCast::from(e).unwrap()
            });

            out.put_pixel(x, y, f);
        }
    }

    out
}

/// Brighten the supplied image
/// ```value``` is the amount to brighten each pixel by.
/// Negative values decrease the brightness and positive values increase it.
// TODO: Is the 'static bound on `I` really required? Can we avoid it?
pub fn brighten<I, P, S>(image: &I, value: i32)
    -> ImageBuffer<P, Vec<S>>
    where I: GenericImage<Pixel=P> + 'static,
          P: Pixel<Subpixel=S> + 'static,
          S: Primitive + 'static {

    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    let max: S = Primitive::max_value();
    let max: i32 = NumCast::from(max).unwrap();

    for y in (0..height) {
        for x in (0..width) {
            let e = image.get_pixel(x, y).map_with_alpha(|b| {
                let c: i32 = NumCast::from(b).unwrap();
                let d = clamp(c + value, 0, max);

                NumCast::from(d).unwrap()
            }, |alpha| alpha);

            out.put_pixel(x, y, e);
        }
    }

    out
}

/// A color map
pub trait ColorMap {
    /// The color type on which the map operates on
    type Color;
    /// Returns the index of the closed match of `color`
    /// in the color map.
    fn index_of(&self, color: &Self::Color) -> usize;
    /// Maps `color` to the closes color in the color map.
    fn map_color(&self, color: &mut Self::Color);
}

/// A bi-level color map
#[derive(Clone, Copy)]
pub struct BiLevel;

impl ColorMap for BiLevel {
    type Color = Luma<u8>;

    #[inline(always)]
    fn index_of(&self, color: &Luma<u8>) -> usize {
        let luma = color.data;
        if luma[0] > 127 {
            1
        } else {
            0
        }
    }

    #[inline(always)]
    fn map_color(&self, color: &mut Luma<u8>) {
        let new_color = 0xFF * self.index_of(color) as u8;
        let luma = &mut color.data;
        luma[0] = new_color;
    }
}

impl ColorMap for nq::NeuQuant {
    type Color = Rgba<u8>;

    #[inline(always)]
    fn index_of(&self, color: &Rgba<u8>) -> usize {
        self.index_of(color.channels())
    }

    #[inline(always)]
    fn map_color(&self, color: &mut Rgba<u8>) {
        self.map_pixel(color.channels_mut())
    }
}

/// Floyd-Steinberg error diffusion
fn diffuse_err<P: Pixel<Subpixel=u8>>(pixel: &mut P, error: [i16; 3], factor: i16) {
    for (e, c) in error.iter().zip(pixel.channels_mut().iter_mut()) {
        *c = match *c as i16 + e * factor / 16 {
            val if val < 0 => {
                0
            },
            val if val > 0xFF => {
                0xFF
            },
            val => val as u8
        }
    }

}

macro_rules! do_dithering(
    ($map:expr, $image:expr, $err:expr, $x:expr, $y:expr) => (
        {
            let old_pixel = $image[($x, $y)];
            let new_pixel = $image.get_pixel_mut($x, $y);
            $map.map_color(new_pixel);
            for ((e, &old), &new) in $err.iter_mut()
                                        .zip(old_pixel.channels().iter())
                                        .zip(new_pixel.channels().iter())
            {
                *e = old as i16 - new as i16
            }
        }
    )
);

/// Reduces the colors of the image using the supplied `color_map` while applying
/// Floyd-Steinberg dithering to improve the visual conception
pub fn dither<Pix, Map>(image: &mut ImageBuffer<Pix, Vec<u8>>, color_map: &Map)
where Map: ColorMap<Color=Pix>,
      Pix: Pixel<Subpixel=u8> + 'static,
{
    let (width, height) = image.dimensions();
    let mut err: [i16; 3] = [0; 3];
    for y in 0..height-1 {
        let x = 0;
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
        diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
        diffuse_err(image.get_pixel_mut(x+1, y+1), err, 1);
        for x in 1..width-1 {
            do_dithering!(color_map, image, err, x, y);
            diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
            diffuse_err(image.get_pixel_mut(x-1, y+1), err, 3);
            diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
            diffuse_err(image.get_pixel_mut(x+1, y+1), err, 1);
        }
        let x = width-1;
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x-1, y+1), err, 3);
        diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
    }
    let y = height-1;
    let x = 0;
    do_dithering!(color_map, image, err, x, y);
    diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
    for x in 1..width-1 {
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
    }
    let x = width-1;
    do_dithering!(color_map, image, err, x, y);
}

/// Reduces the colors using the supplied `color_map` and returns an image of the indices
pub fn index_colors<Pix, Map>(image: &ImageBuffer<Pix, Vec<u8>>, color_map: &Map) ->
ImageBuffer<Luma<u8>, Vec<u8>>
where Map: ColorMap<Color=Pix>,
      Pix: Pixel<Subpixel=u8> + 'static,
{
    let mut indices = ImageBuffer::new(image.width(), image.height());
    for (pixel, idx) in image.pixels().zip(indices.pixels_mut()) {
        *idx = Luma([color_map.index_of(pixel) as u8])
    }
    indices
}

#[cfg(test)]
mod test {

    use ImageBuffer;
    use super::*;

    #[test]
    fn test_dither() {
        let mut image = ImageBuffer::from_raw(2, 2, vec![127, 127, 127, 127]).unwrap();
        let cmap = BiLevel;
        dither(&mut image, &cmap);
        assert_eq!(&*image, &[0, 0xFF, 0xFF, 0]);
        assert_eq!(index_colors(&image, &cmap).into_raw(), vec![0, 1, 1, 0])
    }
}
<commit_msg>imageops::colorops: Remove unused parameter bounds<commit_after>//! Functions for altering and converting the color of pixelbufs
use num:: {
    NumCast,
    Float,
};

use color::{Luma, Rgba};
use buffer::{ImageBuffer, Pixel};
use traits::Primitive;
use image::GenericImage;
use math::utils::clamp;
use math::nq;

/// Convert the supplied image to grayscale
pub fn grayscale<'a, I: GenericImage>(image: &I)
    -> ImageBuffer<Luma<<I::Pixel as Pixel>::Subpixel>, Vec<<I::Pixel as Pixel>::Subpixel>>
    where <I::Pixel as Pixel>::Subpixel: 'static {
    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    for y in (0..height) {
        for x in (0..width) {
            let p = image.get_pixel(x, y).to_luma();
            out.put_pixel(x, y, p);
        }
    }

    out
}

/// Invert each pixel within the supplied image
/// This function operates in place.
pub fn invert<I: GenericImage>(image: &mut I) {
    let (width, height) = image.dimensions();

    for y in (0..height) {
        for x in (0..width) {
            let mut p = image.get_pixel(x, y);
            p.invert();

            image.put_pixel(x, y, p);
        }
    }
}

/// Adjust the contrast of the supplied image
/// ```contrast``` is the amount to adjust the contrast by.
/// Negative values decrease the contrast and positive values increase the contrast.
pub fn contrast<I, P, S>(image: &I, contrast: f32)
    -> ImageBuffer<P, Vec<S>>
    where I: GenericImage<Pixel=P>,
          P: Pixel<Subpixel=S> + 'static,
          S: Primitive + 'static {

    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    let max: S = Primitive::max_value();
    let max: f32 = NumCast::from(max).unwrap();

    let percent = ((100.0 + contrast) / 100.0).powi(2);

    for y in (0..height) {
        for x in (0..width) {
            let f = image.get_pixel(x, y).map(|b| {
                let c: f32 = NumCast::from(b).unwrap();

                let d = ((c / max - 0.5) * percent  + 0.5) * max;
                let e = clamp(d, 0.0, max);

                NumCast::from(e).unwrap()
            });

            out.put_pixel(x, y, f);
        }
    }

    out
}

/// Brighten the supplied image
/// ```value``` is the amount to brighten each pixel by.
/// Negative values decrease the brightness and positive values increase it.
pub fn brighten<I, P, S>(image: &I, value: i32)
    -> ImageBuffer<P, Vec<S>>
    where I: GenericImage<Pixel=P>,
          P: Pixel<Subpixel=S> + 'static,
          S: Primitive + 'static {

    let (width, height) = image.dimensions();
    let mut out = ImageBuffer::new(width, height);

    let max: S = Primitive::max_value();
    let max: i32 = NumCast::from(max).unwrap();

    for y in (0..height) {
        for x in (0..width) {
            let e = image.get_pixel(x, y).map_with_alpha(|b| {
                let c: i32 = NumCast::from(b).unwrap();
                let d = clamp(c + value, 0, max);

                NumCast::from(d).unwrap()
            }, |alpha| alpha);

            out.put_pixel(x, y, e);
        }
    }

    out
}

/// A color map
pub trait ColorMap {
    /// The color type on which the map operates on
    type Color;
    /// Returns the index of the closed match of `color`
    /// in the color map.
    fn index_of(&self, color: &Self::Color) -> usize;
    /// Maps `color` to the closes color in the color map.
    fn map_color(&self, color: &mut Self::Color);
}

/// A bi-level color map
#[derive(Clone, Copy)]
pub struct BiLevel;

impl ColorMap for BiLevel {
    type Color = Luma<u8>;

    #[inline(always)]
    fn index_of(&self, color: &Luma<u8>) -> usize {
        let luma = color.data;
        if luma[0] > 127 {
            1
        } else {
            0
        }
    }

    #[inline(always)]
    fn map_color(&self, color: &mut Luma<u8>) {
        let new_color = 0xFF * self.index_of(color) as u8;
        let luma = &mut color.data;
        luma[0] = new_color;
    }
}

impl ColorMap for nq::NeuQuant {
    type Color = Rgba<u8>;

    #[inline(always)]
    fn index_of(&self, color: &Rgba<u8>) -> usize {
        self.index_of(color.channels())
    }

    #[inline(always)]
    fn map_color(&self, color: &mut Rgba<u8>) {
        self.map_pixel(color.channels_mut())
    }
}

/// Floyd-Steinberg error diffusion
fn diffuse_err<P: Pixel<Subpixel=u8>>(pixel: &mut P, error: [i16; 3], factor: i16) {
    for (e, c) in error.iter().zip(pixel.channels_mut().iter_mut()) {
        *c = match *c as i16 + e * factor / 16 {
            val if val < 0 => {
                0
            },
            val if val > 0xFF => {
                0xFF
            },
            val => val as u8
        }
    }

}

macro_rules! do_dithering(
    ($map:expr, $image:expr, $err:expr, $x:expr, $y:expr) => (
        {
            let old_pixel = $image[($x, $y)];
            let new_pixel = $image.get_pixel_mut($x, $y);
            $map.map_color(new_pixel);
            for ((e, &old), &new) in $err.iter_mut()
                                        .zip(old_pixel.channels().iter())
                                        .zip(new_pixel.channels().iter())
            {
                *e = old as i16 - new as i16
            }
        }
    )
);

/// Reduces the colors of the image using the supplied `color_map` while applying
/// Floyd-Steinberg dithering to improve the visual conception
pub fn dither<Pix, Map>(image: &mut ImageBuffer<Pix, Vec<u8>>, color_map: &Map)
where Map: ColorMap<Color=Pix>,
      Pix: Pixel<Subpixel=u8> + 'static,
{
    let (width, height) = image.dimensions();
    let mut err: [i16; 3] = [0; 3];
    for y in 0..height-1 {
        let x = 0;
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
        diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
        diffuse_err(image.get_pixel_mut(x+1, y+1), err, 1);
        for x in 1..width-1 {
            do_dithering!(color_map, image, err, x, y);
            diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
            diffuse_err(image.get_pixel_mut(x-1, y+1), err, 3);
            diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
            diffuse_err(image.get_pixel_mut(x+1, y+1), err, 1);
        }
        let x = width-1;
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x-1, y+1), err, 3);
        diffuse_err(image.get_pixel_mut(x+0, y+1), err, 5);
    }
    let y = height-1;
    let x = 0;
    do_dithering!(color_map, image, err, x, y);
    diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
    for x in 1..width-1 {
        do_dithering!(color_map, image, err, x, y);
        diffuse_err(image.get_pixel_mut(x+1, y+0), err, 7);
    }
    let x = width-1;
    do_dithering!(color_map, image, err, x, y);
}

/// Reduces the colors using the supplied `color_map` and returns an image of the indices
pub fn index_colors<Pix, Map>(image: &ImageBuffer<Pix, Vec<u8>>, color_map: &Map) ->
ImageBuffer<Luma<u8>, Vec<u8>>
where Map: ColorMap<Color=Pix>,
      Pix: Pixel<Subpixel=u8> + 'static,
{
    let mut indices = ImageBuffer::new(image.width(), image.height());
    for (pixel, idx) in image.pixels().zip(indices.pixels_mut()) {
        *idx = Luma([color_map.index_of(pixel) as u8])
    }
    indices
}

#[cfg(test)]
mod test {

    use ImageBuffer;
    use super::*;

    #[test]
    fn test_dither() {
        let mut image = ImageBuffer::from_raw(2, 2, vec![127, 127, 127, 127]).unwrap();
        let cmap = BiLevel;
        dither(&mut image, &cmap);
        assert_eq!(&*image, &[0, 0xFF, 0xFF, 0]);
        assert_eq!(index_colors(&image, &cmap).into_raw(), vec![0, 1, 1, 0])
    }
}
<|endoftext|>


<commit_before><commit_msg>Creates tests file for xmlutils.<commit_after>extern crate rusoto;
extern crate xml;

use xml::reader::*;
use rusoto::xmlutil::*;

#[test]
fn parse_sqs_list_queues() {
    panic!("not implemented.");
}
<|endoftext|>


<commit_before><commit_msg>add regression test for issue #37508<commit_after>// only-x86_64
// compile-flags: -Ccode-model=large --crate-type lib
// build-pass
//
// Regression test for issue #37508

#![no_main]
#![no_std]
#![feature(thread_local, lang_items)]

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_panic: &PanicInfo<'_>) -> ! {
    loop {}
}

pub struct BB;

#[thread_local]
static mut KEY: Key = Key { inner: BB, dtor_running: false };

pub unsafe fn set() -> Option<&'static BB> {
    if KEY.dtor_running {
        return None;
    }
    Some(&KEY.inner)
}

pub struct Key {
    inner: BB,
    dtor_running: bool,
}
<|endoftext|>


<commit_before><commit_msg> #32 Added some debug logging for invalid actions<commit_after><|endoftext|>


<commit_before><commit_msg>libxen/x86: Add module callbacks<commit_after><|endoftext|>