<commit_before>/*
Copyright 2014 Benjamin Elder from https://github.com/BenTheElder/slack-rs

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.
*/
#![feature(core)]
extern crate hyper;
extern crate websocket;
extern crate openssl;
extern crate "rustc-serialize" as rustc_serialize;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,Receiver,channel};
use std::thread;
use std::io::Read;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::Client;
pub use websocket::message::Message;
use websocket::Sender as WsSender;
use websocket::Receiver as WsReceiver;
use websocket::dataframe::DataFrame;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;

pub type WsClient = Client<websocket::dataframe::DataFrame,
                           websocket::client::sender::Sender<websocket::stream::WebSocketStream>,
                           websocket::client::receiver::Receiver<websocket::stream::WebSocketStream>>;

///Implement this trait in your code to handle message events
pub trait MessageHandler {
	///When a message is received this will be called with self, the slack client,
	///and the json encoded string payload.
	fn on_receive(&mut self, cli: &mut RtmClient, json_str: &str);

	///Called when a ping is received; you do NOT need to handle the reply pong,
	///but you may use this event to track the connection as a keep-alive.
	fn on_ping(&mut self, cli: &mut RtmClient);

	///Called when the connection is closed for any reason.
	fn on_close(&mut self, cli: &mut RtmClient);

	///Called when the connection is opened.
	fn on_connect(&mut self, cli: &mut RtmClient);
}

///Contains information about the team the bot is logged into.
pub struct Team {
	name : String,
	id : String
}

impl Team {
	///private, create empty team.
	fn new() -> Team {
		Team{name: String::new(), id: String::new()}
	}

	///Returns the team's name as a String
	pub fn get_name(&self) -> String {
		self.name.clone()
	}

	///Returns the team's id as a String
	pub fn get_id(&self) -> String {
		self.id.clone()
	}
}

impl Clone for Team {
	fn clone(&self) -> Self {
		Team{
			name: self.name.clone(),
			id: self.id.clone()
		}
	}

	fn clone_from(&mut self, source: &Self) {
		self.name = source.name.clone();
		self.id = source.id.clone();
	}
}

///The actual messaging client.
pub struct RtmClient{
	name : String,
	id : String,
	team : Team,
	msg_num: AtomicIsize,
	outs : Option<Sender<Message>>
}

///Error string. (FIXME: better error return values/ custom error type)
static RTM_INVALID : &'static str = "Invalid data returned from slack (rtm.start)";

impl RtmClient {

	///Creates a new empty client.
	pub fn new() -> RtmClient {
		RtmClient{
			name : String::new(),
			id : String::new(),
			team : Team::new(),
			msg_num: AtomicIsize::new(0),
			outs : None
		}
	}

	pub fn get_outs(&self) -> Option<Sender<Message>> {
		self.outs.clone()
	}

	///Returns the name of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_name(&self) -> String {
		return self.name.clone();
	}

	///Returns the id of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_id(&self) -> String {
		return self.id.clone();
	}

	///Returns the Team struct of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_team<'a>(&'a self) -> &'a Team {
		&self.team
	}

	///Returns a unique identifier to be used in the 'id' field of a message
	///sent to slack.
	pub fn get_msg_uid(&self) -> isize {
		self.msg_num.fetch_add(1, Ordering::SeqCst)
	}

	///Allows sending a json string message over the websocket connection.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///Note that you will need to form a valid json reply yourself if you
	///use this method, and you will also need to retrieve a unique id for
	///the message via RtmClient.get_msg_uid()
	///Only valid after login.
	pub fn send(&mut self, s : &str) -> Result<(),String> {
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(Message::Text(s.to_string())) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Allows sending a textual string message over the websocket connection,
	///to the requested channel id. Ideal usage would be EG:
	///extract the channel in on_receive and then send back a message to the channel.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///This method also handles getting a unique id and formatting the actual json
	///sent.
	///Only valid after login.
	pub fn send_message(&self, chan: &str, msg: &str) -> Result<(),String>{
		let n = self.get_msg_uid();
		let mstr = "{".to_string()+format!(r#""id": {},"type": "message","channel": "{}","text": "{}""#,n,chan,msg).as_slice()+"}";
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(Message::Text(mstr)) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Logs in to slack. Call this before calling run.
	///Alternatively use login_and_run
	pub fn login(&mut self, token: &str) -> Result<(WsClient,Receiver<Message>),String> {
		//Slack real time api url
		let url = "https://slack.com/api/rtm.start?token=".to_string()+token;

		//Create http client and send request to slack
		let mut client = hyper::Client::new();
		let mut res = match client.get(url.as_slice()).send() {
			Ok(res) => res,
			Err(err) => return Err(format!("Hyper Error: {:?}", err))
		};

		//Read result string
		let mut res_str = String::new();

		match res.read_to_string(&mut res_str) {
			Err(err) => return Err(format!("{:?}", err)),
			_ => {},
		};

		//Start parsing json. We do not map to a structure,
		//because slack makes no guarantee that there won't be extra fields.
		let js = match Json::from_str(res_str.as_slice()) {
			Ok(js) => js,
			Err(err) => return Err(format!("{:?}", err))
		};

		if !js.is_object() {
			return Err(format!("{} : json is not an object.", RTM_INVALID))
		}
		let jo = js.as_object().unwrap();

		match jo.get("ok") {
			Some(v) => {
				if !(v.is_boolean() && v.as_boolean().unwrap() == true) {
					return Err(format!("{} : js.get(\"ok\") != true : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"ok\") returned None. : {:?}", RTM_INVALID, jo))
		}

		let wss_url_string = match jo.get("url") {
			Some(wss_url) => {
				if wss_url.is_string() {
					wss_url.as_string().unwrap()
				}else{
					return Err(format!("{} : jo.get(\"url\") failed! : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"url\") returned None. : {:?}", RTM_INVALID, jo))
		};

		let wss_url = match Url::parse(wss_url_string) {
			Ok(url) => url,
			Err(err) => return Err(format!("{:?}", err))
		};

		let jself = match jo.get("self") {
			Some(jself) => {
				if jself.is_object() {
					jself.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jself.get("name") {
			Some(jname) => {
				if jname.is_string() {
					self.name = jname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}
		match jself.get("id") {
			Some(jid) => {
				if jid.is_string() {
					self.id = jid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}

		let jteam = match jo.get("team") {
			Some(jteam) => {
				if jteam.is_object() {
					jteam.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jteam.get("name") {
			Some(jtname) => {
				if jtname.is_string() {
					self.team.name = jtname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}
		match jteam.get("id") {
			Some(jtid) => {
				if jtid.is_string() {
					self.team.id = jtid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}

		let req = match websocket::client::Client::connect(wss_url.clone()) {
			Ok(res) => res,
			Err(err) => return Err(format!("{:?}, Websocket request to `{:?}` failed", err, wss_url))
		};

		//Connect via tls, do websocket handshake.
		let res = match req.send() {
			Ok(res) => res,
			Err(err) => {
				return Err(format!("{:?}, Websocket request to `{:?}` failed", err, wss_url))
			}
		};

		match res.validate() {
			Ok(()) => { }
			Err(err) => {
				return Err(format!("Error: res.validate(): {:?}", err))
			}
		}

		let (tx,rx) = channel::<Message>();
		self.outs = Some(tx.clone());
		Ok((res.begin(),rx))
	}

	///Runs the message receive loop
	pub fn run<T: MessageHandler>(&mut self, handler: &mut T, client: WsClient, rx: Receiver<Message>) -> Result<(),String> {
		//for sending messages
		let tx = match self.outs {
			Some(ref mut tx) => { tx.clone() },
			None => { return Err("No tx!".to_string()); }
		};

		let (mut sender, mut receiver) = client.split();

		handler.on_connect(self);
		//websocket send loop
		let guard = thread::scoped(move || -> () {
			loop {
				let msg = match rx.recv() {
					Ok(m) => { m },
					Err(_) => { return; }
				};

				let closing = match msg {
					Message::Close(_) => { true },
					_ => { false }
				};
				match sender.send_message(msg) {
					Ok(_) => {},
					Err(_) => { return; }//panic!(format!("{:?}", err))
				}
				if closing {
					drop(rx);
					return;
				}
			}
		});

		//receive loop
		for message in receiver.incoming_messages() {
			let message = match message {
				Ok(message) => message,
				Err(err) => {
					return Err(format!("{:?}", err));
				}
			};

			match message {
				Message::Text(data) => {
					handler.on_receive(self, data.as_slice());
				},
				Message::Ping(data) => {
					handler.on_ping(self);
					let message = Message::Pong(data);
					match tx.send(message) {
						Ok(_) => {},
						Err(err) => {
							return Err(format!("{:?}", err));
						}
					}
				},
				Message::Close(data) => {
					handler.on_close(self);
					let message = Message::Close(data);
					match tx.send(message) {
						Ok(_) => {},
						Err(err) => {
							return Err(format!("{:?}", err));
						}
					}
					return Ok(());
				},
				_ => {}
			}
		}
		let _ = guard.join();
		Ok(())
	}

	///Runs the main loop for the client after logging in to slack,
	///returns an error if the process fails at an point, or an Ok(()) on succesful
	///close.
	///Takes a MessageHandler (implemented by the user) to call events handlers on.
	///once the first on_receive() or on_ping is called on the MessageHandler, you
	///can soon the 'Only valid after login' methods are safe to use.
	///Sending is run in a thread in parallel while the receive loop runs on the main thread.
	///Both loops should end on return.
	///Sending should be thread safe as the messages are passed in via a channel in
	///RtmClient.send and RtmClient.send_message
	pub fn login_and_run<T: MessageHandler>(&mut self, handler: &mut T, token : &str) -> Result<(),String> {
		let (client,rx) = match self.login(token) {
			Ok((c,r)) => { (c,r) },
			Err(err) => { return Err(format!("{:?}",err)); }
		};
		self.run(handler, client, rx)
	}
}
<commit_msg>Use rustc_serialize instead of "rustc-serialize"<commit_after>/*
Copyright 2014 Benjamin Elder from https://github.com/BenTheElder/slack-rs

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.
*/
#![feature(core)]
extern crate hyper;
extern crate websocket;
extern crate openssl;
extern crate rustc_serialize;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,Receiver,channel};
use std::thread;
use std::io::Read;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::Client;
pub use websocket::message::Message;
use websocket::Sender as WsSender;
use websocket::Receiver as WsReceiver;
use websocket::dataframe::DataFrame;
use websocket::stream::WebSocketStream;
use websocket::client::request::Url;

pub type WsClient = Client<websocket::dataframe::DataFrame,
                           websocket::client::sender::Sender<websocket::stream::WebSocketStream>,
                           websocket::client::receiver::Receiver<websocket::stream::WebSocketStream>>;

///Implement this trait in your code to handle message events
pub trait MessageHandler {
	///When a message is received this will be called with self, the slack client,
	///and the json encoded string payload.
	fn on_receive(&mut self, cli: &mut RtmClient, json_str: &str);

	///Called when a ping is received; you do NOT need to handle the reply pong,
	///but you may use this event to track the connection as a keep-alive.
	fn on_ping(&mut self, cli: &mut RtmClient);

	///Called when the connection is closed for any reason.
	fn on_close(&mut self, cli: &mut RtmClient);

	///Called when the connection is opened.
	fn on_connect(&mut self, cli: &mut RtmClient);
}

///Contains information about the team the bot is logged into.
pub struct Team {
	name : String,
	id : String
}

impl Team {
	///private, create empty team.
	fn new() -> Team {
		Team{name: String::new(), id: String::new()}
	}

	///Returns the team's name as a String
	pub fn get_name(&self) -> String {
		self.name.clone()
	}

	///Returns the team's id as a String
	pub fn get_id(&self) -> String {
		self.id.clone()
	}
}

impl Clone for Team {
	fn clone(&self) -> Self {
		Team{
			name: self.name.clone(),
			id: self.id.clone()
		}
	}

	fn clone_from(&mut self, source: &Self) {
		self.name = source.name.clone();
		self.id = source.id.clone();
	}
}

///The actual messaging client.
pub struct RtmClient{
	name : String,
	id : String,
	team : Team,
	msg_num: AtomicIsize,
	outs : Option<Sender<Message>>
}

///Error string. (FIXME: better error return values/ custom error type)
static RTM_INVALID : &'static str = "Invalid data returned from slack (rtm.start)";

impl RtmClient {

	///Creates a new empty client.
	pub fn new() -> RtmClient {
		RtmClient{
			name : String::new(),
			id : String::new(),
			team : Team::new(),
			msg_num: AtomicIsize::new(0),
			outs : None
		}
	}

	pub fn get_outs(&self) -> Option<Sender<Message>> {
		self.outs.clone()
	}

	///Returns the name of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_name(&self) -> String {
		return self.name.clone();
	}

	///Returns the id of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_id(&self) -> String {
		return self.id.clone();
	}

	///Returns the Team struct of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_team<'a>(&'a self) -> &'a Team {
		&self.team
	}

	///Returns a unique identifier to be used in the 'id' field of a message
	///sent to slack.
	pub fn get_msg_uid(&self) -> isize {
		self.msg_num.fetch_add(1, Ordering::SeqCst)
	}

	///Allows sending a json string message over the websocket connection.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///Note that you will need to form a valid json reply yourself if you
	///use this method, and you will also need to retrieve a unique id for
	///the message via RtmClient.get_msg_uid()
	///Only valid after login.
	pub fn send(&mut self, s : &str) -> Result<(),String> {
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(Message::Text(s.to_string())) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Allows sending a textual string message over the websocket connection,
	///to the requested channel id. Ideal usage would be EG:
	///extract the channel in on_receive and then send back a message to the channel.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///This method also handles getting a unique id and formatting the actual json
	///sent.
	///Only valid after login.
	pub fn send_message(&self, chan: &str, msg: &str) -> Result<(),String>{
		let n = self.get_msg_uid();
		let mstr = "{".to_string()+format!(r#""id": {},"type": "message","channel": "{}","text": "{}""#,n,chan,msg).as_slice()+"}";
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(Message::Text(mstr)) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Logs in to slack. Call this before calling run.
	///Alternatively use login_and_run
	pub fn login(&mut self, token: &str) -> Result<(WsClient,Receiver<Message>),String> {
		//Slack real time api url
		let url = "https://slack.com/api/rtm.start?token=".to_string()+token;

		//Create http client and send request to slack
		let mut client = hyper::Client::new();
		let mut res = match client.get(url.as_slice()).send() {
			Ok(res) => res,
			Err(err) => return Err(format!("Hyper Error: {:?}", err))
		};

		//Read result string
		let mut res_str = String::new();

		match res.read_to_string(&mut res_str) {
			Err(err) => return Err(format!("{:?}", err)),
			_ => {},
		};

		//Start parsing json. We do not map to a structure,
		//because slack makes no guarantee that there won't be extra fields.
		let js = match Json::from_str(res_str.as_slice()) {
			Ok(js) => js,
			Err(err) => return Err(format!("{:?}", err))
		};

		if !js.is_object() {
			return Err(format!("{} : json is not an object.", RTM_INVALID))
		}
		let jo = js.as_object().unwrap();

		match jo.get("ok") {
			Some(v) => {
				if !(v.is_boolean() && v.as_boolean().unwrap() == true) {
					return Err(format!("{} : js.get(\"ok\") != true : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"ok\") returned None. : {:?}", RTM_INVALID, jo))
		}

		let wss_url_string = match jo.get("url") {
			Some(wss_url) => {
				if wss_url.is_string() {
					wss_url.as_string().unwrap()
				}else{
					return Err(format!("{} : jo.get(\"url\") failed! : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"url\") returned None. : {:?}", RTM_INVALID, jo))
		};

		let wss_url = match Url::parse(wss_url_string) {
			Ok(url) => url,
			Err(err) => return Err(format!("{:?}", err))
		};

		let jself = match jo.get("self") {
			Some(jself) => {
				if jself.is_object() {
					jself.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jself.get("name") {
			Some(jname) => {
				if jname.is_string() {
					self.name = jname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}
		match jself.get("id") {
			Some(jid) => {
				if jid.is_string() {
					self.id = jid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}

		let jteam = match jo.get("team") {
			Some(jteam) => {
				if jteam.is_object() {
					jteam.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jteam.get("name") {
			Some(jtname) => {
				if jtname.is_string() {
					self.team.name = jtname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}
		match jteam.get("id") {
			Some(jtid) => {
				if jtid.is_string() {
					self.team.id = jtid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}

		let req = match websocket::client::Client::connect(wss_url.clone()) {
			Ok(res) => res,
			Err(err) => return Err(format!("{:?}, Websocket request to `{:?}` failed", err, wss_url))
		};

		//Connect via tls, do websocket handshake.
		let res = match req.send() {
			Ok(res) => res,
			Err(err) => {
				return Err(format!("{:?}, Websocket request to `{:?}` failed", err, wss_url))
			}
		};

		match res.validate() {
			Ok(()) => { }
			Err(err) => {
				return Err(format!("Error: res.validate(): {:?}", err))
			}
		}

		let (tx,rx) = channel::<Message>();
		self.outs = Some(tx.clone());
		Ok((res.begin(),rx))
	}

	///Runs the message receive loop
	pub fn run<T: MessageHandler>(&mut self, handler: &mut T, client: WsClient, rx: Receiver<Message>) -> Result<(),String> {
		//for sending messages
		let tx = match self.outs {
			Some(ref mut tx) => { tx.clone() },
			None => { return Err("No tx!".to_string()); }
		};

		let (mut sender, mut receiver) = client.split();

		handler.on_connect(self);
		//websocket send loop
		let guard = thread::scoped(move || -> () {
			loop {
				let msg = match rx.recv() {
					Ok(m) => { m },
					Err(_) => { return; }
				};

				let closing = match msg {
					Message::Close(_) => { true },
					_ => { false }
				};
				match sender.send_message(msg) {
					Ok(_) => {},
					Err(_) => { return; }//panic!(format!("{:?}", err))
				}
				if closing {
					drop(rx);
					return;
				}
			}
		});

		//receive loop
		for message in receiver.incoming_messages() {
			let message = match message {
				Ok(message) => message,
				Err(err) => {
					return Err(format!("{:?}", err));
				}
			};

			match message {
				Message::Text(data) => {
					handler.on_receive(self, data.as_slice());
				},
				Message::Ping(data) => {
					handler.on_ping(self);
					let message = Message::Pong(data);
					match tx.send(message) {
						Ok(_) => {},
						Err(err) => {
							return Err(format!("{:?}", err));
						}
					}
				},
				Message::Close(data) => {
					handler.on_close(self);
					let message = Message::Close(data);
					match tx.send(message) {
						Ok(_) => {},
						Err(err) => {
							return Err(format!("{:?}", err));
						}
					}
					return Ok(());
				},
				_ => {}
			}
		}
		let _ = guard.join();
		Ok(())
	}

	///Runs the main loop for the client after logging in to slack,
	///returns an error if the process fails at an point, or an Ok(()) on succesful
	///close.
	///Takes a MessageHandler (implemented by the user) to call events handlers on.
	///once the first on_receive() or on_ping is called on the MessageHandler, you
	///can soon the 'Only valid after login' methods are safe to use.
	///Sending is run in a thread in parallel while the receive loop runs on the main thread.
	///Both loops should end on return.
	///Sending should be thread safe as the messages are passed in via a channel in
	///RtmClient.send and RtmClient.send_message
	pub fn login_and_run<T: MessageHandler>(&mut self, handler: &mut T, token : &str) -> Result<(),String> {
		let (client,rx) = match self.login(token) {
			Ok((c,r)) => { (c,r) },
			Err(err) => { return Err(format!("{:?}",err)); }
		};
		self.run(handler, client, rx)
	}
}
<|endoftext|>


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


<commit_before><commit_msg>run_command API update<commit_after><|endoftext|>


<commit_before><commit_msg>Rename parameters for clarity<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to add value.rs file.<commit_after>/* This module collects value functions. */

use std::str::FromStr;

use game;
use game::{PlayerColor, LineState};

#[derive(Clone, Copy, Debug)]
pub enum Simple {
    Subsets,
    WinOnly,
}

impl Simple {
    pub fn value_of(self,
                    structure: &game::Structure,
                    state: &game::State,
                    my_color: PlayerColor)
                    -> i32 {
        match self {
            Simple::Subsets => subsets(structure, state, my_color),
            Simple::WinOnly => win_only(structure, state, my_color),
        }
    }
}

impl FromStr for Simple {
    type Err = ();
    fn from_str(s: &str) -> Result<Simple, ()> {
        match s {
            "subsets" => Ok(Simple::Subsets),
            "win" => Ok(Simple::WinOnly),
            _ => Err(())
        }
    }
}

// For each possible winning subset, this adds some score.
// One piece on a line => 1 Point
// Two pieces on a line => 4 Points
// Three pieces on a line => 9 Points
pub fn subsets(structure: &game::Structure, state: &game::State, my_color: PlayerColor) -> i32 {
    if let game::VictoryState::Win { winner, .. } = state.victory_state {
        if winner == my_color {
            return 1000;
        } else {
            return -1000;
        }
    }

    let mut score = 0;

    for subset in &structure.source {
        score += match subset.win_state(state) {
            LineState::Empty => 0,
            LineState::Mixed => 0,
            LineState::Pure { color, count } => {
                if color == my_color {
                    (count * count) as i32
                } else {
                    -(count * count) as i32
                }
            }
            LineState::Win(_) => {
                panic!("If the game is already won this should be caught earlier.")
            }
        }
    }

    score
}

#[test]
fn test_subsets_values() {
    use game::{Structure, State, Position2};
    use game::PlayerColor::White;
    use constants::LINES;

    let structure = Structure::new(&LINES);

    let mut state = State::new();
    assert_eq!(0, subsets(&structure, &state, White));

    state.insert(&structure, Position2::new(0, 0));
    assert_eq!(7, subsets(&structure, &state, White));

    state.insert(&structure, Position2::new(0, 3));
    assert_eq!(0, subsets(&structure, &state, White));
}

// This value function only checks if you won the game already.
pub fn win_only(structure: &game::Structure, state: &game::State, my_color: PlayerColor) -> i32 {
    if let game::VictoryState::Win { winner, .. } = state.victory_state {
        if winner == my_color {
            return 1;
        } else {
            return -1;
        }
    } else {
        0
    }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #137<commit_after>//! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x)     = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x)   = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
//! ```
//!
//! `F_k = F_{k-1} + F_k`, `F_1 = F_2 = 1` より、
//!
//! ```math
//! (1 - x - x^2) A_F(x) = x
//! ```
//!
//! `A_F(x)` は正の整数なので `n := A_F(x) > 0` とおくと、以下の二次方程式を得る。
//!
//! ```math
//! n x^2 + (n + 1) x - n = 0
//! ```
//!
//! この方程式が有理数解をもつのは、判別式 `D` が平方数の場合であり、ある整数 `m` を用いると以下のように表せる場合である。
//!
//! ```math
//! D = (n+1)^2 + 4n^2 = m^2
//! (5n+1)^2 - 5m^2 = -4
//! ```
//!
//! これは Pell 方程式であり、解を列挙すれば良い。
//!
//! `p := 5n + 1`, `q := m` とおくと、
//! `p_0 = 1`, `q_0 = 1` より、
//! ```math
//! p_{k+1} = \frac{3p_k + 5q_k}{2}
//! q_{k+1} = \frac{p_k + 3q_k}{2}
//! ```
//!
//! となり、これが一般解である。

#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

#[macro_use(problem)] extern crate common;
extern crate itertools;

use itertools::Unfold;

fn compute(i: usize) -> u64 {
    Unfold::new((1, 1), |state| {
        let next = ((3 * state.0 + 5 * state.1) / 2,
                    (state.0 + 3 * state.1) / 2);
        *state = next;
        Some(next)
    }).filter_map(|(p, q)| {
        if p % 5 == 1 {
            Some((p / 5, q))
        } else {
            None
        }
    }).nth(i).unwrap().0
}

fn solve() -> String {
    compute(14).to_string()
}

problem!("1120149658760", solve);

#[cfg(test)]
mod tests {
    #[test]
    fn tenth_sol() {
        assert_eq!(74049690, super::compute(9));
    }
}
<|endoftext|>


<commit_before><commit_msg>Cleanup imports<commit_after><|endoftext|>


<commit_before><commit_msg>Fix backwards red/blue (lol)<commit_after><|endoftext|>


<commit_before>/*!
Test supports module.

*/

#![allow(dead_code)]

use glutin;
use glium::{self, DisplayBuild};

use std::env;

/// Returns true if we are executing headless tests.
pub fn is_headless() -> bool {
    env::var("HEADLESS_TESTS").is_ok()
}

/// Builds a headless display for tests.
#[cfg(feature = "headless")]
pub fn build_display() -> glium::Display {
    let display = if is_headless() {
        glutin::HeadlessRendererBuilder::new(1024, 768).with_gl_debug_flag(true)
                                                       .build_glium().unwrap()
    } else {
        glutin::WindowBuilder::new().with_gl_debug_flag(true).with_visibility(false)
                                    .build_glium().unwrap()
    };

    display
}

/// Builds a headless display for tests.
#[cfg(not(feature = "headless"))]
pub fn build_display() -> glium::Display {
    assert!(!is_headless());
    glutin::WindowBuilder::new().with_gl_debug_flag(true).with_visibility(false)
                                .build_glium().unwrap()
}

/// Builds a 2x2 unicolor texture.
pub fn build_unicolor_texture2d(display: &glium::Display, red: f32, green: f32, blue: f32)
    -> glium::Texture2d
{
    let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);

    glium::texture::Texture2d::new(display, vec![
        vec![color, color],
        vec![color, color],
    ])
}

/// Builds a vertex buffer, index buffer, and program, to draw red `(1.0, 0.0, 0.0, 1.0)` to the whole screen.
pub fn build_fullscreen_red_pipeline(display: &glium::Display) -> (glium::vertex::VertexBufferAny,
    glium::IndexBuffer, glium::Program)
{
    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
    }

    implement_vertex!(Vertex, position);

    (
        glium::VertexBuffer::new(display, vec![
            Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
            Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
        ]).into_vertex_buffer_any(),

        glium::IndexBuffer::new(display, glium::index::TriangleStrip(vec![0u8, 1, 2, 3])),

        glium::Program::from_source(display,
            "
                #version 110

                attribute vec2 position;

                void main() {
                    gl_Position = vec4(position, 0.0, 1.0);
                }
            ",
            "
                #version 110

                void main() {
                    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
                }
            ",
            None).unwrap()
    )
}

/// Builds a vertex buffer and an index buffer corresponding to a rectangle.
///
/// The vertex buffer has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib(display: &glium::Display)
    -> (glium::vertex::VertexBufferAny, glium::IndexBuffer)
{
    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
    }

    implement_vertex!(Vertex, position);

    (
        glium::VertexBuffer::new(display, vec![
            Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
            Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
        ]).into_vertex_buffer_any(),

        glium::IndexBuffer::new(display, glium::index::TriangleStrip(vec![0u8, 1, 2, 3])),
    )
}

/// Builds a texture suitable for rendering.
pub fn build_renderable_texture(display: &glium::Display) -> glium::Texture2d {
    glium::Texture2d::empty(display, 1024, 1024)
}
<commit_msg>Make tests support module more flexible with the facade<commit_after>/*!
Test supports module.

*/

#![allow(dead_code)]

use glutin;
use glium::{self, DisplayBuild};
use glium::backend::Facade;

use std::env;

/// Returns true if we are executing headless tests.
pub fn is_headless() -> bool {
    env::var("HEADLESS_TESTS").is_ok()
}

/// Builds a headless display for tests.
#[cfg(feature = "headless")]
pub fn build_display() -> glium::Display {
    let display = if is_headless() {
        glutin::HeadlessRendererBuilder::new(1024, 768).with_gl_debug_flag(true)
                                                       .build_glium().unwrap()
    } else {
        glutin::WindowBuilder::new().with_gl_debug_flag(true).with_visibility(false)
                                    .build_glium().unwrap()
    };

    display
}

/// Builds a headless display for tests.
#[cfg(not(feature = "headless"))]
pub fn build_display() -> glium::Display {
    assert!(!is_headless());
    glutin::WindowBuilder::new().with_gl_debug_flag(true).with_visibility(false)
                                .build_glium().unwrap()
}

/// Builds a 2x2 unicolor texture.
pub fn build_unicolor_texture2d<F>(facade: &F, red: f32, green: f32, blue: f32)
    -> glium::Texture2d where F: Facade
{
    let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);

    glium::texture::Texture2d::new(facade, vec![
        vec![color, color],
        vec![color, color],
    ])
}

/// Builds a vertex buffer, index buffer, and program, to draw red `(1.0, 0.0, 0.0, 1.0)` to the whole screen.
pub fn build_fullscreen_red_pipeline<F>(facade: &F) -> (glium::vertex::VertexBufferAny,
    glium::IndexBuffer, glium::Program) where F: Facade
{
    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
    }

    implement_vertex!(Vertex, position);

    (
        glium::VertexBuffer::new(facade, vec![
            Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
            Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
        ]).into_vertex_buffer_any(),

        glium::IndexBuffer::new(facade, glium::index::TriangleStrip(vec![0u8, 1, 2, 3])),

        glium::Program::from_source(facade,
            "
                #version 110

                attribute vec2 position;

                void main() {
                    gl_Position = vec4(position, 0.0, 1.0);
                }
            ",
            "
                #version 110

                void main() {
                    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
                }
            ",
            None).unwrap()
    )
}

/// Builds a vertex buffer and an index buffer corresponding to a rectangle.
///
/// The vertex buffer has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib<F>(facade: &F)
    -> (glium::vertex::VertexBufferAny, glium::IndexBuffer) where F: Facade
{
    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
    }

    implement_vertex!(Vertex, position);

    (
        glium::VertexBuffer::new(facade, vec![
            Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
            Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
        ]).into_vertex_buffer_any(),

        glium::IndexBuffer::new(facade, glium::index::TriangleStrip(vec![0u8, 1, 2, 3])),
    )
}

/// Builds a texture suitable for rendering.
pub fn build_renderable_texture<F>(facade: &F) -> glium::Texture2d where F: Facade {
    glium::Texture2d::empty(facade, 1024, 1024)
}
<|endoftext|>


<commit_before>use std::collections::HashMap;

use metric::Metric;

pub trait Registry<'a> {
    fn get(&'a self, name: &'a str) -> &'a Metric;

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T);
}

pub struct StdRegistry<'a> {
    metrics: HashMap<&'a str, Box<Metric + 'a>>,
}

// Specific stuff for registry goes here
impl<'a> Registry<'a> for StdRegistry<'a> {
    fn get(&'a self, name: &'a str) -> &'a Metric {
        &*self.metrics[name]
    }

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T) {
        let boxed = Box::new(metric);

        self.metrics.insert(name, boxed);
    }
}

// General StdRegistry
impl<'a> StdRegistry<'a> {
    fn new() -> StdRegistry<'a> {
        StdRegistry{
            metrics: HashMap::new()
        }
    }
}

#[cfg(test)]
mod test {
    use metric::Metric;
    use meter::StdMeter;
    use registry::{Registry, StdRegistry};

    #[test]
    fn meter() {
        let mut r: StdRegistry = StdRegistry::new();
        let mut m: StdMeter = StdMeter::new();

        r.insert("foo", m);
        r.get("foo");
    }
}
<commit_msg>quiet warnings<commit_after>use std::collections::HashMap;

use metric::Metric;

pub trait Registry<'a> {
    fn get(&'a self, name: &'a str) -> &'a Metric;

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T);
}

pub struct StdRegistry<'a> {
    metrics: HashMap<&'a str, Box<Metric + 'a>>,
}

// Specific stuff for registry goes here
impl<'a> Registry<'a> for StdRegistry<'a> {
    fn get(&'a self, name: &'a str) -> &'a Metric {
        &*self.metrics[name]
    }

    fn insert<T: Metric + 'a>(&mut self, name: &'a str, metric: T) {
        let boxed = Box::new(metric);

        self.metrics.insert(name, boxed);
    }
}

// General StdRegistry
impl<'a> StdRegistry<'a> {
    #[allow(dead_code)]
    fn new() -> StdRegistry<'a> {
        StdRegistry{
            metrics: HashMap::new()
        }
    }
}

#[cfg(test)]
mod test {
    use meter::StdMeter;
    use registry::{Registry, StdRegistry};

    #[test]
    fn meter() {
        let mut r: StdRegistry = StdRegistry::new();
        let m: StdMeter = StdMeter::new();

        r.insert("foo", m);
        r.get("foo");
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove double prompting for password of new user.<commit_after><|endoftext|>


<commit_before>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;
// use std::thread;

fn main() {
	let mut provider = DefaultAWSCredentialsProviderChain::new();

	// println!("Creds in main: {}, {}, {}.", creds.get_aws_secret_key(), creds.get_aws_secret_key(),
	// 	creds.get_token());

	match sqs_roundtrip_tests(&provider.get_credentials()) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	let bucket_name = format!("rusoto{}", get_time().sec);

	match s3_list_buckets_tests(&provider.get_credentials()) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	match s3_create_bucket_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			f.write(&(result.body));
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_delete_bucket_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_buckets_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.list_buckets());
	// println!("response is {:?}", response);
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(creds: &AWSCredentials, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.get_object(bucket, "sample-credentials"));
	// println!("get object response is {:?}", response);
	Ok(response)
}

fn s3_delete_object_test(creds: &AWSCredentials, bucket: &str) -> Result<DeleteObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.delete_object(bucket, "sample-credentials"));
	// println!("delete object response is {:?}", response);
	Ok(response)
}

fn s3_put_object_test(creds: &AWSCredentials, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	f.read_to_end(&mut contents);

	let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
	// println!("put object response is {:?}", response);
	Ok(response)
}

fn s3_create_bucket_test(creds: &AWSCredentials, bucket: &str) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.create_bucket_in_region(bucket, "us-east-1"));

	// println!("Create bucket response is {:?}", response);
	Ok(())
}

fn s3_delete_bucket_test(creds: &AWSCredentials, bucket: &str) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.delete_bucket(bucket));
	// println!("Delete bucket response is {:?}", response);
	Ok(())
}

fn sqs_roundtrip_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	let sqs = SQSHelper::new(&creds, "us-east-1");

	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<commit_msg>Refactors main to not have compiler warnings.<commit_after>#![allow(dead_code)]
extern crate rusoto;
extern crate xml;
extern crate time;
extern crate regex;
extern crate rustc_serialize;
use rusoto::credentials::*;
use rusoto::error::*;
use rusoto::sqs::*;
use rusoto::s3::*;
use time::*;
use std::fs::File;
use std::io::Write;
use std::io::Read;
// use std::thread;

fn main() {
	let mut provider = DefaultAWSCredentialsProviderChain::new();

	// println!("Creds in main: {}, {}, {}.", creds.get_aws_secret_key(), creds.get_aws_secret_key(),
	// 	creds.get_token());

	match sqs_roundtrip_tests(&provider.get_credentials()) {
		Ok(_) => { println!("Everything worked."); },
		Err(err) => { println!("Got error: {:#?}", err); }
	}

	let bucket_name = format!("rusoto{}", get_time().sec);

	match s3_list_buckets_tests(&provider.get_credentials()) {
		Ok(_) => { println!("Everything worked for S3 list buckets."); },
		Err(err) => { println!("Got error in s3 list buckets: {:#?}", err); }
	}

	match s3_create_bucket_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => { println!("Everything worked for S3 create bucket."); },
		Err(err) => { println!("Got error in s3 create bucket: {:#?}", err); }
	}

	match s3_put_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 put object.");
		}
		Err(err) => { println!("Got error in s3 put object: {:#?}", err); }
	}

	match s3_get_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(result) => {
			println!("Everything worked for S3 get object.");
			let mut f = File::create("s3-sample-creds").unwrap();
			match f.write(&(result.body)) {
				Err(why) => println!("Couldn't create file to save object from S3: {}", why),
				Ok(_) => return,
			}
		}
		Err(err) => { println!("Got error in s3 get object: {:#?}", err); }
	}

	match s3_delete_object_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => {
			println!("Everything worked for S3 delete object.");
		}
		Err(err) => { println!("Got error in s3 delete object: {:#?}", err); }
	}

	match s3_delete_bucket_test(&provider.get_credentials(), &bucket_name) {
		Ok(_) => { println!("Everything worked for S3 delete bucket."); },
		Err(err) => { println!("Got error in s3 delete bucket: {:#?}", err); }
	}
}

fn s3_list_buckets_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.list_buckets());
	// println!("response is {:?}", response);
	for q in response.buckets {
		println!("Existing bucket: {:?}", q.name);
	}

	Ok(())
}

fn s3_get_object_test(creds: &AWSCredentials, bucket: &str) -> Result<GetObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.get_object(bucket, "sample-credentials"));
	// println!("get object response is {:?}", response);
	Ok(response)
}

fn s3_delete_object_test(creds: &AWSCredentials, bucket: &str) -> Result<DeleteObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let response = try!(s3.delete_object(bucket, "sample-credentials"));
	// println!("delete object response is {:?}", response);
	Ok(response)
}

fn s3_put_object_test(creds: &AWSCredentials, bucket: &str) -> Result<PutObjectOutput, AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	let mut f = File::open("src/sample-credentials").unwrap();
	let mut contents = Vec::new();
	match f.read_to_end(&mut contents) {
		Err(why) => return Err(AWSError::new(format!("Error opening file to send to S3: {}", why))),
		Ok(_) => {
			let response = try!(s3.put_object(bucket, "sample-credentials", &contents));
			Ok(response)
		}
	}
}

fn s3_create_bucket_test(creds: &AWSCredentials, bucket: &str) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	try!(s3.create_bucket_in_region(bucket, "us-east-1"));

	Ok(())
}

fn s3_delete_bucket_test(creds: &AWSCredentials, bucket: &str) -> Result<(), AWSError> {
	let s3 = S3Helper::new(&creds, "us-east-1");

	try!(s3.delete_bucket(bucket));
	Ok(())
}

fn sqs_roundtrip_tests(creds: &AWSCredentials) -> Result<(), AWSError> {
	let sqs = SQSHelper::new(&creds, "us-east-1");

	// list existing queues
	let response = try!(sqs.list_queues());
	for q in response.queue_urls {
		println!("Existing queue: {}", q);
	}

	// create a new queue
	let q_name = &format!("test_q_{}", get_time().sec);
	let response = try!(sqs.create_queue(q_name));
	println!("Created queue {} with url {}", q_name, response.queue_url);

	// query it by name
	let response = try!(sqs.get_queue_url(q_name));
	let queue_url = &response.queue_url;
	println!("Verified queue url {} for queue name {}", queue_url, q_name);

	// send it a message
	let msg_str = "lorem ipsum dolor sit amet";
	let response = try!(sqs.send_message(queue_url, msg_str));
	println!("Send message with body '{}' and created message_id {}", msg_str, response.message_id);

	// receive a message
	let response = try!(sqs.receive_message(queue_url));
	for msg in response.messages {
		println!("Received message '{}' with id {}", msg.body, msg.message_id);
		try!(sqs.delete_message(queue_url, &msg.receipt_handle));
	}

	// delete the queue
	try!(sqs.delete_queue(queue_url));
	println!("Queue {} deleted", queue_url);

	Ok(())
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test case for derived-tydescs-before-dynamic-allocas<commit_after>// xfail-stage0

tag option[T] {
    some(T);
    none;
}

type r[T] = rec(mutable (option[T])[] v);

fn f[T]() -> T[] {
    ret ~[];
}

fn main() {
    let r[int] r = rec(mutable v=~[]);
    r.v = f();
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #25287 - jdm:google-load, r=pcwalton<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed Indentation.<commit_after><|endoftext|>


<commit_before>// 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.

//! An experimental pass that scources for `#[rustc_mir]` attributes,
//! builds the resulting MIR, and dumps it out into a file for inspection.
//!
//! The attribute formats that are currently accepted are:
//!
//! - `#[rustc_mir(graphviz="file.gv")]`
//! - `#[rustc_mir(pretty="file.mir")]`

extern crate syntax;

use build;
use rustc::dep_graph::DepNode;
use rustc::mir::repr::Mir;
use pretty;
use hair::cx::Cx;

use rustc::mir::mir_map::MirMap;
use rustc::infer;
use rustc::traits::ProjectionMode;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc::util::nodemap::NodeMap;
use rustc::hir;
use rustc::hir::intravisit::{self, Visitor};
use syntax::abi::Abi;
use syntax::ast;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;

pub fn build_mir_for_crate<'tcx>(tcx: &TyCtxt<'tcx>) -> MirMap<'tcx> {
    let mut map = MirMap {
        map: NodeMap(),
    };
    {
        let mut dump = OuterDump {
            tcx: tcx,
            map: &mut map,
        };
        tcx.visit_all_items_in_krate(DepNode::MirMapConstruction, &mut dump);
    }
    map
}

///////////////////////////////////////////////////////////////////////////
// OuterDump -- walks a crate, looking for fn items and methods to build MIR from

struct OuterDump<'a, 'tcx: 'a> {
    tcx: &'a TyCtxt<'tcx>,
    map: &'a mut MirMap<'tcx>,
}

impl<'a, 'tcx> OuterDump<'a, 'tcx> {
    fn visit_mir<OP>(&mut self, attributes: &'a [ast::Attribute], mut walk_op: OP)
        where OP: for<'m> FnMut(&mut InnerDump<'a, 'm, 'tcx>)
    {
        let mut closure_dump = InnerDump {
            tcx: self.tcx,
            attr: None,
            map: &mut *self.map,
        };
        for attr in attributes {
            if attr.check_name("rustc_mir") {
                closure_dump.attr = Some(attr);
            }
        }
        walk_op(&mut closure_dump);
    }
}

impl<'a, 'tcx> Visitor<'tcx> for OuterDump<'a, 'tcx> {
    fn visit_item(&mut self, item: &'tcx hir::Item) {
        self.visit_mir(&item.attrs, |c| intravisit::walk_item(c, item));
        intravisit::walk_item(self, item);
    }

    fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
        match trait_item.node {
            hir::MethodTraitItem(_, Some(_)) => {
                self.visit_mir(&trait_item.attrs, |c| intravisit::walk_trait_item(c, trait_item));
            }
            hir::MethodTraitItem(_, None) |
            hir::ConstTraitItem(..) |
            hir::TypeTraitItem(..) => {}
        }
        intravisit::walk_trait_item(self, trait_item);
    }

    fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
        match impl_item.node {
            hir::ImplItemKind::Method(..) => {
                self.visit_mir(&impl_item.attrs, |c| intravisit::walk_impl_item(c, impl_item));
            }
            hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(..) => {}
        }
        intravisit::walk_impl_item(self, impl_item);
    }
}

///////////////////////////////////////////////////////////////////////////
// InnerDump -- dumps MIR for a single fn and its contained closures

struct InnerDump<'a, 'm, 'tcx: 'a + 'm> {
    tcx: &'a TyCtxt<'tcx>,
    map: &'m mut MirMap<'tcx>,
    attr: Option<&'a ast::Attribute>,
}

impl<'a, 'm, 'tcx> Visitor<'tcx> for InnerDump<'a,'m,'tcx> {
    fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) {
        // ignore methods; the outer dump will call us for them independently
    }

    fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) {
        // ignore methods; the outer dump will call us for them independently
    }

    fn visit_fn(&mut self,
                fk: intravisit::FnKind<'tcx>,
                decl: &'tcx hir::FnDecl,
                body: &'tcx hir::Block,
                span: Span,
                id: ast::NodeId) {
        let implicit_arg_tys = if let intravisit::FnKind::Closure(..) = fk {
            vec![closure_self_ty(&self.tcx, id, body.id)]
        } else {
            vec![]
        };

        let param_env = ty::ParameterEnvironment::for_item(self.tcx, id);
        let infcx = infer::new_infer_ctxt(self.tcx,
                                          &self.tcx.tables,
                                          Some(param_env),
                                          ProjectionMode::AnyFinal);

        match build_mir(Cx::new(&infcx), implicit_arg_tys, id, span, decl, body) {
            Ok(mir) => assert!(self.map.map.insert(id, mir).is_none()),
            Err(ErrorReported) => {}
        }

        intravisit::walk_fn(self, fk, decl, body, span);
    }
}

fn build_mir<'a,'tcx:'a>(cx: Cx<'a,'tcx>,
                         implicit_arg_tys: Vec<Ty<'tcx>>,
                         fn_id: ast::NodeId,
                         span: Span,
                         decl: &'tcx hir::FnDecl,
                         body: &'tcx hir::Block)
                         -> Result<Mir<'tcx>, ErrorReported> {
    // fetch the fully liberated fn signature (that is, all bound
    // types/lifetimes replaced)
    let fn_sig = match cx.tcx().tables.borrow().liberated_fn_sigs.get(&fn_id) {
        Some(f) => f.clone(),
        None => {
            span_bug!(span, "no liberated fn sig for {:?}", fn_id);
        }
    };

    let arguments =
        decl.inputs
            .iter()
            .enumerate()
            .map(|(index, arg)| {
                (fn_sig.inputs[index], &*arg.pat)
            })
            .collect();

    let (mut mir, scope_auxiliary) =
        build::construct(cx,
                         span,
                         fn_id,
                         body.id,
                         implicit_arg_tys,
                         arguments,
                         fn_sig.output,
                         body);

    match cx.tcx().node_id_to_type(fn_id).sty {
        ty::TyFnDef(_, _, f) if f.abi == Abi::RustCall => {
            // RustCall pseudo-ABI untuples the last argument.
            if let Some(arg_decl) = mir.arg_decls.last_mut() {
                arg_decl.spread = true;
            }
        }
        _ => {}
    }

    pretty::dump_mir(cx.tcx(),
                     "mir_map",
                     &0,
                     fn_id,
                     &mir,
                     Some(&scope_auxiliary));

    Ok(mir)
}

fn closure_self_ty<'a, 'tcx>(tcx: &TyCtxt<'tcx>,
                             closure_expr_id: ast::NodeId,
                             body_id: ast::NodeId)
                             -> Ty<'tcx> {
    let closure_ty = tcx.node_id_to_type(closure_expr_id);

    // We're just hard-coding the idea that the signature will be
    // &self or &mut self and hence will have a bound region with
    // number 0, hokey.
    let region = ty::Region::ReFree(ty::FreeRegion {
        scope: tcx.region_maps.item_extent(body_id),
        bound_region: ty::BoundRegion::BrAnon(0),
    });
    let region = tcx.mk_region(region);

    match tcx.closure_kind(tcx.map.local_def_id(closure_expr_id)) {
        ty::ClosureKind::Fn =>
            tcx.mk_ref(region,
                       ty::TypeAndMut { ty: closure_ty,
                                        mutbl: hir::MutImmutable }),
        ty::ClosureKind::FnMut =>
            tcx.mk_ref(region,
                       ty::TypeAndMut { ty: closure_ty,
                                        mutbl: hir::MutMutable }),
        ty::ClosureKind::FnOnce =>
            closure_ty
    }
}
<commit_msg>mir: remove the unused attribute logic in the MIR map construction.<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.

//! An experimental pass that scources for `#[rustc_mir]` attributes,
//! builds the resulting MIR, and dumps it out into a file for inspection.
//!
//! The attribute formats that are currently accepted are:
//!
//! - `#[rustc_mir(graphviz="file.gv")]`
//! - `#[rustc_mir(pretty="file.mir")]`

extern crate syntax;

use build;
use rustc::dep_graph::DepNode;
use rustc::mir::repr::Mir;
use pretty;
use hair::cx::Cx;

use rustc::mir::mir_map::MirMap;
use rustc::infer;
use rustc::traits::ProjectionMode;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc::util::nodemap::NodeMap;
use rustc::hir;
use rustc::hir::intravisit::{self, Visitor};
use syntax::abi::Abi;
use syntax::ast;
use syntax::codemap::Span;

pub fn build_mir_for_crate<'tcx>(tcx: &TyCtxt<'tcx>) -> MirMap<'tcx> {
    let mut map = MirMap {
        map: NodeMap(),
    };
    {
        let mut dump = BuildMir {
            tcx: tcx,
            map: &mut map,
        };
        tcx.visit_all_items_in_krate(DepNode::MirMapConstruction, &mut dump);
    }
    map
}

///////////////////////////////////////////////////////////////////////////
// BuildMir -- walks a crate, looking for fn items and methods to build MIR from

struct BuildMir<'a, 'tcx: 'a> {
    tcx: &'a TyCtxt<'tcx>,
    map: &'a mut MirMap<'tcx>,
}

impl<'a, 'tcx> Visitor<'tcx> for BuildMir<'a, 'tcx> {
    fn visit_fn(&mut self,
                fk: intravisit::FnKind<'tcx>,
                decl: &'tcx hir::FnDecl,
                body: &'tcx hir::Block,
                span: Span,
                id: ast::NodeId) {
        let implicit_arg_tys = if let intravisit::FnKind::Closure(..) = fk {
            vec![closure_self_ty(&self.tcx, id, body.id)]
        } else {
            vec![]
        };

        let param_env = ty::ParameterEnvironment::for_item(self.tcx, id);
        let infcx = infer::new_infer_ctxt(self.tcx,
                                          &self.tcx.tables,
                                          Some(param_env),
                                          ProjectionMode::AnyFinal);

        match build_mir(Cx::new(&infcx), implicit_arg_tys, id, span, decl, body) {
            Ok(mir) => assert!(self.map.map.insert(id, mir).is_none()),
            Err(ErrorReported) => {}
        }

        intravisit::walk_fn(self, fk, decl, body, span);
    }
}

fn build_mir<'a,'tcx:'a>(cx: Cx<'a,'tcx>,
                         implicit_arg_tys: Vec<Ty<'tcx>>,
                         fn_id: ast::NodeId,
                         span: Span,
                         decl: &'tcx hir::FnDecl,
                         body: &'tcx hir::Block)
                         -> Result<Mir<'tcx>, ErrorReported> {
    // fetch the fully liberated fn signature (that is, all bound
    // types/lifetimes replaced)
    let fn_sig = match cx.tcx().tables.borrow().liberated_fn_sigs.get(&fn_id) {
        Some(f) => f.clone(),
        None => {
            span_bug!(span, "no liberated fn sig for {:?}", fn_id);
        }
    };

    let arguments =
        decl.inputs
            .iter()
            .enumerate()
            .map(|(index, arg)| {
                (fn_sig.inputs[index], &*arg.pat)
            })
            .collect();

    let (mut mir, scope_auxiliary) =
        build::construct(cx,
                         span,
                         fn_id,
                         body.id,
                         implicit_arg_tys,
                         arguments,
                         fn_sig.output,
                         body);

    match cx.tcx().node_id_to_type(fn_id).sty {
        ty::TyFnDef(_, _, f) if f.abi == Abi::RustCall => {
            // RustCall pseudo-ABI untuples the last argument.
            if let Some(arg_decl) = mir.arg_decls.last_mut() {
                arg_decl.spread = true;
            }
        }
        _ => {}
    }

    pretty::dump_mir(cx.tcx(),
                     "mir_map",
                     &0,
                     fn_id,
                     &mir,
                     Some(&scope_auxiliary));

    Ok(mir)
}

fn closure_self_ty<'a, 'tcx>(tcx: &TyCtxt<'tcx>,
                             closure_expr_id: ast::NodeId,
                             body_id: ast::NodeId)
                             -> Ty<'tcx> {
    let closure_ty = tcx.node_id_to_type(closure_expr_id);

    // We're just hard-coding the idea that the signature will be
    // &self or &mut self and hence will have a bound region with
    // number 0, hokey.
    let region = ty::Region::ReFree(ty::FreeRegion {
        scope: tcx.region_maps.item_extent(body_id),
        bound_region: ty::BoundRegion::BrAnon(0),
    });
    let region = tcx.mk_region(region);

    match tcx.closure_kind(tcx.map.local_def_id(closure_expr_id)) {
        ty::ClosureKind::Fn =>
            tcx.mk_ref(region,
                       ty::TypeAndMut { ty: closure_ty,
                                        mutbl: hir::MutImmutable }),
        ty::ClosureKind::FnMut =>
            tcx.mk_ref(region,
                       ty::TypeAndMut { ty: closure_ty,
                                        mutbl: hir::MutMutable }),
        ty::ClosureKind::FnOnce =>
            closure_ty
    }
}
<|endoftext|>


<commit_before>// 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.

use syntax::ast;
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::symbol::Symbol;
use syntax_pos;
use syntax::tokenstream;
use syntax::print::pprust;

use std::string::String;

pub fn expand_syntax_ext(cx: &mut base::ExtCtxt,
                         sp: syntax_pos::Span,
                         tts: &[tokenstream::TokenTree])
                         -> Box<base::MacResult + 'static> {
    let es = match base::get_exprs_from_tts(cx, sp, tts) {
        Some(e) => e,
        None => return base::DummyResult::expr(sp),
    };
    let mut accumulator = String::new();
    for e in es {
        match e.node {
            ast::ExprKind::Lit(ref lit) => {
                match lit.node {
                    ast::LitKind::Str(ref s, _) |
                    ast::LitKind::Float(ref s, _) |
                    ast::LitKind::FloatUnsuffixed(ref s) => {
                        accumulator.push_str(&s.as_str());
                    }
                    ast::LitKind::Char(c) => {
                        accumulator.push(c);
                    }
                    ast::LitKind::Int(i, ast::LitIntType::Unsigned(_)) |
                    ast::LitKind::Int(i, ast::LitIntType::Signed(_)) |
                    ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
                        accumulator.push_str(&format!("{}", i));
                    }
                    ast::LitKind::Bool(b) => {
                        accumulator.push_str(&format!("{}", b));
                    }
                    ast::LitKind::Byte(..) |
                    ast::LitKind::ByteStr(..) => {
                        cx.span_err(e.span, "cannot concatenate a byte string literal");
                    }
                }
            }
            _ => {
                let mut err = cx.struct_span_err(e.span, "expected a literal");
                err.span_suggestion(
                    e.span,
                    "consider changing this to",
                    format!("\"{{}}\", {}", pprust::expr_to_string(&e))
                );
                err.emit();
            }
        }
    }
    let sp = sp.apply_mark(cx.current_expansion.mark);
    base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&accumulator)))
}
<commit_msg>add span note<commit_after>// 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.

use syntax::ast;
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::symbol::Symbol;
use syntax_pos;
use syntax::tokenstream;
use syntax::print::pprust;

use std::string::String;

pub fn expand_syntax_ext(cx: &mut base::ExtCtxt,
                         sp: syntax_pos::Span,
                         tts: &[tokenstream::TokenTree])
                         -> Box<base::MacResult + 'static> {
    let es = match base::get_exprs_from_tts(cx, sp, tts) {
        Some(e) => e,
        None => return base::DummyResult::expr(sp),
    };
    let mut accumulator = String::new();
    for e in es {
        match e.node {
            ast::ExprKind::Lit(ref lit) => {
                match lit.node {
                    ast::LitKind::Str(ref s, _) |
                    ast::LitKind::Float(ref s, _) |
                    ast::LitKind::FloatUnsuffixed(ref s) => {
                        accumulator.push_str(&s.as_str());
                    }
                    ast::LitKind::Char(c) => {
                        accumulator.push(c);
                    }
                    ast::LitKind::Int(i, ast::LitIntType::Unsigned(_)) |
                    ast::LitKind::Int(i, ast::LitIntType::Signed(_)) |
                    ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
                        accumulator.push_str(&format!("{}", i));
                    }
                    ast::LitKind::Bool(b) => {
                        accumulator.push_str(&format!("{}", b));
                    }
                    ast::LitKind::Byte(..) |
                    ast::LitKind::ByteStr(..) => {
                        cx.span_err(e.span, "cannot concatenate a byte string literal");
                    }
                }
            }
            _ => {
                let mut err = cx.struct_span_err(e.span, "expected a literal");
                let msg = cx.codemap().span_to_snippet(e.span).unwrap_or_else(
                    |_| pprust::expr_to_string(&e)
                );
                err.span_suggestion(
                    e.span,
                    "consider changing this to",
                    format!("\"{{}}\", {}", msg)
                );
                err.span_note(
                    e.span,
                    "you might be missing a string literal to format with",
                );
                err.emit();
            }
        }
    }
    let sp = sp.apply_mark(cx.current_expansion.mark);
    base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&accumulator)))
}
<|endoftext|>


<commit_before><commit_msg>Rename the tar writer thing.<commit_after><|endoftext|>


<commit_before><commit_msg>Added unix platform.<commit_after>/// Write a string to the output channel.
pub unsafe fn puts(s: &str) {
    print!("{}", s);
}
<|endoftext|>


<commit_before><commit_msg>Add unicode tests to all images docker-exec/dexec#27<commit_after>fn main() {
    println!("hello unicode 👾");
}
<|endoftext|>


<commit_before><commit_msg>rust primitives<commit_after>use std::fmt::{Display, Formatter, Result};
use std::mem;

#[allow(dead_code,unused_variables,unused_mut)]
fn main() {
    let an_integer0 = 5i8;
    let an_integer1 = 5i16;
    let an_integer2 = 5i32;
    let an_integer3 = 5i64;
    let unsigned_integer0 = 5u8;
    let unsigned_integer1 = 5u16;
    let unsigned_integer2 = 5u32;
    let unsigned_integer3 = 5u64;
    let a_float0: f32 = 1.0;
    let a_float1: f64 = 1.0;
    let char0: char = 'a';
    let char1 = 'α';
    let char2 = '∞'; // 4 bytes
    let default_float = 3.0; // f64
    let default_integer = 7; // i32
    let mut mutable = 12; // mutable i32
    // mutable = true; // type of variable can't be changed
    let logical: bool = true;
    let unit: () = ();
    let array = [1, 2, 3];
    let tuple = (1, true);

    // 2.1
    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
    println!("1 << 5 is {}", 1u32 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x82u32 >> 2);
    println!("One million: {}", 1_000_000u32);

    // 2.2
    fn reverse(pair: (i32, bool)) -> (bool, i32) {
        let (i, b) = pair;
        (b, i)
    }
    #[derive(Debug)]
    struct Matrix(f32, f32, f32, f32);
    let tuple_of_tuples = ((1u8, 2u16, 3u32), (4u64, -1i8), -2i16);
    println!("tuple of tuples {:?}", tuple_of_tuples);
    println!("tuple 1: {:?}", tuple_of_tuples.0);

    let tuple = (1, "hello", 4.5, true);
    let (a,b,c,d) = tuple;
    println!("{:?} {:?} {:?} {:?}", a, b, c, d);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("{:?}", matrix);
    impl Display for Matrix {
        fn fmt(&self, f: &mut  Formatter) -> Result {
            write!(f, "( {} {} )\n( {} {} )", self.0, self.1, self.2, self.3)
        }
    }
    println!("{}", matrix);

    fn transpose(m: Matrix) -> Matrix {
        return Matrix(m.0, m.2, m.1, m.3);
    }
    println!("Transpose:\n{}", transpose(matrix));

    // 2.3
    let xs: [i32; 5] = [1,2,3,4,5];
    let ys: [i32; 500] = [0; 500]; // init all elements to 0
    println!("first element of the array: {}", xs[1]);
    println!("second element of the array: {}", xs[2]);
    //println!("array out of bound: {}", xs[5]);
    println!("array size: {}", xs.len());
    println!("array occupies {} bytes", mem::size_of_val(&xs));
    fn analyze_slice(slice: &[i32]) {
        println!("slice[0]: {}, size: {}", slice[0], slice.len());
    }
    analyze_slice(&xs);
    analyze_slice(&ys[1..4]);
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #66756<commit_after>// Test for <https://github.com/rust-lang/rust/issues/66756>

// check-pass

#![feature(const_if_match)]

enum E {
    A,
    B,
    C
}

const fn f(e: E) {
    match e {
        E::A => {}
        E::B => {}
        E::C => {}
    }
}

const fn g(e: E) {
    match e {
        _ => {}
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Added network module.<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot a file.<commit_after>use session::Session;
use subscription::Subscription;
use frame::Frame;
use option_setter::OptionSetter;
use std::old_io::IoResult;

pub struct SubscriptionBuilder <'a> {
  pub session: &'a mut Session<'a>,
  pub frame: Frame,
  pub subscription: Subscription<'a>
}

impl <'a> SubscriptionBuilder <'a> {
  pub fn new(session: &'a mut Session<'a>, frame: Frame, sub: Subscription<'a>) -> SubscriptionBuilder <'a> {
   SubscriptionBuilder {
      session: session,
      frame: frame,
      subscription: sub
    }
  }

  #[allow(dead_code)]
  pub fn create(mut self) -> IoResult<String> {
    try!(self.session.send(self.frame));
    debug!("Registering callback for subscription id '{}' from builder", self.subscription.id);
    let id_to_return = self.subscription.id.to_string();
    self.session.subscriptions.insert(self.subscription.id.to_string(), self.subscription);
    Ok(id_to_return)
  }

  #[allow(dead_code)]
  pub fn with<T>(self, option_setter: T) -> SubscriptionBuilder<'a> where T: OptionSetter<SubscriptionBuilder<'a>> {
    option_setter.set_option(self)
  }
}

<|endoftext|>


<commit_before>/* MT19937 Mersenne Twister RNG
 *
 * Official Mersenne Twister page:
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
 *
 * Dmitry Vasiliev <dima@hlabs.org>
 */

extern crate test;

use std::cmp::max;

static N: uint = 624;
static M: uint = 397;

struct MersenneTwister {
    state: Vec<u32>,
    index: uint
}

impl MersenneTwister {
    fn new(init_key: &[u32]) -> MersenneTwister {
        MersenneTwister{state: init_by_vec(init_key), index: N}
    }

    fn rand_u32(&mut self) -> u32 {
        if self.index >= N {
            self.init();
        }
        let mut y = self.state[self.index];
        self.index += 1;
        y ^= y >> 11;
        y ^= (y << 7) & 0x9d2c5680;
        y ^= (y << 15) & 0xefc60000;
        y ^ (y >> 18)
    }

    fn rand_f64(&mut self) -> f64 {
        self.rand_u32() as f64 / 4294967296.0
    }

    #[inline]
    fn init(&mut self) {
        for i in range(0, N) {
            let y = (self.state[i] & 0x80000000)
                    | (self.state[(i + 1) % N] & 0x7fffffff);
            self.state[i] = self.state[(i + M) % N] ^ (y >> 1);
            if y % 2 != 0 {
                self.state[i] ^= 0x9908b0df;
            }
        }
        self.index = 0;
    }
}

#[inline]
fn init_state(seed: u32) -> Vec<u32> {
    range(0, N as u32).scan(seed, |state, i| {
        let prev = *state;
        *state = 1812433253 * (*state ^ (*state >> 30)) + i + 1;
        Some(prev)
    }).collect()
}

#[inline]
fn init_by_vec(init_key: &[u32]) -> Vec<u32> {
    let mut state = init_state(19650218);
    let len = init_key.len();
    for i in range(0, max(N, len)) {
        state[i % (N - 1) + 1] = (state[i % (N - 1) + 1]
            ^ ((state[i % (N - 1)] ^ (state[i % (N - 1)] >> 30)) * 1664525))
            + init_key[i % len] + (i % len) as u32;
        if (i + 1) % (N - 1) == 0 {
            state[0] = state[N - 1];
        }
    }

    for i in range(1, N) {
        state[i % (N - 1) + 1] = (state[i % (N - 1) + 1]
            ^ ((state[i % (N - 1)] ^ (state[i % (N - 1)] >> 30)) * 1566083941))
            - (i % (N - 1) + 1) as u32;
        if (i + 1) % (N - 1) == 0 {
            state[0] = state[N - 1];
        }
    }

    state[0] = 0x80000000;
    state
}

/*
 * Main entry point
 */
#[cfg(not(test))]
fn main() {
    let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
    for i in range(0u, 1000) {
        match i % 5 == 4 {
            false => print!("{:>10} ", rng.rand_u32()),
            true => println!("{:>10}", rng.rand_u32())
        }
    }
    println!("");
    for i in range(0u, 1000) {
        match i % 5 == 4 {
            false => print!("{:>10.8} ", rng.rand_f64()),
            true => println!("{:>10.8}", rng.rand_f64())
        }
    }
}

/*
 * Tests
 *
 * Link to the test data:
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.out
 */
#[cfg(test)]
mod tests {
    use test::Bencher;

    use super::MersenneTwister;

    #[test]
    fn test_rand_u32() {
        let expected: [u32, ..50] = [
            1067595299, 955945823, 477289528, 4107218783, 4228976476,
            3344332714, 3355579695, 227628506, 810200273, 2591290167,
            2560260675, 3242736208, 646746669, 1479517882, 4245472273,
            1143372638, 3863670494, 3221021970, 1773610557, 1138697238,
            1421897700, 1269916527, 2859934041, 1764463362, 3874892047,
            3965319921, 72549643, 2383988930, 2600218693, 3237492380,
            2792901476, 725331109, 605841842, 271258942, 715137098,
            3297999536, 1322965544, 4229579109, 1395091102, 3735697720,
            2101727825, 3730287744, 2950434330, 1661921839, 2895579582,
            2370511479, 1004092106, 2247096681, 2111242379, 3237345263,
        ];
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        for (i, &exp) in expected.iter().enumerate() {
            assert_eq!((i, exp), (i, rng.rand_u32()));
        }
    }

    #[test]
    fn test_rand_f64() {
        let expected: [f64, ..50] = [
            0.76275443, 0.99000644, 0.98670464, 0.10143112, 0.27933125,
            0.69867227, 0.94218740, 0.03427201, 0.78842173, 0.28180608,
            0.92179002, 0.20785655, 0.54534773, 0.69644020, 0.38107718,
            0.23978165, 0.65286910, 0.07514568, 0.22765211, 0.94872929,
            0.74557914, 0.62664415, 0.54708246, 0.90959343, 0.42043116,
            0.86334511, 0.19189126, 0.14718544, 0.70259889, 0.63426346,
            0.77408121, 0.04531601, 0.04605807, 0.88595519, 0.69398270,
            0.05377184, 0.61711170, 0.05565708, 0.10133577, 0.41500776,
            0.91810699, 0.22320679, 0.23353705, 0.92871862, 0.98897234,
            0.19786706, 0.80558809, 0.06961067, 0.55840445, 0.90479405,
        ];
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        // For the test data we use 1000 values should be skipped
        for _ in range(0u, 1000) {
            rng.rand_f64();
        }
        for (i, &exp) in expected.iter().enumerate() {
            assert_eq!((i, true), (i, rng.rand_f64() - exp < 0.00000001f64));
        }
    }

    #[bench]
    fn bench_rand_u32(b: &mut Bencher) {
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        b.iter(|| rng.rand_u32());
    }
}
<commit_msg>Slightly better code for 3/21<commit_after>/* MT19937 Mersenne Twister RNG
 *
 * Official Mersenne Twister page:
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
 *
 * Dmitry Vasiliev <dima@hlabs.org>
 */

extern crate test;

use std::cmp::max;

static N: uint = 624;
static M: uint = 397;

struct MersenneTwister {
    state: Vec<u32>,
    index: uint
}

impl MersenneTwister {
    fn new(init_key: &[u32]) -> MersenneTwister {
        MersenneTwister{state: init_by_vec(init_key), index: N}
    }

    fn rand_u32(&mut self) -> u32 {
        if self.index >= N {
            self.init();
        }
        let mut y = self.state[self.index];
        self.index += 1;
        y ^= y >> 11;
        y ^= (y << 7) & 0x9d2c5680;
        y ^= (y << 15) & 0xefc60000;
        y ^ (y >> 18)
    }

    fn rand_f64(&mut self) -> f64 {
        self.rand_u32() as f64 / 4294967296.0
    }

    #[inline]
    fn init(&mut self) {
        for i in range(0, N) {
            let y = (self.state[i] & 0x80000000)
                    | (self.state[(i + 1) % N] & 0x7fffffff);
            self.state[i] = match y % 2 {
                0 => self.state[(i + M) % N] ^ (y >> 1),
                _ => self.state[(i + M) % N] ^ (y >> 1) ^ 0x9908b0df
            }
        }
        self.index = 0;
    }
}

#[inline]
fn init_state(seed: u32) -> Vec<u32> {
    range(0, N as u32).scan(seed, |state, i| {
        let prev = *state;
        *state = 1812433253 * (*state ^ (*state >> 30)) + i + 1;
        Some(prev)
    }).collect()
}

#[inline]
fn init_by_vec(init_key: &[u32]) -> Vec<u32> {
    let mut state = init_state(19650218);
    let len = init_key.len();
    let limit = N - 1;
    for i in range(0, max(N, len)) {
        let idx = i % limit;
        state[idx + 1] = (state[idx + 1]
            ^ ((state[idx] ^ (state[idx] >> 30)) * 1664525))
            + init_key[i % len] + (i % len) as u32;
        if (i + 1) % limit == 0 {
            state[0] = state[limit];
        }
    }

    for i in range(2, N) {
        state[i] = (state[i]
            ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941)) - i as u32;
    }

    state[1] = (state[1]
        ^ ((state[N - 1] ^ (state[N - 1] >> 30)) * 1566083941)) - 1;
    state[0] = 0x80000000;
    state
}

/*
 * Main entry point
 */
#[cfg(not(test))]
fn main() {
    let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
    for i in range(0u, 1000) {
        match i % 5 == 4 {
            false => print!("{:>10} ", rng.rand_u32()),
            true => println!("{:>10}", rng.rand_u32())
        }
    }
    println!("");
    for i in range(0u, 1000) {
        match i % 5 == 4 {
            false => print!("{:>10.8} ", rng.rand_f64()),
            true => println!("{:>10.8}", rng.rand_f64())
        }
    }
}

/*
 * Tests
 *
 * Link to the test data:
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.out
 */
#[cfg(test)]
mod tests {
    use test::Bencher;

    use super::MersenneTwister;

    #[test]
    fn test_rand_u32() {
        let expected: [u32, ..50] = [
            1067595299, 955945823, 477289528, 4107218783, 4228976476,
            3344332714, 3355579695, 227628506, 810200273, 2591290167,
            2560260675, 3242736208, 646746669, 1479517882, 4245472273,
            1143372638, 3863670494, 3221021970, 1773610557, 1138697238,
            1421897700, 1269916527, 2859934041, 1764463362, 3874892047,
            3965319921, 72549643, 2383988930, 2600218693, 3237492380,
            2792901476, 725331109, 605841842, 271258942, 715137098,
            3297999536, 1322965544, 4229579109, 1395091102, 3735697720,
            2101727825, 3730287744, 2950434330, 1661921839, 2895579582,
            2370511479, 1004092106, 2247096681, 2111242379, 3237345263,
        ];
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        for (i, &exp) in expected.iter().enumerate() {
            assert_eq!((i, exp), (i, rng.rand_u32()));
        }
    }

    #[test]
    fn test_rand_f64() {
        let expected: [f64, ..50] = [
            0.76275443, 0.99000644, 0.98670464, 0.10143112, 0.27933125,
            0.69867227, 0.94218740, 0.03427201, 0.78842173, 0.28180608,
            0.92179002, 0.20785655, 0.54534773, 0.69644020, 0.38107718,
            0.23978165, 0.65286910, 0.07514568, 0.22765211, 0.94872929,
            0.74557914, 0.62664415, 0.54708246, 0.90959343, 0.42043116,
            0.86334511, 0.19189126, 0.14718544, 0.70259889, 0.63426346,
            0.77408121, 0.04531601, 0.04605807, 0.88595519, 0.69398270,
            0.05377184, 0.61711170, 0.05565708, 0.10133577, 0.41500776,
            0.91810699, 0.22320679, 0.23353705, 0.92871862, 0.98897234,
            0.19786706, 0.80558809, 0.06961067, 0.55840445, 0.90479405,
        ];
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        // For the test data we use 1000 values should be skipped
        for _ in range(0u, 1000) {
            rng.rand_f64();
        }
        for (i, &exp) in expected.iter().enumerate() {
            assert_eq!((i, true), (i, rng.rand_f64() - exp < 0.00000001f64));
        }
    }

    #[bench]
    fn bench_rand_u32(b: &mut Bencher) {
        let mut rng = MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]);
        b.iter(|| rng.rand_u32());
    }

    #[bench]
    fn bench_new(b: &mut Bencher) {
        b.iter(|| MersenneTwister::new(&[0x123, 0x234, 0x345, 0x456]));
    }
}
<|endoftext|>


<commit_before><commit_msg>Offset is a Monoid<commit_after><|endoftext|>


<commit_before><commit_msg>optimize permissions conversions<commit_after><|endoftext|>


<commit_before><commit_msg>bit faster, works sometimes, gets stuck most times. needs better selection algorithm<commit_after><|endoftext|>


<commit_before><commit_msg>Add main.rs to solve errors<commit_after>extern crate simcom;

use std::io::{self, Read};

use simcom::lexer::Lexer;
use simcom::parser::Parser;

fn main() {
    let content = {
        let mut buffer = String::new();
        let stdin = io::stdin();
        stdin.lock().read_to_string(&mut buffer).unwrap();

        buffer
    };

    let ast = Parser::new(Lexer::new(&content));

    for node in ast {
        println!("{:?}", node);
    }
}<|endoftext|>


<commit_before><commit_msg>macro usage<commit_after><|endoftext|>


<commit_before><commit_msg>Add a trailing slash to folder names in the list view<commit_after><|endoftext|>


<commit_before><commit_msg>dynamic refresh<commit_after><|endoftext|>


<commit_before>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use spec::{LinkerFlavor, Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::openbsd_base::opts();
    base.cpu = "pentium4".to_string();
    base.max_atomic_width = Some(64);
    base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
    base.stack_probes = true;

    Ok(Target {
        llvm_target: "i686-unknown-openbsd".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
        arch: "x86".to_string(),
        target_os: "openbsd".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<commit_msg>openbsd-i686: use lld as linker by default<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use spec::{LinkerFlavor, Target, TargetResult};

pub fn target() -> TargetResult {
    let mut base = super::openbsd_base::opts();
    base.cpu = "pentium4".to_string();
    base.max_atomic_width = Some(64);
    base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
    base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-fuse-ld=lld".to_string());
    base.stack_probes = true;

    Ok(Target {
        llvm_target: "i686-unknown-openbsd".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        target_c_int_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
        arch: "x86".to_string(),
        target_os: "openbsd".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: base,
    })
}
<|endoftext|>


<commit_before><commit_msg>Don't import M; fix build<commit_after><|endoftext|>


<commit_before><commit_msg>Add test case.<commit_after>// Copyright 2016 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.

// Checks that lint attributes work on non-item AST nodes

fn main() {
    #[deny(unreachable_code)]
    loop {
        break;
        "unreachable"; //~ ERROR unreachable statement
    }
}
<|endoftext|>


<commit_before><commit_msg>add a build-pass test for issue 62220<commit_after>// build-pass
#![allow(incomplete_features)]

#![feature(const_generics)]
pub struct Vector<T, const N: usize>([T; N]);

pub type TruncatedVector<T, const N: usize> = Vector<T, { N - 1 }>;

impl<T, const N: usize> Vector<T, { N }> {
    /// Drop the last component and return the vector with one fewer dimension.
    pub fn trunc(self) -> (TruncatedVector<T, { N }>, T) {
        unimplemented!()
    }
}

fn vec4<T>(a: T, b: T, c: T, d: T) -> Vector<T, 4> {
    Vector([a, b, c, d])
}

fn main() {
    let (_xyz, _w): (TruncatedVector<u32, 4>, u32) = vec4(0u32, 1, 2, 3).trunc();
}
<|endoftext|>


<commit_before><commit_msg>Refactor(syncfile): split write_syncfile_header into functions; add HMAC skeleton<commit_after><|endoftext|>


<commit_before><commit_msg>Implement PredDouble for positive bin nats<commit_after><|endoftext|>


<commit_before>use data::{Asn1Seq, Asn1SeqField};
use parse::{asn1_type_name, asn1_type};
use parse::space::{skip_other};

named!(pub asn1_seq_field <Asn1SeqField>, chain!(
  skip_other? ~
  name: asn1_type_name ~
  skip_other? ~
  asn1_type: asn1_type,
  || Asn1SeqField {
    name: name,
    asn1_type: asn1_type,
  }
));

named!(pub asn1_seq <Asn1Seq>, chain!(
  tag!("SEQUENCE") ~
  skip_other? ~
  fields: delimited!(
    tag!("{"),
    separated_list!(
      chain!(skip_other? ~ tag!(","), || ()),
      asn1_seq_field
    ),
    tuple!(opt!(skip_other), tag!("}"))
  ),
  || Asn1Seq {
    fields: fields,
  }
));

#[test]
fn test_asn1_sequence_field() {
  let field1 = Asn1SeqField {
    name: "foo".into(),
    asn1_type: ::data::Asn1Type::Type("Bar".into()),
  };
  let field2 = Asn1SeqField {
    name: "asdf".into(),
    asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
  };
  assert_eq!(
    field1,
    asn1_seq_field("foo Bar".as_bytes()).unwrap().1
  );
  assert_eq!(
    field2,
    asn1_seq_field("asdf INTEGER,".as_bytes()).unwrap().1
  );
  assert_eq!(
    field1,
    asn1_seq_field("foo--test\n Bar".as_bytes()).unwrap().1
  );
}

#[test]
fn test_seq_fields() {
  let seq = Asn1Seq {
    fields: vec![
      Asn1SeqField {
        name: "foo".into(),
        asn1_type: ::data::Asn1Type::Type("Bar".into()),
      },
      Asn1SeqField {
        name: "asdf".into(),
        asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
      }
    ],
  };
  println!("{:#?}", asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()));
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()).unwrap().1
  );
}
<commit_msg>Improve sequence tests<commit_after>use data::{Asn1Seq, Asn1SeqField};
use parse::{asn1_type_name, asn1_type};
use parse::space::{skip_other};

named!(pub asn1_seq_field <Asn1SeqField>, chain!(
  skip_other? ~
  name: asn1_type_name ~
  skip_other? ~
  asn1_type: asn1_type,
  || Asn1SeqField {
    name: name,
    asn1_type: asn1_type,
  }
));

named!(pub asn1_seq <Asn1Seq>, chain!(
  tag!("SEQUENCE") ~
  skip_other? ~
  fields: delimited!(
    tag!("{"),
    separated_list!(
      chain!(skip_other? ~ tag!(","), || ()),
      asn1_seq_field
    ),
    tuple!(opt!(skip_other), tag!("}"))
  ),
  || Asn1Seq {
    fields: fields,
  }
));

#[test]
fn test_asn1_sequence_field() {
  let field1 = Asn1SeqField {
    name: "foo".into(),
    asn1_type: ::data::Asn1Type::Type("Bar".into()),
  };
  let field2 = Asn1SeqField {
    name: "asdf".into(),
    asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
  };
  assert_eq!(
    field1,
    asn1_seq_field("foo Bar".as_bytes()).unwrap().1
  );
  assert_eq!(
    field2,
    asn1_seq_field("asdf INTEGER,".as_bytes()).unwrap().1
  );
  assert_eq!(
    field1,
    asn1_seq_field("foo--test\n Bar".as_bytes()).unwrap().1
  );
}

#[test]
fn test_seq_fields() {
  let seq = Asn1Seq {
    fields: vec![
      Asn1SeqField {
        name: "foo".into(),
        asn1_type: ::data::Asn1Type::Type("Bar".into()),
      },
      Asn1SeqField {
        name: "asdf".into(),
        asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
      }
    ],
  };
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()).unwrap().1
  );
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {
        foo Bar --,
        , asdf INTEGER
      }
    ".as_bytes()).unwrap().1
  );
  assert!(asn1_seq("SEQUENC ".as_bytes()).is_err());
}
<|endoftext|>


<commit_before>// Copyright (C) 2014  Josh Stone
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use fuse::FileType;
use git2;
use libc;
use libc::consts::os::posix88;
use std::collections::hash_map;
use std::default::Default;
use std::path::{Path, PathBuf};

use inode;

/// Represents a virtual directory in reference paths
/// (e.g. `refs/heads/master` needs intermediate `refs/` and `refs/heads/`)
pub struct RefDir {
    entries: hash_map::HashMap<PathBuf, inode::Id>,
}

impl RefDir {
    pub fn new() -> Box<inode::Inode+'static> {
        Box::new(RefDir {
            entries: Default::default(),
        })
    }
}

impl inode::Inode for RefDir {
    fn lookup(&mut self, _repo: &git2::Repository, name: &Path
              ) -> Result<inode::Id, libc::c_int> {
        self.entries.get(name).cloned().ok_or(posix88::ENOENT)
    }

    fn getattr(&mut self, _repo: &git2::Repository, attr: inode::FileAttr
               ) -> Result<inode::FileAttr, libc::c_int> {
        let size = self.entries.len() as u64;
        Ok(inode::FileAttr {
            size: size,
            blocks: inode::st_blocks(size),
            kind: FileType::Directory,
            perm: 0755,
            ..attr
        })
    }

    fn readdir<'a>(&mut self, _repo: &git2::Repository, offset: u64,
               mut add: Box<FnMut(inode::Id, FileType, &Path) -> bool + 'a>
              ) -> Result<(), libc::c_int> {
        if offset < self.entries.len() as u64 {
            for (path, &id) in self.entries.iter().skip(offset as usize) {
                if add(id, FileType::Directory, path) {
                    break;
                }
            }
        }
        Ok(())
    }
}

<commit_msg>Path/PathBuf workaround for rustc ICE<commit_after>// Copyright (C) 2014  Josh Stone
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use fuse::FileType;
use git2;
use libc;
use libc::consts::os::posix88;
use std::collections::hash_map;
use std::default::Default;
use std::path::{Path, PathBuf};

use inode;

/// Represents a virtual directory in reference paths
/// (e.g. `refs/heads/master` needs intermediate `refs/` and `refs/heads/`)
pub struct RefDir {
    entries: hash_map::HashMap<PathBuf, inode::Id>,
}

impl RefDir {
    pub fn new() -> Box<inode::Inode+'static> {
        Box::new(RefDir {
            entries: Default::default(),
        })
    }
}

impl inode::Inode for RefDir {
    fn lookup(&mut self, _repo: &git2::Repository, name: &Path
              ) -> Result<inode::Id, libc::c_int> {
        // workaround for rust-lang/rust#23649
        let name_buf = name.to_path_buf();
        let name = &name_buf;

        self.entries.get(name).cloned().ok_or(posix88::ENOENT)
    }

    fn getattr(&mut self, _repo: &git2::Repository, attr: inode::FileAttr
               ) -> Result<inode::FileAttr, libc::c_int> {
        let size = self.entries.len() as u64;
        Ok(inode::FileAttr {
            size: size,
            blocks: inode::st_blocks(size),
            kind: FileType::Directory,
            perm: 0755,
            ..attr
        })
    }

    fn readdir<'a>(&mut self, _repo: &git2::Repository, offset: u64,
               mut add: Box<FnMut(inode::Id, FileType, &Path) -> bool + 'a>
              ) -> Result<(), libc::c_int> {
        if offset < self.entries.len() as u64 {
            for (path, &id) in self.entries.iter().skip(offset as usize) {
                if add(id, FileType::Directory, path) {
                    break;
                }
            }
        }
        Ok(())
    }
}

<|endoftext|>