<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.
*/
extern crate hyper;
extern crate websocket;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,channel};
use std::thread::Thread;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::message::WebSocketMessage;
use websocket::handshake::WebSocketRequest;
use url::Url;

///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);
}

///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()
	}
}

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

///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
		}
	}

	///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(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(mstr) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		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> {
		//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 res_str = match res.read_to_string() {
			Ok(res_str) => 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())
		}

		//Make websocket request
		let req = match WebSocketRequest::connect(wss_url) {
			Ok(req) => req,
			Err(err) => return Err(format!("{:?} : WebSocketRequest::connect(wss_url): wss_url{:?}", err, wss_url))
		};

		//Get the key so we can verify it later.
		let key = match req.key() {
			Some(key) => key.clone(),
			None => return Err("Request host key match failed.".to_string())
		};

		//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(&key) {
			Ok(()) => { }
			Err(err) => return Err(format!("Websocket request key validation error: {:?}", err))
		}

		let mut client = res.begin();

		//for sending messages
		let (tx,rx) = channel::<String>();
		self.outs = Some(tx);

		let mut captured_client = client.clone();

		//websocket send loop
		let guard = Thread::spawn(move || -> () {
			loop {
				let m = match rx.recv() {
					Ok(m) => m,
					Err(err) => panic!(format!("{:?}", err))
				};
			 	let msg = WebSocketMessage::Text(m);
			 	match captured_client.send_message(msg) {
			 		Ok(_) => {},
			 		Err(err) => panic!(format!("{:?}", err))
			 	}
			 }
		});

		let mut sending_client = client.clone();

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

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

		Ok(())
	}
}
<commit_msg>clone wss_url to avoid usage of moved value in debug.<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.
*/
extern crate hyper;
extern crate websocket;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,channel};
use std::thread::Thread;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::message::WebSocketMessage;
use websocket::handshake::WebSocketRequest;
use url::Url;

///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);
}

///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()
	}
}

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

///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
		}
	}

	///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(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(mstr) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		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> {
		//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 res_str = match res.read_to_string() {
			Ok(res_str) => 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())
		}

		//Make websocket request
		let req = match WebSocketRequest::connect(wss_url.clone()) {
			Ok(req) => req,
			Err(err) => return Err(format!("{:?} : WebSocketRequest::connect(wss_url): wss_url{:?}", err, wss_url))
		};

		//Get the key so we can verify it later.
		let key = match req.key() {
			Some(key) => key.clone(),
			None => return Err("Request host key match failed.".to_string())
		};

		//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(&key) {
			Ok(()) => { }
			Err(err) => return Err(format!("Websocket request key validation error: {:?}", err))
		}

		let mut client = res.begin();

		//for sending messages
		let (tx,rx) = channel::<String>();
		self.outs = Some(tx);

		let mut captured_client = client.clone();

		//websocket send loop
		let guard = Thread::spawn(move || -> () {
			loop {
				let m = match rx.recv() {
					Ok(m) => m,
					Err(err) => panic!(format!("{:?}", err))
				};
			 	let msg = WebSocketMessage::Text(m);
			 	match captured_client.send_message(msg) {
			 		Ok(_) => {},
			 		Err(err) => panic!(format!("{:?}", err))
			 	}
			 }
		});

		let mut sending_client = client.clone();

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

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

		Ok(())
	}
}
<|endoftext|>


<commit_before><commit_msg>Handle expressions like (hello(world))<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015, Nathan Zadoks <nathan@nathan7.eu>
// See the LICENSE file included in this distribution.
#![feature(no_std)]
#![feature(asm, core)]
#![feature(libc)]
#![no_std]

#[macro_use]
extern crate core;

#[cfg(test)]
#[macro_use]
extern crate std;

pub use context::Context;
pub use stack::Stack;
#[cfg(feature = "os")]
pub use os::Stack as OsStack;

#[cfg(not(test))]
mod std { pub use core::*; }

mod context;
mod stack;

mod debug;

mod arch;

#[cfg(feature = "os")]
mod os;
<commit_msg>rejig lib.rs a little<commit_after>// Copyright (c) 2015, Nathan Zadoks <nathan@nathan7.eu>
// See the LICENSE file included in this distribution.
#![feature(no_std)]
#![feature(asm, core)]
#![feature(libc)]
#![no_std]

#[macro_use]
extern crate core;

#[cfg(test)]
#[macro_use]
extern crate std;

pub use context::Context;
pub use stack::Stack;

#[cfg(feature = "os")]
pub use os::Stack as OsStack;

mod context;
mod stack;

#[cfg(feature = "os")]
mod os;

mod arch;
mod debug;

#[cfg(not(test))]
mod std { pub use core::*; }
<|endoftext|>


<commit_before><commit_msg>feat(lib): make `Font` derive `Copy`<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Table data-structure<commit_after><|endoftext|>


<commit_before><commit_msg>Another attempt that still isnt working yet.<commit_after>#![feature(phase)]
#[phase(syntax, link)] extern crate log;

extern crate http;
extern crate sync;
use std::io::net::ip::SocketAddr;
use std::vec::Vec;
use std::cell::RefCell;
use http::server::ResponseWriter;
use http::server::Server;

use sync::{RWLock, Arc};

#[deriving(Clone)]
struct Oxidize<'a> {
    pub conf : Arc<&'a Config>,
    pub router : RefCell<~Router<'a>:Send>,
    // pub filters : ~[~MiddleWare],
}

trait App<'a>:Send+Share {
    fn get_router(&'a self) -> ~Router<'a>:Send;
    fn handle_route(&self, reverse: &str);
}

impl<'a> App<'a> for MyApp<'a> {
    fn get_router(&'a self) -> ~Router<'a>:Send {
        ~MatchRouter {
            app: Arc::new(RWLock::new(self as &'a App:Send+Share)),
            routes: Arc::new(RWLock::new(~[
                ("GET", "index", "/index"),
                ("GET", "hello", "/hello"),
            ])),
        } as ~Router:Send
    }

    fn handle_route(&self, reverse: &str) {
        match reverse {
            "/index" => self.index(),
            "/hello" => self.hello(),
            _ => unreachable!(),
        }
    }
}

struct MyApp<'a> {
    router : Arc<Option<&'a Router<'a>:Send>>,
    renderer: Arc<Renderer>,
}

trait Router<'a>:Send {
    fn add_route(&self, method: &str, name: &str, url: &str);
    fn route(&self, Request, &mut Response);
    fn copy(&self) -> ~Router<'a>:Send;
}

impl<'a> Clone for ~Router<'a>:Send {
    fn clone(&self) -> ~Router<'a>:Send {
        self.copy()
    }
}

// not fully operational but good enough for now
struct MatchRouter<'a> {
    app : Arc<RWLock<&'a App<'a>:Send+Share>>,
    routes : Arc<RWLock<~[(&'static str, &'static str, &'static str)]>>,
}

impl<'a> Router<'a> for MatchRouter<'a> {
    fn add_route(&self, method: &str, name: &str, url: &str){
        // self.routes.write().push(f);
    }
    fn route(&self, req: Request, res: &mut Response) {
        match req.url {
            "/index" | "/hello" => self.app.read().handle_route(req.url),
            _ => unreachable!(),
        };
    }
    fn copy(&self) -> ~Router<'a>:Send {
        ~MatchRouter {
            app: self.app.clone(),
            routes: self.routes.clone(),
        } as ~Router<'a>:Send
    }
}

impl<'a> MyApp<'a> {
    fn index(&self) { self.renderer.print(); }
    fn hello(&self) { println!("hello!"); }
}

impl<'a> Server for Oxidize<'a> {
    fn get_config(&self) -> http::server::Config {
        let bind_addr = self.conf.bind_addr;
        http::server::Config { bind_address: bind_addr }
    }

    fn handle_request(&self, req: &http::server::Request, response: &mut ResponseWriter) {
        let q = Request{ url: "test" };
        let mut s = Response{ text: ~"hehe" };

        self.router.borrow().route(q, &mut s);
    }
}

impl<'a> Oxidize<'a> {
    fn serve(self) {
        println!("Server is now running at {}", self.conf.bind_addr.to_str());
        self.serve_forever();
    }
}
fn main() {

    let conf = Config {
        bind_addr: from_str::<SocketAddr>("127.0.0.1:8001").unwrap(),
    };
}

struct Renderer;

impl Renderer {
    fn print(&self) {
        println!("Rendered!");
    }
}

struct Config {
    pub bind_addr : SocketAddr,
}

struct Request<'a> {
    url: &'a str,
}

struct Response {
    text: ~str
}<|endoftext|>


<commit_before><commit_msg>Store#frames, #filtered_frames: handle invalid ranges; fix #4<commit_after><|endoftext|>


<commit_before>/*

Idea: provide functions for 'exhaustive' and 'random' modification of vecs.

  two functions, "return all edits" and "return a random edit" <-- leaning toward this model
    or
  two functions, "return the number of possible edits" and "return edit #n"

It would be nice if this could be data-driven, so the two functions could share information:
  type vec_modifier = rec(fn (&int[] v, uint i) -> int[] fun, uint lo, uint di);
  const vec_modifier[] vec_modifiers = ~[rec(fun=vec_omit, 0u, 1u), ...];
But that gives me "error: internal compiler error unimplemented consts that's not a plain literal".
https://github.com/graydon/rust/issues/570

vec_edits is not an iter because iters might go away and:
https://github.com/graydon/rust/issues/639

vec_omit and friends are not type-parameterized because:
https://github.com/graydon/rust/issues/640

*/

use std;
import std::ivec;
import std::ivec::slice;
import std::ivec::len;
import std::int;

//fn vec_reverse(&int[] v) -> int[] { ... }

fn vec_omit   (&int[] v, uint i) -> int[] { slice(v, 0u, i) +                      slice(v, i+1u, len(v)) }
fn vec_dup    (&int[] v, uint i) -> int[] { slice(v, 0u, i) + ~[v.(i)]           + slice(v, i,    len(v)) }
fn vec_swadj  (&int[] v, uint i) -> int[] { slice(v, 0u, i) + ~[v.(i+1u), v.(i)] + slice(v, i+2u, len(v)) }
fn vec_prefix (&int[] v, uint i) -> int[] { slice(v, 0u, i) }
fn vec_suffix (&int[] v, uint i) -> int[] { slice(v, i, len(v)) }

fn vec_poke   (&int[] v, uint i, int x) -> int[] { slice(v, 0u, i) + ~[x] + slice(v, i+1u, len(v)) }
fn vec_insert (&int[] v, uint i, int x) -> int[] { slice(v, 0u, i) + ~[x] + slice(v, i, len(v)) }

// Iterates over 0...length, skipping the specified number on each side.
iter ix(uint skip_low, uint skip_high, uint length) -> uint { let uint i = skip_low; while (i + skip_high <= length) { put i; i += 1u; } }

// Returns a bunch of modified versions of v, some of which introduce new elements (borrowed from xs).
fn vec_edits(&int[] v, &int[] xs) -> int[][] {
    let int[][] edits = ~[];
    let uint Lv = len(v);

    if (Lv != 1u) { edits += ~[~[]]; } // When Lv == 1u, this is redundant with omit
    //if (Lv >= 3u) { edits += ~[vec_reverse(v)]; }

    for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_omit  (v, i)]; }
    for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_dup   (v, i)]; }
    for each (uint i in ix(0u, 2u, Lv)) { edits += ~[vec_swadj (v, i)]; }
    for each (uint i in ix(1u, 2u, Lv)) { edits += ~[vec_prefix(v, i)]; }
    for each (uint i in ix(2u, 1u, Lv)) { edits += ~[vec_suffix(v, i)]; }

    for each (uint j in ix(0u, 1u, len(xs))) {
      for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_poke  (v, i, xs.(j))]; }
      for each (uint i in ix(0u, 0u, Lv)) { edits += ~[vec_insert(v, i, xs.(j))]; }
    }

    edits
}

// Would be nice if this were built in: https://github.com/graydon/rust/issues/424
fn vec_to_str(&int[] v) -> str {
    auto i = 0u;
    auto s = "[";
    while (i < len(v)) {
        s += int::str(v.(i));
        if (i + 1u < len(v)) {
            s += ", "
        }
        i += 1u;
    }
    ret s + "]";
}

fn show_edits(&int[] a, &int[] xs) {
    log_err "=== Edits of " + vec_to_str(a) + " ===";
    auto b = vec_edits(a, xs);
    for each (uint i in ix(0u, 1u, len(b))) {
        log_err vec_to_str(b.(i));
    }
}

fn demo_edits() {
    auto xs = ~[7, 8];
    show_edits(~[], xs);
    show_edits(~[1], xs);
    show_edits(~[1,2], xs);
    show_edits(~[1,2,3], xs);
    show_edits(~[1,2,3,4], xs);
}

fn main() {
    demo_edits();
}
<commit_msg>Type-parameterize ivec_fuzz<commit_after>/*

Idea: provide functions for 'exhaustive' and 'random' modification of vecs.

  two functions, "return all edits" and "return a random edit" <-- leaning toward this model
    or
  two functions, "return the number of possible edits" and "return edit #n"

It would be nice if this could be data-driven, so the two functions could share information:
  type vec_modifier = rec(fn (&T[] v, uint i) -> T[] fun, uint lo, uint di);
  const vec_modifier[] vec_modifiers = ~[rec(fun=vec_omit, 0u, 1u), ...];
But that gives me "error: internal compiler error unimplemented consts that's not a plain literal".
https://github.com/graydon/rust/issues/570

vec_edits is not an iter because iters might go away and:
https://github.com/graydon/rust/issues/639

vec_omit and friends are not type-parameterized because:
https://github.com/graydon/rust/issues/640

*/

use std;
import std::ivec;
import std::ivec::slice;
import std::ivec::len;
import std::int;

//fn vec_reverse(&T[] v) -> T[] { ... }

fn vec_omit   [T] (&T[] v, uint i) -> T[] { slice(v, 0u, i) +                      slice(v, i+1u, len(v)) }
fn vec_dup    [T] (&T[] v, uint i) -> T[] { slice(v, 0u, i) + ~[v.(i)]           + slice(v, i,    len(v)) }
fn vec_swadj  [T] (&T[] v, uint i) -> T[] { slice(v, 0u, i) + ~[v.(i+1u), v.(i)] + slice(v, i+2u, len(v)) }
fn vec_prefix [T] (&T[] v, uint i) -> T[] { slice(v, 0u, i) }
fn vec_suffix [T] (&T[] v, uint i) -> T[] { slice(v, i, len(v)) }

fn vec_poke   [T] (&T[] v, uint i, &T x) -> T[] { slice(v, 0u, i) + ~[x] + slice(v, i+1u, len(v)) }
fn vec_insert [T] (&T[] v, uint i, &T x) -> T[] { slice(v, 0u, i) + ~[x] + slice(v, i, len(v)) }

// Iterates over 0...length, skipping the specified number on each side.
iter ix(uint skip_low, uint skip_high, uint length) -> uint { let uint i = skip_low; while (i + skip_high <= length) { put i; i += 1u; } }

// Returns a bunch of modified versions of v, some of which introduce new elements (borrowed from xs).
fn vec_edits[T](&T[] v, &T[] xs) -> T[][] {
    let T[][] edits = ~[];
    let uint Lv = len(v);

    if (Lv != 1u) { edits += ~[~[]]; } // When Lv == 1u, this is redundant with omit
    //if (Lv >= 3u) { edits += ~[vec_reverse(v)]; }

    for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_omit  (v, i)]; }
    for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_dup   (v, i)]; }
    for each (uint i in ix(0u, 2u, Lv)) { edits += ~[vec_swadj (v, i)]; }
    for each (uint i in ix(1u, 2u, Lv)) { edits += ~[vec_prefix(v, i)]; }
    for each (uint i in ix(2u, 1u, Lv)) { edits += ~[vec_suffix(v, i)]; }

    for each (uint j in ix(0u, 1u, len(xs))) {
        for each (uint i in ix(0u, 1u, Lv)) { edits += ~[vec_poke  (v, i, xs.(j))]; }
        for each (uint i in ix(0u, 0u, Lv)) { edits += ~[vec_insert(v, i, xs.(j))]; }
    }

    edits
}

// Would be nice if this were built in: https://github.com/graydon/rust/issues/424
fn vec_to_str(&int[] v) -> str {
    auto i = 0u;
    auto s = "[";
    while (i < len(v)) {
        s += int::str(v.(i));
        if (i + 1u < len(v)) {
            s += ", "
        }
        i += 1u;
    }
    ret s + "]";
}

fn show_edits(&int[] a, &int[] xs) {
    log_err "=== Edits of " + vec_to_str(a) + " ===";
    auto b = vec_edits(a, xs);
    for each (uint i in ix(0u, 1u, len(b))) {
        log_err vec_to_str(b.(i));
    }
}

fn demo_edits() {
    auto xs = ~[7, 8];
    show_edits(~[], xs);
    show_edits(~[1], xs);
    show_edits(~[1,2], xs);
    show_edits(~[1,2,3], xs);
    show_edits(~[1,2,3,4], xs);
}

fn main() {
    demo_edits();
}
<|endoftext|>


<commit_before><commit_msg>ICH: Add test case sensitive to function bodies in metadata.<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.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Case 1: The function body is not exported to metadata. If the body changes,
//         the hash of the HirBody node should change, but not the hash of
//         either the Hir or the Metadata node.

#[cfg(cfail1)]
pub fn body_not_exported_to_metadata() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn body_not_exported_to_metadata() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         marked as #[inline]. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         generic. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    2
}

<|endoftext|>


<commit_before><commit_msg>Add test for #6861<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.

// Make sure the destructor is run for unit-like structs.

use std::task;

struct Foo;

impl Drop for Foo {
    fn finalize(&self) {
        fail!("This failure should happen.");
    }
}

fn main() {
    let x = do task::try {
        let _b = Foo;
    };
    assert_eq!(x, Err(()));
}
<|endoftext|>


<commit_before>use utils;
use errors::*;
use temp;
use env_var;
use dist;
#[cfg(windows)]
use msi;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::env;

const REL_MANIFEST_DIR: &'static str = "rustlib";

pub struct InstallPrefix {
	path: PathBuf,
	install_type: InstallType,
}

#[derive(Eq, PartialEq, Copy, Clone)]
pub enum InstallType {
	// Must be uninstalled by deleting the entire directory
	Owned,
	// Must be uninstalled via `uninstall.sh` on linux or `msiexec /x` on windows
	Shared,
}

pub enum Uninstaller {
	Sh(PathBuf),
	Msi(String),
}

impl Uninstaller {
	pub fn run(&self) -> Result<()> {
		match *self {
			Uninstaller::Sh(ref path) => {
				let mut cmd = Command::new("sudo");
				cmd.arg("sh").arg(path);
				utils::cmd_status("uninstall.sh", cmd)
			},
			Uninstaller::Msi(ref id) => {
				let mut cmd = Command::new("msiexec");
				cmd.arg("/x").arg(id);
				utils::cmd_status("msiexec", cmd)
			},
		}
	}
}

pub enum InstallMethod<'a> {
	Copy(&'a Path),
	Link(&'a Path),
	Installer(&'a Path, &'a temp::Cfg),
	Dist(&'a str, Option<&'a Path>, dist::DownloadCfg<'a>),
}

impl<'a> InstallMethod<'a> {
	pub fn install_type_possible(&self, install_type: InstallType) -> bool {
		match *self {
			InstallMethod::Copy(_)|InstallMethod::Link(_) => install_type == InstallType::Owned,
			InstallMethod::Installer(_, _)|InstallMethod::Dist(_,_,_) => true,
		}
	}
	pub fn run(self, prefix: &InstallPrefix, notify_handler: &NotifyHandler) -> Result<()> {
		if prefix.is_installed_here() {
			// Don't uninstall first for Dist method
			match self {
				InstallMethod::Dist(_,_,_) => {},
				_ => { try!(prefix.uninstall(notify_handler)); },
			}
		}

		if !self.install_type_possible(prefix.install_type) {
			return Err(Error::InstallTypeNotPossible);
		}

		match self {
			InstallMethod::Copy(src) => {
				utils::copy_dir(src, &prefix.path, notify_handler)
			},
			InstallMethod::Link(src) => {
				utils::symlink_dir(&prefix.path, src, notify_handler)
			},
			InstallMethod::Installer(src, temp_cfg) => {
				notify_handler.call(Extracting(src, prefix.path()));
				let temp_dir = try!(temp_cfg.new_directory());
				match src.extension().and_then(OsStr::to_str) {
					Some("gz") => InstallMethod::tar_gz(src, &temp_dir, prefix),
					Some("msi") => InstallMethod::msi(src, &temp_dir, prefix),
					_ => Err(Error::InvalidFileExtension),
				}
			},
			InstallMethod::Dist(toolchain, update_hash, dl_cfg) => {
				if let Some((installer, hash)) = try!(dist::download_dist(toolchain, update_hash, dl_cfg)) {
					try!(InstallMethod::Installer(&*installer, dl_cfg.temp_cfg).run(prefix, dl_cfg.notify_handler));
					if let Some(hash_file) = update_hash {
						try!(utils::write_file("update hash", hash_file, &hash));
					}
				}
				Ok(())
			}
		}
	}

	fn tar_gz(src: &Path, work_dir: &Path, prefix: &InstallPrefix) -> Result<()> {
		let installer_dir = Path::new(try!(Path::new(src.file_stem().unwrap()).file_stem()
			.ok_or(Error::InvalidFileExtension)));

		let mut cmd = Command::new("tar");
		cmd
			.arg("xzf").arg(src)
			.arg("-C").arg(work_dir);

		try!(utils::cmd_status("tar", cmd));

		// Find the root Rust folder within the subfolder
		let root_dir = try!(try!(utils::read_dir("install", work_dir))
			.filter_map(io::Result::ok)
			.map(|e| e.path())
			.filter(|p| utils::is_directory(&p))
			.next()
			.ok_or(Error::InvalidInstaller));

		let mut cmd = Command::new("sh");
		cmd
			.arg(root_dir.join("install.sh"))
			.arg("--prefix").arg(&prefix.path);

		if prefix.install_type != InstallType::Shared {
			cmd.arg("--disable-ldconfig");
		}

		let result = utils::cmd_status("sh", cmd);

		let _ = fs::remove_dir_all(&installer_dir);

		if result.is_err() && prefix.install_type == InstallType::Owned {
			let _ = fs::remove_dir_all(&prefix.path);
		}

		result
	}
	fn msi(src: &Path, work_dir: &Path, prefix: &InstallPrefix) -> Result<()> {
		let msi_owned = || -> Result<()> {
			let target_arg = utils::prefix_arg("TARGETDIR=", work_dir);

			// Extract the MSI to the subfolder
			let mut cmd = Command::new("msiexec");
			cmd
				.arg("/a").arg(src)
				.arg("/qn")
				.arg(&target_arg);

			try!(utils::cmd_status("msiexec", cmd));

			// Find the root Rust folder within the subfolder
			let root_dir = try!(try!(utils::read_dir("install", work_dir))
				.filter_map(io::Result::ok)
				.map(|e| e.path())
				.filter(|p| utils::is_directory(&p))
				.next()
				.ok_or(Error::InvalidInstaller));

			// Rename and move it to the toolchain directory
			utils::rename_dir("install", &root_dir, &prefix.path)
		};

		let msi_shared = || -> Result<()> {
			let target_arg = utils::prefix_arg("TARGETDIR=", &prefix.path);

			// Extract the MSI to the subfolder
			let mut cmd = Command::new("msiexec");
			cmd
				.arg("/i").arg(src)
				.arg("/qn")
				.arg(&target_arg);

			utils::cmd_status("msiexec", cmd)
		};

		match prefix.install_type {
			InstallType::Owned => {
				let result = msi_owned();
				if result.is_err() {
					let _ = fs::remove_dir_all(&prefix.path);
				}
				result
			},
			InstallType::Shared => {
				msi_shared()
			}
		}
	}
}

pub fn bin_path(name: &str) -> PathBuf {
	let mut path = PathBuf::from("bin");
	path.push(name.to_owned() + env::consts::EXE_SUFFIX);
	path
}

impl InstallPrefix {
	pub fn from(path: PathBuf, install_type: InstallType) -> Self {
		InstallPrefix {
			path: path,
			install_type: install_type,
		}
	}
	pub fn path(&self) -> &Path {
		&self.path
	}
	pub fn manifest_dir(&self) -> PathBuf {
		let mut path = self.path.clone();
		path.push("bin");
		path.push(REL_MANIFEST_DIR);
		path
	}
	pub fn manifest_file(&self, name: &str) -> PathBuf {
		let mut path = self.manifest_dir();
		path.push(name);
		path
	}
	pub fn binary_file(&self, name: &str) -> PathBuf {
		let mut path = self.path.clone();
		path.push(bin_path(name));
		path
	}
	pub fn doc_path(&self, relative: &str) -> Result<PathBuf> {
		let parts = vec!["share", "doc", "rust", "html"];
		let mut doc_dir = self.path.clone();
		for part in parts {
			doc_dir.push(part);
		}
		doc_dir.push(relative);

		Ok(doc_dir)
	}
	pub fn is_installed_here(&self) -> bool {
		utils::is_directory(&self.manifest_dir())
	}
	pub fn get_uninstall_sh(&self) -> Option<PathBuf> {
		let path = self.manifest_file("uninstall.sh");
		if utils::is_file(&path) {
			Some(path)
		} else {
			None
		}
	}

	#[cfg(windows)]
	pub fn get_uninstall_msi(&self, notify_handler: &NotifyHandler) -> Option<String> {
		let canon_path = utils::canonicalize_path(&self.path, notify_handler);

		if let Ok(installers) = msi::all_installers() {
			for installer in &installers {
				if let Ok(loc) = installer.install_location() {
					let path = utils::canonicalize_path(&loc, notify_handler);

					if path == canon_path {
						return Some(installer.product_id().to_owned());
					}
				}
			}
		}

		None
	}
	#[cfg(not(windows))]
	pub fn get_uninstall_msi(&self, _: &NotifyHandler) -> Option<String> {
		None
	}
	pub fn get_uninstaller(&self, notify_handler: &NotifyHandler) -> Option<Uninstaller> {
		self.get_uninstall_sh().map(Uninstaller::Sh).or_else(
			|| self.get_uninstall_msi(notify_handler).map(Uninstaller::Msi)
			)
	}
	pub fn uninstall(&self, notify_handler: &NotifyHandler) -> Result<()> {
		if self.is_installed_here() {
			match self.install_type {
				InstallType::Owned => {
					utils::remove_dir("install", &self.path, notify_handler)
				},
				InstallType::Shared => {
					if let Some(uninstaller) = self.get_uninstaller(notify_handler) {
						uninstaller.run()
					} else {
						Err(Error::NotInstalledHere)
					}
				},
			}
		} else {
			Err(Error::NotInstalledHere)
		}
	}
	pub fn install(&self, method: InstallMethod, notify_handler: &NotifyHandler) -> Result<()> {
		method.run(self, notify_handler)
	}

	pub fn with_ldpath<T, F: FnOnce() -> Result<T>>(&self, f: F) -> Result<T> {
		let new_path = self.path.join("lib");

		env_var::with_path("LD_LIBRARY_PATH", &new_path, || {
			env_var::with_path("DYLD_LIBRARY_PATH", &new_path, || {
				f()
			})
		})
	}

	pub fn with_env<T, F: FnOnce() -> Result<T>>(&self, f: F) -> Result<T> {
		let cargo_path = self.path.join("cargo");

		self.with_ldpath(|| {
			env_var::with_default("CARGO_HOME", cargo_path.as_ref(), || {
				f()
			})
		})
	}

	pub fn create_command(&self, binary: &str) -> Result<Command> {
		let binary_path = self.binary_file(binary);

		self.with_env(|| Ok(Command::new(binary_path)))
	}

	pub fn open_docs(&self, relative: &str) -> Result<()> {
		utils::open_browser(&try!(self.doc_path(relative)))
	}
}
<commit_msg>Fix install.sh invocation<commit_after>use utils;
use errors::*;
use temp;
use env_var;
use dist;
#[cfg(windows)]
use msi;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::env;

const REL_MANIFEST_DIR: &'static str = "rustlib";

pub struct InstallPrefix {
	path: PathBuf,
	install_type: InstallType,
}

#[derive(Eq, PartialEq, Copy, Clone)]
pub enum InstallType {
	// Must be uninstalled by deleting the entire directory
	Owned,
	// Must be uninstalled via `uninstall.sh` on linux or `msiexec /x` on windows
	Shared,
}

pub enum Uninstaller {
	Sh(PathBuf),
	Msi(String),
}

impl Uninstaller {
	pub fn run(&self) -> Result<()> {
		match *self {
			Uninstaller::Sh(ref path) => {
				let mut cmd = Command::new("sudo");
				cmd.arg("sh").arg(path);
				utils::cmd_status("uninstall.sh", cmd)
			},
			Uninstaller::Msi(ref id) => {
				let mut cmd = Command::new("msiexec");
				cmd.arg("/x").arg(id);
				utils::cmd_status("msiexec", cmd)
			},
		}
	}
}

pub enum InstallMethod<'a> {
	Copy(&'a Path),
	Link(&'a Path),
	Installer(&'a Path, &'a temp::Cfg),
	Dist(&'a str, Option<&'a Path>, dist::DownloadCfg<'a>),
}

impl<'a> InstallMethod<'a> {
	pub fn install_type_possible(&self, install_type: InstallType) -> bool {
		match *self {
			InstallMethod::Copy(_)|InstallMethod::Link(_) => install_type == InstallType::Owned,
			InstallMethod::Installer(_, _)|InstallMethod::Dist(_,_,_) => true,
		}
	}
	pub fn run(self, prefix: &InstallPrefix, notify_handler: &NotifyHandler) -> Result<()> {
		if prefix.is_installed_here() {
			// Don't uninstall first for Dist method
			match self {
				InstallMethod::Dist(_,_,_) => {},
				_ => { try!(prefix.uninstall(notify_handler)); },
			}
		}

		if !self.install_type_possible(prefix.install_type) {
			return Err(Error::InstallTypeNotPossible);
		}

		match self {
			InstallMethod::Copy(src) => {
				utils::copy_dir(src, &prefix.path, notify_handler)
			},
			InstallMethod::Link(src) => {
				utils::symlink_dir(&prefix.path, src, notify_handler)
			},
			InstallMethod::Installer(src, temp_cfg) => {
				notify_handler.call(Extracting(src, prefix.path()));
				let temp_dir = try!(temp_cfg.new_directory());
				match src.extension().and_then(OsStr::to_str) {
					Some("gz") => InstallMethod::tar_gz(src, &temp_dir, prefix),
					Some("msi") => InstallMethod::msi(src, &temp_dir, prefix),
					_ => Err(Error::InvalidFileExtension),
				}
			},
			InstallMethod::Dist(toolchain, update_hash, dl_cfg) => {
				if let Some((installer, hash)) = try!(dist::download_dist(toolchain, update_hash, dl_cfg)) {
					try!(InstallMethod::Installer(&*installer, dl_cfg.temp_cfg).run(prefix, dl_cfg.notify_handler));
					if let Some(hash_file) = update_hash {
						try!(utils::write_file("update hash", hash_file, &hash));
					}
				}
				Ok(())
			}
		}
	}

	fn tar_gz(src: &Path, work_dir: &Path, prefix: &InstallPrefix) -> Result<()> {
		let installer_dir = Path::new(try!(Path::new(src.file_stem().unwrap()).file_stem()
			.ok_or(Error::InvalidFileExtension)));

		let mut cmd = Command::new("tar");
		cmd
			.arg("xzf").arg(src)
			.arg("-C").arg(work_dir);

		try!(utils::cmd_status("tar", cmd));

		// Find the root Rust folder within the subfolder
		let root_dir = try!(try!(utils::read_dir("install", work_dir))
			.filter_map(io::Result::ok)
			.map(|e| e.path())
			.filter(|p| utils::is_directory(&p))
			.next()
			.ok_or(Error::InvalidInstaller));

		let mut cmd = Command::new("sh");
		let mut arg = OsString::from("--prefix=\"");
		arg.push(&prefix.path);
		arg.push("\"");
		cmd
			.arg(root_dir.join("install.sh"))
			.arg(arg);

		if prefix.install_type != InstallType::Shared {
			cmd.arg("--disable-ldconfig");
		}

		let result = utils::cmd_status("sh", cmd);

		let _ = fs::remove_dir_all(&installer_dir);

		if result.is_err() && prefix.install_type == InstallType::Owned {
			let _ = fs::remove_dir_all(&prefix.path);
		}

		result
	}
	fn msi(src: &Path, work_dir: &Path, prefix: &InstallPrefix) -> Result<()> {
		let msi_owned = || -> Result<()> {
			let target_arg = utils::prefix_arg("TARGETDIR=", work_dir);

			// Extract the MSI to the subfolder
			let mut cmd = Command::new("msiexec");
			cmd
				.arg("/a").arg(src)
				.arg("/qn")
				.arg(&target_arg);

			try!(utils::cmd_status("msiexec", cmd));

			// Find the root Rust folder within the subfolder
			let root_dir = try!(try!(utils::read_dir("install", work_dir))
				.filter_map(io::Result::ok)
				.map(|e| e.path())
				.filter(|p| utils::is_directory(&p))
				.next()
				.ok_or(Error::InvalidInstaller));

			// Rename and move it to the toolchain directory
			utils::rename_dir("install", &root_dir, &prefix.path)
		};

		let msi_shared = || -> Result<()> {
			let target_arg = utils::prefix_arg("TARGETDIR=", &prefix.path);

			// Extract the MSI to the subfolder
			let mut cmd = Command::new("msiexec");
			cmd
				.arg("/i").arg(src)
				.arg("/qn")
				.arg(&target_arg);

			utils::cmd_status("msiexec", cmd)
		};

		match prefix.install_type {
			InstallType::Owned => {
				let result = msi_owned();
				if result.is_err() {
					let _ = fs::remove_dir_all(&prefix.path);
				}
				result
			},
			InstallType::Shared => {
				msi_shared()
			}
		}
	}
}

pub fn bin_path(name: &str) -> PathBuf {
	let mut path = PathBuf::from("bin");
	path.push(name.to_owned() + env::consts::EXE_SUFFIX);
	path
}

impl InstallPrefix {
	pub fn from(path: PathBuf, install_type: InstallType) -> Self {
		InstallPrefix {
			path: path,
			install_type: install_type,
		}
	}
	pub fn path(&self) -> &Path {
		&self.path
	}
	pub fn manifest_dir(&self) -> PathBuf {
		let mut path = self.path.clone();
		path.push("bin");
		path.push(REL_MANIFEST_DIR);
		path
	}
	pub fn manifest_file(&self, name: &str) -> PathBuf {
		let mut path = self.manifest_dir();
		path.push(name);
		path
	}
	pub fn binary_file(&self, name: &str) -> PathBuf {
		let mut path = self.path.clone();
		path.push(bin_path(name));
		path
	}
	pub fn doc_path(&self, relative: &str) -> Result<PathBuf> {
		let parts = vec!["share", "doc", "rust", "html"];
		let mut doc_dir = self.path.clone();
		for part in parts {
			doc_dir.push(part);
		}
		doc_dir.push(relative);

		Ok(doc_dir)
	}
	pub fn is_installed_here(&self) -> bool {
		utils::is_directory(&self.manifest_dir())
	}
	pub fn get_uninstall_sh(&self) -> Option<PathBuf> {
		let path = self.manifest_file("uninstall.sh");
		if utils::is_file(&path) {
			Some(path)
		} else {
			None
		}
	}

	#[cfg(windows)]
	pub fn get_uninstall_msi(&self, notify_handler: &NotifyHandler) -> Option<String> {
		let canon_path = utils::canonicalize_path(&self.path, notify_handler);

		if let Ok(installers) = msi::all_installers() {
			for installer in &installers {
				if let Ok(loc) = installer.install_location() {
					let path = utils::canonicalize_path(&loc, notify_handler);

					if path == canon_path {
						return Some(installer.product_id().to_owned());
					}
				}
			}
		}

		None
	}
	#[cfg(not(windows))]
	pub fn get_uninstall_msi(&self, _: &NotifyHandler) -> Option<String> {
		None
	}
	pub fn get_uninstaller(&self, notify_handler: &NotifyHandler) -> Option<Uninstaller> {
		self.get_uninstall_sh().map(Uninstaller::Sh).or_else(
			|| self.get_uninstall_msi(notify_handler).map(Uninstaller::Msi)
			)
	}
	pub fn uninstall(&self, notify_handler: &NotifyHandler) -> Result<()> {
		if self.is_installed_here() {
			match self.install_type {
				InstallType::Owned => {
					utils::remove_dir("install", &self.path, notify_handler)
				},
				InstallType::Shared => {
					if let Some(uninstaller) = self.get_uninstaller(notify_handler) {
						uninstaller.run()
					} else {
						Err(Error::NotInstalledHere)
					}
				},
			}
		} else {
			Err(Error::NotInstalledHere)
		}
	}
	pub fn install(&self, method: InstallMethod, notify_handler: &NotifyHandler) -> Result<()> {
		method.run(self, notify_handler)
	}

	pub fn with_ldpath<T, F: FnOnce() -> Result<T>>(&self, f: F) -> Result<T> {
		let new_path = self.path.join("lib");

		env_var::with_path("LD_LIBRARY_PATH", &new_path, || {
			env_var::with_path("DYLD_LIBRARY_PATH", &new_path, || {
				f()
			})
		})
	}

	pub fn with_env<T, F: FnOnce() -> Result<T>>(&self, f: F) -> Result<T> {
		let cargo_path = self.path.join("cargo");

		self.with_ldpath(|| {
			env_var::with_default("CARGO_HOME", cargo_path.as_ref(), || {
				f()
			})
		})
	}

	pub fn create_command(&self, binary: &str) -> Result<Command> {
		let binary_path = self.binary_file(binary);

		self.with_env(|| Ok(Command::new(binary_path)))
	}

	pub fn open_docs(&self, relative: &str) -> Result<()> {
		utils::open_browser(&try!(self.doc_path(relative)))
	}
}
<|endoftext|>


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

//! Support code for encoding and decoding types.

/*
Core encoding and decoding interfaces.
*/

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       html_playground_url = "https://play.rust-lang.org/",
       test(attr(allow(unused_variables), deny(warnings))))]

#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(specialization)]
#![feature(never_type)]
#![cfg_attr(test, feature(test))]

pub use self::serialize::{Decoder, Encoder, Decodable, Encodable};

pub use self::serialize::{SpecializationError, SpecializedEncoder, SpecializedDecoder};
pub use self::serialize::{UseSpecializedEncodable, UseSpecializedDecodable};

mod serialize;
mod collection_impls;

pub mod hex;
pub mod json;

pub mod opaque;
pub mod leb128;

mod rustc_serialize {
    pub use serialize::*;
}
<commit_msg>[nll] libserialize: enable feature(nll) for bootstrap<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Support code for encoding and decoding types.

/*
Core encoding and decoding interfaces.
*/

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       html_playground_url = "https://play.rust-lang.org/",
       test(attr(allow(unused_variables), deny(warnings))))]

#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(specialization)]
#![feature(never_type)]
#![cfg_attr(not(stage0), feature(nll))]
#![cfg_attr(test, feature(test))]

pub use self::serialize::{Decoder, Encoder, Decodable, Encodable};

pub use self::serialize::{SpecializationError, SpecializedEncoder, SpecializedDecoder};
pub use self::serialize::{UseSpecializedEncodable, UseSpecializedDecodable};

mod serialize;
mod collection_impls;

pub mod hex;
pub mod json;

pub mod opaque;
pub mod leb128;

mod rustc_serialize {
    pub use serialize::*;
}
<|endoftext|>


<commit_before><commit_msg>Added the benches<commit_after>#![feature(test)]

extern crate noritama;
extern crate test;

use noritama::flaker::*;

use test::Bencher;

fn flaker() -> Flaker {
    Flaker::new().unwrap()
}

#[bench]
fn gen(b: &mut Bencher) {
    let c: Flaker = flaker();
    b.iter(|| {
        c.id().unwrap()
    });
}

<|endoftext|>


<commit_before><commit_msg>Add problem #48<commit_after>fn pow_mod(base: uint, exponent: uint, modulo: uint) -> uint {
    if base == 0 { return 0; }
    let mut acc = 1;
    for exponent.times {
        acc = (acc * base) % modulo;
    }
    return acc;
}

fn main() {
    let modulo  = 100_0000_0000;
    let mut sum = 0;
    for uint::range(1, 1000 + 1) |n| {
        sum = (sum + pow_mod(n, n, modulo)) % modulo;
    }
    io::println(fmt!("%u", sum));
}
<|endoftext|>


<commit_before><commit_msg>Add xfail'd test for default methods.<commit_after>//xfail-test

trait Cat {
    fn meow() -> bool;
    fn scratch() -> bool;
    fn purr() -> bool { true }
}

impl int : Cat {
    fn meow() -> bool {
        self.scratch()
    }
    fn scratch() -> bool {
        self.purr()
    }
}

fn main() {
    assert 5.meow();
}
<|endoftext|>


<commit_before><commit_msg>Add test case<commit_after>extern crate lettre_email;
extern crate lettre;
use lettre_email::EmailBuilder;
use lettre::{EmailAddress, Envelope};

#[test]
fn build_with_envelope_test() {
    let e = Envelope::new(
        Some(EmailAddress::new("from@example.org".to_string()).unwrap()),
        vec![EmailAddress::new("to@example.org".to_string()).unwrap()],
    ).unwrap();
    let _email = EmailBuilder::new()
        .envelope(e)
        .subject("subject")
        .text("message")
        .build()
        .unwrap();
}<|endoftext|>


<commit_before><commit_msg>add test<commit_after><|endoftext|>


<commit_before>// A pass that annotates for each loops and functions with the free
// variables that they contain.

import std::map;
import std::map::*;
import std::ivec;
import std::option;
import std::int;
import std::option::*;
import syntax::ast;
import syntax::visit;
import driver::session;
import middle::resolve;
import syntax::codemap::span;

export annotate_freevars;
export freevar_set;
export freevar_map;
export get_freevar_info;
export get_freevars;
export get_freevar_uses;
export has_freevars;
export is_freevar_of;
export def_lookup;

type freevar_set = hashset[ast::node_id];
type freevar_info = rec(freevar_set defs, @ast::node_id[] uses);
type freevar_map = hashmap[ast::node_id, freevar_info];

// Searches through part of the AST for all references to locals or
// upvars in this frame and returns the list of definition IDs thus found.
// Since we want to be able to collect upvars in some arbitrary piece
// of the AST, we take a walker function that we invoke with a visitor
// in order to start the search.
fn collect_freevars(&resolve::def_map def_map, &session::session sess,
                    &fn (&visit::vt[()]) walker,
                    ast::node_id[] initial_decls) -> freevar_info {
    type env =
        @rec(mutable ast::node_id[] refs,
             hashset[ast::node_id] decls,
             resolve::def_map def_map,
             session::session sess);

    fn walk_fn(env e, &ast::_fn f, &ast::ty_param[] tps, &span sp,
               &ast::fn_ident i, ast::node_id nid) {
        for (ast::arg a in f.decl.inputs) { e.decls.insert(a.id, ()); }
    }
    fn walk_expr(env e, &@ast::expr expr) {
        alt (expr.node) {
            case (ast::expr_path(?path)) {
                if (! e.def_map.contains_key(expr.id)) {
                    e.sess.span_fatal(expr.span,
                       "internal error in collect_freevars");
                }
                alt (e.def_map.get(expr.id)) {
                    case (ast::def_arg(?did)) { e.refs += ~[expr.id]; }
                    case (ast::def_local(?did)) { e.refs += ~[expr.id]; }
                    case (ast::def_binding(?did)) { e.refs += ~[expr.id]; }
                    case (_) { /* no-op */ }
                }
            }
            case (_) { }
        }
    }
    fn walk_local(env e, &@ast::local local) {
        set_add(e.decls, local.node.id);
    }
    fn walk_pat(env e, &@ast::pat p) {
        alt (p.node) {
            case (ast::pat_bind(_)) {
                set_add(e.decls, p.id);
            }
            case (_) {}
        }
    }
    let hashset[ast::node_id] decls = new_int_hash();
    for (ast::node_id decl in initial_decls) { set_add(decls, decl); }

    let env e = @rec(mutable refs=~[],
                     decls=decls,
                     def_map=def_map,
                     sess=sess);
    walker(visit::mk_simple_visitor(
        @rec(visit_local=bind walk_local(e, _),
             visit_pat=bind walk_pat(e, _),
             visit_expr=bind walk_expr(e, _),
             visit_fn=bind walk_fn(e, _, _, _, _, _)
             with *visit::default_simple_visitor())));

    // Calculate (refs - decls). This is the set of captured upvars.
    // We build a vec of the node ids of the uses and a set of the
    // node ids of the definitions.
    auto uses = ~[];
    auto defs = new_int_hash();
    for (ast::node_id ref_id_ in e.refs) {
        auto ref_id = ref_id_;
        auto def_id = ast::def_id_of_def(def_map.get(ref_id)).node;
        if !decls.contains_key(def_id) {
            uses += ~[ref_id];
            set_add(defs, def_id);
        }
    }
    ret rec(defs=defs, uses=@uses);
}

// Build a map from every function and for-each body to a set of the
// freevars contained in it. The implementation is not particularly
// efficient as it fully recomputes the free variables at every
// node of interest rather than building up the free variables in
// one pass. This could be improved upon if it turns out to matter.
fn annotate_freevars(&session::session sess, &resolve::def_map def_map,
                     &@ast::crate crate) -> freevar_map {
    type env =
        rec(freevar_map freevars,
            resolve::def_map def_map,
            session::session sess);

    fn walk_fn(env e, &ast::_fn f, &ast::ty_param[] tps, &span sp,
               &ast::fn_ident i, ast::node_id nid) {
        auto walker = bind visit::visit_fn(f, tps, sp, i, nid, (), _);
        auto vars = collect_freevars(e.def_map, e.sess, walker, ~[]);
        e.freevars.insert(nid, vars);
    }
    fn walk_expr(env e, &@ast::expr expr) {
        alt (expr.node) {
            ast::expr_for_each(?local, _, ?body) {
                auto vars = collect_freevars
                    (e.def_map, e.sess, bind visit::visit_block(body, (), _),
                     ~[local.node.id]);
                e.freevars.insert(body.node.id, vars);
            }
            _ {}
        }
    }

    let env e =
        rec(freevars = new_int_hash(), def_map=def_map, sess=sess);
    auto visitor = visit::mk_simple_visitor
        (@rec(visit_fn=bind walk_fn(e, _, _, _, _, _),
              visit_expr=bind walk_expr(e, _)
              with *visit::default_simple_visitor()));
    visit::visit_crate(*crate, (), visitor);

    ret e.freevars;
}

fn get_freevar_info(&ty::ctxt tcx, ast::node_id fid) -> freevar_info {
    alt (tcx.freevars.find(fid)) {
        none {
            fail "get_freevars: " + int::str(fid) + " has no freevars";
        }
        some(?d) { ret d; }
    }
}
fn get_freevars(&ty::ctxt tcx, ast::node_id fid) -> freevar_set {
    ret get_freevar_info(tcx, fid).defs;
}
fn get_freevar_uses(&ty::ctxt tcx, ast::node_id fid) -> @ast::node_id[] {
    ret get_freevar_info(tcx, fid).uses;
}
fn has_freevars(&ty::ctxt tcx, ast::node_id fid) -> bool {
    ret get_freevars(tcx, fid).size() != 0u;
}
fn is_freevar_of(&ty::ctxt tcx, ast::node_id var, ast::node_id f) -> bool {
    ret get_freevars(tcx, f).contains_key(var);
}
fn def_lookup(&ty::ctxt tcx, ast::node_id f, ast::node_id id) ->
    option::t[ast::def] {
    alt (tcx.def_map.find(id)) {
      none { ret none; }
      some(?d) {
        auto did = ast::def_id_of_def(d);
        if is_freevar_of(tcx, did.node, f) {
            ret some(ast::def_upvar(did, @d));
        } else { ret some(d); }
      }
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Fix the freevars pass to actually work on top of visit.<commit_after>// A pass that annotates for each loops and functions with the free
// variables that they contain.

import std::map;
import std::map::*;
import std::ivec;
import std::option;
import std::int;
import std::option::*;
import syntax::ast;
import syntax::visit;
import driver::session;
import middle::resolve;
import syntax::codemap::span;

export annotate_freevars;
export freevar_set;
export freevar_map;
export get_freevar_info;
export get_freevars;
export get_freevar_uses;
export has_freevars;
export is_freevar_of;
export def_lookup;

type freevar_set = hashset[ast::node_id];
type freevar_info = rec(freevar_set defs, @ast::node_id[] uses);
type freevar_map = hashmap[ast::node_id, freevar_info];

// Searches through part of the AST for all references to locals or
// upvars in this frame and returns the list of definition IDs thus found.
// Since we want to be able to collect upvars in some arbitrary piece
// of the AST, we take a walker function that we invoke with a visitor
// in order to start the search.
fn collect_freevars(&resolve::def_map def_map, &session::session sess,
                    &fn (&visit::vt[()]) walker,
                    ast::node_id[] initial_decls) -> freevar_info {
    type env =
        @rec(mutable ast::node_id[] refs,
             hashset[ast::node_id] decls,
             resolve::def_map def_map,
             session::session sess);

    fn walk_fn(env e, &ast::_fn f, &ast::ty_param[] tps, &span sp,
               &ast::fn_ident i, ast::node_id nid) {
        for (ast::arg a in f.decl.inputs) { e.decls.insert(a.id, ()); }
    }
    fn walk_expr(env e, &@ast::expr expr) {
        alt (expr.node) {
            case (ast::expr_path(?path)) {
                if (! e.def_map.contains_key(expr.id)) {
                    e.sess.span_fatal(expr.span,
                       "internal error in collect_freevars");
                }
                alt (e.def_map.get(expr.id)) {
                    case (ast::def_arg(?did)) { e.refs += ~[expr.id]; }
                    case (ast::def_local(?did)) { e.refs += ~[expr.id]; }
                    case (ast::def_binding(?did)) { e.refs += ~[expr.id]; }
                    case (_) { /* no-op */ }
                }
            }
            case (_) { }
        }
    }
    fn walk_local(env e, &@ast::local local) {
        set_add(e.decls, local.node.id);
    }
    fn walk_pat(env e, &@ast::pat p) {
        alt (p.node) {
            case (ast::pat_bind(_)) {
                set_add(e.decls, p.id);
            }
            case (_) {}
        }
    }
    let hashset[ast::node_id] decls = new_int_hash();
    for (ast::node_id decl in initial_decls) { set_add(decls, decl); }

    let env e = @rec(mutable refs=~[],
                     decls=decls,
                     def_map=def_map,
                     sess=sess);
    walker(visit::mk_simple_visitor(
        @rec(visit_local=bind walk_local(e, _),
             visit_pat=bind walk_pat(e, _),
             visit_expr=bind walk_expr(e, _),
             visit_fn=bind walk_fn(e, _, _, _, _, _)
             with *visit::default_simple_visitor())));

    // Calculate (refs - decls). This is the set of captured upvars.
    // We build a vec of the node ids of the uses and a set of the
    // node ids of the definitions.
    auto uses = ~[];
    auto defs = new_int_hash();
    for (ast::node_id ref_id_ in e.refs) {
        auto ref_id = ref_id_;
        auto def_id = ast::def_id_of_def(def_map.get(ref_id)).node;
        if !decls.contains_key(def_id) {
            uses += ~[ref_id];
            set_add(defs, def_id);
        }
    }
    ret rec(defs=defs, uses=@uses);
}

// Build a map from every function and for-each body to a set of the
// freevars contained in it. The implementation is not particularly
// efficient as it fully recomputes the free variables at every
// node of interest rather than building up the free variables in
// one pass. This could be improved upon if it turns out to matter.
fn annotate_freevars(&session::session sess, &resolve::def_map def_map,
                     &@ast::crate crate) -> freevar_map {
    type env =
        rec(freevar_map freevars,
            resolve::def_map def_map,
            session::session sess);

    fn walk_fn(env e, &ast::_fn f, &ast::ty_param[] tps, &span sp,
               &ast::fn_ident i, ast::node_id nid) {
        fn start_walk(&ast::_fn f, &ast::ty_param[] tps, &span sp,
                      &ast::fn_ident i, ast::node_id nid, &visit::vt[()] v) {
            v.visit_fn(f, tps, sp, i, nid, (), v);
        }
        auto walker = bind start_walk(f, tps, sp, i, nid, _);
        auto vars = collect_freevars(e.def_map, e.sess, walker, ~[]);
        e.freevars.insert(nid, vars);
    }
    fn walk_expr(env e, &@ast::expr expr) {
        alt (expr.node) {
            ast::expr_for_each(?local, _, ?body) {
                fn start_walk(&ast::blk b, &visit::vt[()] v) {
                    v.visit_block(b, (), v);
                }
                auto vars = collect_freevars
                    (e.def_map, e.sess, bind start_walk(body, _),
                     ~[local.node.id]);
                e.freevars.insert(body.node.id, vars);
            }
            _ {}
        }
    }

    let env e =
        rec(freevars = new_int_hash(), def_map=def_map, sess=sess);
    auto visitor = visit::mk_simple_visitor
        (@rec(visit_fn=bind walk_fn(e, _, _, _, _, _),
              visit_expr=bind walk_expr(e, _)
              with *visit::default_simple_visitor()));
    visit::visit_crate(*crate, (), visitor);

    ret e.freevars;
}

fn get_freevar_info(&ty::ctxt tcx, ast::node_id fid) -> freevar_info {
    alt (tcx.freevars.find(fid)) {
        none {
            fail "get_freevars: " + int::str(fid) + " has no freevars";
        }
        some(?d) { ret d; }
    }
}
fn get_freevars(&ty::ctxt tcx, ast::node_id fid) -> freevar_set {
    ret get_freevar_info(tcx, fid).defs;
}
fn get_freevar_uses(&ty::ctxt tcx, ast::node_id fid) -> @ast::node_id[] {
    ret get_freevar_info(tcx, fid).uses;
}
fn has_freevars(&ty::ctxt tcx, ast::node_id fid) -> bool {
    ret get_freevars(tcx, fid).size() != 0u;
}
fn is_freevar_of(&ty::ctxt tcx, ast::node_id var, ast::node_id f) -> bool {
    ret get_freevars(tcx, f).contains_key(var);
}
fn def_lookup(&ty::ctxt tcx, ast::node_id f, ast::node_id id) ->
    option::t[ast::def] {
    alt (tcx.def_map.find(id)) {
      none { ret none; }
      some(?d) {
        auto did = ast::def_id_of_def(d);
        if is_freevar_of(tcx, did.node, f) {
            ret some(ast::def_upvar(did, @d));
        } else { ret some(d); }
      }
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>Rewrite from TcpStream to lazy-socket<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor(logging): prefer the term "local" to "native" in messages<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor(core): terminate terminate() and TerminateReason<commit_after><|endoftext|>


<commit_before><commit_msg>Added post ID querying.<commit_after><|endoftext|>


<commit_before><commit_msg>Parse/print basic ROM info<commit_after><|endoftext|>


<commit_before><commit_msg>Added Socket Shutdown to avoid hanging Connections<commit_after><|endoftext|>


<commit_before><commit_msg>	modified:   src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>help text<commit_after><|endoftext|>


<commit_before><commit_msg>start on lnp flags/prettyprint<commit_after><|endoftext|>


<commit_before><commit_msg>Print test lines<commit_after><|endoftext|>


<commit_before><commit_msg>Added timing and let tests run 100 times<commit_after><|endoftext|>


<commit_before><commit_msg>Add home page link and title to navigation<commit_after><|endoftext|>


<commit_before><commit_msg>minor changes.<commit_after><|endoftext|>


<commit_before><commit_msg>Actually committing type database.<commit_after>// Copyright 2020 Google LLC
//
// 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
//
//    https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::TypeName;
use lazy_static::lazy_static;
use std::collections::HashMap;

#[derive(Debug)]
pub(crate) struct TypeDetails {
    /// Substitutions from the names constructed by bindgen into those
    /// which cxx uses.
    pub(crate) cxx_replacement: Option<TypeName>,
    /// C++ equivalent name for a Rust type.
    pub(crate) cxx_name: Option<String>,
}

impl TypeDetails {
    fn new(cxx_replacement: Option<TypeName>, cxx_name: Option<String>) -> Self {
        TypeDetails {
            cxx_replacement,
            cxx_name,
        }
    }
}

lazy_static! {
    pub(crate) static ref KNOWN_TYPES: HashMap<TypeName, TypeDetails> = {
        let mut map = HashMap::new();
        map.insert(
            TypeName::new("std_unique_ptr"),
            TypeDetails::new(Some(TypeName::new("UniquePtr")), None),
        );
        map.insert(
            TypeName::new("std_string"),
            TypeDetails::new(Some(TypeName::new("CxxString")), None),
        );
        for (cpp_type, rust_type) in (3..7)
            .map(|x| 2i32.pow(x))
            .map(|x| {
                vec![
                    (format!("uint{}_t", x), format!("u{}", x)),
                    (format!("int{}_t", x), format!("i{}", x)),
                ]
            })
            .flatten()
        {
            map.insert(
                TypeName::new(&rust_type),
                TypeDetails::new(None, Some(cpp_type)),
            );
        }
        map
    };
}

#[cfg(test)]
mod tests {
    use crate::TypeName;

    #[test]
    fn test_ints() {
        assert_eq!(
            super::KNOWN_TYPES
                .get(&TypeName::new("i8"))
                .unwrap()
                .cxx_name
                .as_ref()
                .unwrap(),
            "int8_t"
        );
        assert_eq!(
            super::KNOWN_TYPES
                .get(&TypeName::new("u64"))
                .unwrap()
                .cxx_name
                .as_ref()
                .unwrap(),
            "uint64_t"
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Show we handle a lack of common stations.<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added new examples using logging function<commit_after>//! Example of using urlencoded
extern crate iron;
extern crate urlencoded;

use std::io::net::ip::Ipv4Addr;

use iron::{Iron, ServerT, Request, Response, Alloy};

use urlencoded::{UrlEncoded, Encoded};

// urlencoded returns a Hashmap
// Here we create a function to log the hashmap we are storing in Alloy.
// Alloy is where your middleware can store data and we access it through
// the `find` API exposed by alloy.
fn log_hashmap(req: &mut Request, res: &mut Response, alloy: &mut Alloy) {
    let hashmap = alloy.find::<Encoded>();
    match hashmap {
        Some(&Encoded(ref encoded)) => println!("Url Encoded:\n {}", encoded),
        None => ()
    }
}

// test out the server with `curl -i "127.0.0.1:3000/?name=franklin&name=trevor"`
fn main() {
    let mut server: ServerT = Iron::new();
    server.link(UrlEncoded::new());
    server.link(log_hashmap);
    server.listen(Ipv4Addr(127, 0, 0, 1), 3000);
}
<|endoftext|>


<commit_before><commit_msg>Add regression test.<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.

::foo::bar!(); //~ ERROR expected macro name without module separators
foo::bar!(); //~ ERROR expected macro name without module separators

trait T {
    foo::bar!(); //~ ERROR expected macro name without module separators
    ::foo::bar!(); //~ ERROR expected macro name without module separators
}

struct S {
    x: foo::bar!(), //~ ERROR expected macro name without module separators
    y: ::foo::bar!(), //~ ERROR expected macro name without module separators
}

impl S {
    foo::bar!(); //~ ERROR expected macro name without module separators
    ::foo::bar!(); //~ ERROR expected macro name without module separators
}

fn main() {
    foo::bar!(); //~ ERROR expected macro name without module separators
    ::foo::bar!(); //~ ERROR expected macro name without module separators

    let _ = foo::bar!(); //~ ERROR expected macro name without module separators
    let _ = ::foo::bar!(); //~ ERROR expected macro name without module separators

    let foo::bar!() = 0; //~ ERROR expected macro name without module separators
    let ::foo::bar!() = 0; //~ ERROR expected macro name without module separators
}
<|endoftext|>


<commit_before>// Copyright 2016 Google Inc. All rights reserved.
//
// 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.

//! The main library for xi-core.

extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate time;
extern crate syntect;
extern crate toml;
extern crate notify;

#[cfg(feature = "ledger")]
extern crate fuchsia_zircon;
#[cfg(feature = "ledger")]
extern crate fuchsia_zircon_sys;
#[cfg(feature = "ledger")]
extern crate mxruntime;
#[cfg(feature = "ledger")]
#[macro_use]
extern crate fidl;
#[cfg(feature = "ledger")]
extern crate apps_ledger_services_public;

#[cfg(feature = "ledger")]
extern crate sha2;

use serde_json::Value;

pub mod rpc;

/// Internal data structures and logic.
///
/// These internals are not part of the public API (for the purpose of binding to
/// a front-end), but are exposed here, largely so they appear in documentation.
#[path=""]
pub mod internal {
    pub mod tabs;
    pub mod editor;
    pub mod view;
    pub mod linewrap;
    pub mod plugins;
    #[cfg(feature = "ledger")]
    pub mod fuchsia;
    pub mod styles;
    pub mod word_boundaries;
    pub mod index_set;
    pub mod selection;
    pub mod movement;
    pub mod syntax;
    pub mod layers;
    pub mod config;
    pub mod watcher;
    pub mod line_cache_shadow;
}

pub use plugins::rpc as plugin_rpc;
pub use plugins::PluginPid;
pub use tabs::ViewIdentifier;
pub use syntax::SyntaxDefinition;
pub use config::{BufferItems as BufferConfig, Table as ConfigTable};

use internal::tabs;
use internal::editor;
use internal::view;
use internal::linewrap;
use internal::plugins;
use internal::styles;
use internal::word_boundaries;
use internal::index_set;
use internal::selection;
use internal::movement;
use internal::syntax;
use internal::layers;
use internal::config;
use internal::watcher;
use internal::line_cache_shadow;
#[cfg(feature = "ledger")]
use internal::fuchsia;

use tabs::{Documents, BufferContainerRef};
use rpc::{CoreNotification, CoreRequest};

#[cfg(feature = "ledger")]
use apps_ledger_services_public::Ledger_Proxy;

extern crate xi_rope;
extern crate xi_unicode;
extern crate xi_rpc;

use xi_rpc::{RpcPeer, RpcCtx, Handler, RemoteError};

pub type MainPeer = RpcPeer;

pub struct MainState {
    tabs: Documents,
}

impl MainState {
    pub fn new() -> Self {
        MainState {
            tabs: Documents::new(),
        }
    }

    /// Returns a copy of the `BufferContainerRef`.
    ///
    /// This is exposed for testing purposes only.
    #[doc(hidden)]
    pub fn _get_buffers(&self) -> BufferContainerRef {
        self.tabs._get_buffers()
    }

    #[cfg(feature = "ledger")]
    pub fn set_ledger(&mut self, ledger: Ledger_Proxy, session_id: (u64, u32)) {
        self.tabs.setup_ledger(ledger, session_id);
    }
}

impl Handler for MainState {
    type Notification = CoreNotification;
    type Request = CoreRequest;

    fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {
        self.tabs.handle_notification(rpc, ctx)
    }

    fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request)
                      -> Result<Value, RemoteError> {
        self.tabs.handle_request(rpc, ctx)
    }

    fn idle(&mut self, _ctx: &RpcCtx, token: usize) {
        self.tabs.handle_idle(token);
    }
}
<commit_msg>Cleaner cfg, suggested in review<commit_after>// Copyright 2016 Google Inc. All rights reserved.
//
// 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.

//! The main library for xi-core.

extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate time;
extern crate syntect;
extern crate toml;
extern crate notify;

#[cfg(feature = "ledger")]
mod ledger_includes {
    extern crate fuchsia_zircon;
    extern crate fuchsia_zircon_sys;
    extern crate mxruntime;
    #[macro_use]
    extern crate fidl;
    extern crate apps_ledger_services_public;
    extern crate sha2;
}
#[cfg(feature = "ledger")]
use ledger_includes::*;

use serde_json::Value;

pub mod rpc;

/// Internal data structures and logic.
///
/// These internals are not part of the public API (for the purpose of binding to
/// a front-end), but are exposed here, largely so they appear in documentation.
#[path=""]
pub mod internal {
    pub mod tabs;
    pub mod editor;
    pub mod view;
    pub mod linewrap;
    pub mod plugins;
    #[cfg(feature = "ledger")]
    pub mod fuchsia;
    pub mod styles;
    pub mod word_boundaries;
    pub mod index_set;
    pub mod selection;
    pub mod movement;
    pub mod syntax;
    pub mod layers;
    pub mod config;
    pub mod watcher;
    pub mod line_cache_shadow;
}

pub use plugins::rpc as plugin_rpc;
pub use plugins::PluginPid;
pub use tabs::ViewIdentifier;
pub use syntax::SyntaxDefinition;
pub use config::{BufferItems as BufferConfig, Table as ConfigTable};

use internal::tabs;
use internal::editor;
use internal::view;
use internal::linewrap;
use internal::plugins;
use internal::styles;
use internal::word_boundaries;
use internal::index_set;
use internal::selection;
use internal::movement;
use internal::syntax;
use internal::layers;
use internal::config;
use internal::watcher;
use internal::line_cache_shadow;
#[cfg(feature = "ledger")]
use internal::fuchsia;

use tabs::{Documents, BufferContainerRef};
use rpc::{CoreNotification, CoreRequest};

#[cfg(feature = "ledger")]
use apps_ledger_services_public::Ledger_Proxy;

extern crate xi_rope;
extern crate xi_unicode;
extern crate xi_rpc;

use xi_rpc::{RpcPeer, RpcCtx, Handler, RemoteError};

pub type MainPeer = RpcPeer;

pub struct MainState {
    tabs: Documents,
}

impl MainState {
    pub fn new() -> Self {
        MainState {
            tabs: Documents::new(),
        }
    }

    /// Returns a copy of the `BufferContainerRef`.
    ///
    /// This is exposed for testing purposes only.
    #[doc(hidden)]
    pub fn _get_buffers(&self) -> BufferContainerRef {
        self.tabs._get_buffers()
    }

    #[cfg(feature = "ledger")]
    pub fn set_ledger(&mut self, ledger: Ledger_Proxy, session_id: (u64, u32)) {
        self.tabs.setup_ledger(ledger, session_id);
    }
}

impl Handler for MainState {
    type Notification = CoreNotification;
    type Request = CoreRequest;

    fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {
        self.tabs.handle_notification(rpc, ctx)
    }

    fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request)
                      -> Result<Value, RemoteError> {
        self.tabs.handle_request(rpc, ctx)
    }

    fn idle(&mut self, _ctx: &RpcCtx, token: usize) {
        self.tabs.handle_idle(token);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add rust code for binary-search project<commit_after>fn binary_serch(list: &[u32], key: u32, base: usize) -> Option<usize> {
    let upper = list.len();

    match upper {
        0 => None,
        1 => if list[0] == key {
            Some(base)
        } else {
            None
        },
        _ => {
            let needle = upper / 2;
            let middle = list[needle];

            if key > middle {
                binary_serch(&list[needle..], key, base + needle)
            } else if key < middle {
                binary_serch(&list[..needle], key, base)
            } else {
                Some(base + needle)
            }
        }
    }
}

pub fn find(list: &[u32], key: u32) -> Option<usize> {
    binary_serch(list, key, 0)
}
<|endoftext|>


<commit_before><commit_msg>Rust: 100 doors<commit_after>fn main() {
    let mut doors = vec![false; 100];

    for i in 0..100 {
        let mut j = i;
        while j < 100 {
            doors[j] = !doors[j];
            j += i + 1;
        }
    }

    for i in 0..100 {
        if doors[i] {
            println!("Door {} is open", i + 1);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Init smarter actor<commit_after>use std::collections::HashMap;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::sync::mpsc::TryRecvError;
use std::sync::{Arc, Mutex};
use std::old_io::timer;
use std::time::Duration;

use messages::{ActorMessages, TransactionRequest, MarketMessages, MarketHistory};
use messages::ActorMessages::{StockRequest, MoneyRequest, CommitTransaction, AbortTransaction, History, Time};
use messages::MarketMessages::{SellRequest, Commit, Cancel, RegisterActor, MatchRequest};
use actor::Actor;

// Smarter actor
// (monitors price last sold at and put a sell request if any stocks are above their purchase price)

pub fn start_smarter_actor(actor_id: usize, existing_markets: HashMap<usize, Sender<MarketMessages>>, actor_tx: Sender<ActorMessages>, actor_rx: Receiver<ActorMessages>) {
  println!("Starting Actor {}", actor_id);
  let mut init_history = false;
  let mut actor = Actor { id: actor_id,
                          money: 100,
                          stocks: HashMap::new(),
                          pending_money: 0,
                          pending_stock: (0, 0),
                          markets: existing_markets,
                          history: Arc::new(Mutex::new(MarketHistory {history: HashMap::new()}))};

  for (_, market_tx) in actor.markets.iter() {
    market_tx.send(RegisterActor(actor.id, actor_tx.clone())).unwrap();
  }

  loop {
    //Logic
    let mark_clone = actor.markets.clone();
    let stock_clone = actor.stocks.clone();

    match actor_rx.try_recv() {
      Ok(message) => {
          match message {
            StockRequest(stock_request) => {
              println!("Started Stock Request in smarter_actor {}", actor.id);
              let market_tx;
              let tx_text = mark_clone.get(&stock_request.market_id);
              match tx_text {
                Some(tx) => {
                  market_tx = tx;
                },
                None => {
                  return; //HOW DID WE GET A MISSING MARKET?
                }
              }
              if has_pending_transaction(&actor) {
                market_tx.send(Cancel(actor.id)).unwrap();
              }
              else {
                //if we have the stock. set it aside.
                let stock_id = stock_request.stock_id;
                let quantity = stock_request.quantity;
                let stock = stock_clone.get(&stock_id);
                match stock {
                  Some(owned_quantity) => {
                    if *owned_quantity >= quantity {
                      remove_stock(&mut actor, (stock_id, quantity));
                      actor.pending_stock = (stock_id, quantity);
                      market_tx.send(Commit(actor.id)).unwrap();
                    }
                    else {
                      market_tx.send(Cancel(actor.id)).unwrap();
                    }
                  },
                  None => {
                    market_tx.send(Cancel(actor.id)).unwrap();
                  }
                }
              }
              print_status(&actor);
              },
            MoneyRequest(money_request) => {
              let market_tx;
              let tx_text = actor.markets.get(&money_request.market_id);
              match tx_text {
                Some(tx) => {
                  market_tx = tx;
                },
                None => {
                  return; //HOW DID WE GET A MISSING MARKET?
                }
              }
              if has_pending_transaction(&actor) {
                market_tx.send(Cancel(actor.id)).unwrap();
              }
              else {
                //if we have the money. set it aside.
                if actor.money >= money_request.amount {
                  actor.money = actor.money - money_request.amount;
                  actor.pending_money = money_request.amount;
                  market_tx.send(Commit(actor.id)).unwrap();
                }
                else {
                  market_tx.send(Cancel(actor.id)).unwrap();
                }
              }
              print_status(&actor);
              },
            CommitTransaction(commit_transaction_request) => {
              //if we have money pending, then look up the stock id and add that quantity purchased.
              //remove the pending money
              if actor.pending_money > 0 {
                let price_per_unit = commit_transaction_request.price;
                let units = commit_transaction_request.quantity;
                let leftover_money = actor.pending_money - price_per_unit * units;

                //make a function for adding stock.
                add_stock(&mut actor, (commit_transaction_request.stock_id, units));
                actor.money = actor.money + leftover_money;

                actor.pending_money = 0;
              }

              //if we have stock pending, look up the quantity purchased and add the money.
              //remove the pending stock
              if actor.pending_stock.1 > 0 {
                let money = commit_transaction_request.price * commit_transaction_request.quantity;
                let restore_stock = (commit_transaction_request.stock_id, actor.pending_stock.1 - commit_transaction_request.quantity);
                if restore_stock.1 > 0 {
                  add_stock(&mut actor, restore_stock);
                }
                actor.money = actor.money + money;
                actor.pending_stock = (0,0);
              }
              println!("After a committed transaction in smarter_actor {} ", actor.id);
              print_status(&actor);
              },
            AbortTransaction => {
              //move pending stock back into stocks.
              if actor.pending_stock.1 != 0 {
                let pending_stock_clone = actor.pending_stock.clone();
                add_stock(&mut actor, pending_stock_clone);
                //now that we have moved it. Clear out the pending stock.
                actor.pending_stock = (0,0); //setting the quantity to zero clears it.
              }
              for (stock_id, quantity) in actor.stocks.iter() {
                println!("After aborting the transaction, smarter_actor {} now has StockId: {} Quantity: {}", actor.id, *stock_id, *quantity);
              }

              //move pending money back into money.
              if actor.pending_money > 0 {
                actor.money = actor.money + actor.pending_money;
                actor.pending_money = 0;
              }
              println!("After aborting the transaction, smarter_actor {} now has {} money.", actor.id, actor.money);
            },
            History(history) => {
              println!("Smarter_actor {} received history {}", actor.id, *(history.lock().unwrap()));
              actor.history = history;
              init_history = true;},
            Time(current, max) => {
              println!("Smarter_actor {} received time {}", actor.id, current);
            }
          }
        },
      Err(TryRecvError::Empty) => {timer::sleep(Duration::milliseconds(10));},
      Err(TryRecvError::Disconnected) => {println!("ERROR: Smarter_actor {} disconnected", actor.id);}
    }
  }
}

fn add_stock(actor: &mut Actor, stock_to_add: (usize, usize)) {
  let stock_clone = actor.stocks.clone();
  let held_stock = stock_clone.get(&stock_to_add.0);
  match held_stock {
    Some(stock_count) => {
        //we have some stock. We need to add to our reserve.
        actor.stocks.insert(stock_to_add.0, stock_to_add.1 + *stock_count);
      },
    None => {
      //we don't have any stock left. Just add it back.
      actor.stocks.insert(stock_to_add.0, stock_to_add.1);
    }
  }
}

fn remove_stock(actor: &mut Actor, stock_to_remove: (usize, usize)) {
  let stock_clone = actor.stocks.clone();
  let held_stock = stock_clone.get(&stock_to_remove.0);
  match held_stock {
    Some(stock_count) => {
        //we have some stock. We need to add to our reserve.
        actor.stocks.insert(stock_to_remove.0, *stock_count - stock_to_remove.1);
      },
    None => {} //TODO Should we error handle here?
  }
}

fn print_status(actor: &Actor) {
  for (stock_id, quantity) in (*actor).stocks.iter() {
    println!("Actor {} now has StockId: {} Quantity: {}", (*actor).id, *stock_id, *quantity);
  }
  println!("Actor {} has {} money.", (*actor).id, (*actor).money);
}

fn has_pending_transaction(actor: &Actor) -> bool {
  (*actor).pending_money > 0 || (*actor).pending_stock.1 > 0
}
<|endoftext|>


<commit_before><commit_msg>rustdoc: Add test for mixing doc comments and attrs<commit_after>#![crate_name = "foo"]

// @has 'foo/struct.S1.html'
// @count - '//details[@class="rustdoc-toggle top-doc"]/div[@class="docblock"]/p' \
//     1
// @has - '//details[@class="rustdoc-toggle top-doc"]/div[@class="docblock"]/p[1]' \
//     'Hello world! Goodbye! Hello again!'

#[doc = "Hello world!\n\n"]
/// Goodbye!
#[doc = "  Hello again!\n"]
pub struct S1;

// @has 'foo/struct.S2.html'
// @count - '//details[@class="rustdoc-toggle top-doc"]/div[@class="docblock"]/p' \
//     2
// @has - '//details[@class="rustdoc-toggle top-doc"]/div[@class="docblock"]/p[1]' \
//     'Hello world!'
// @has - '//details[@class="rustdoc-toggle top-doc"]/div[@class="docblock"]/p[2]' \
//     'Goodbye! Hello again!'

/// Hello world!
///
#[doc = "Goodbye!"]
/// Hello again!
pub struct S2;
<|endoftext|>


<commit_before><commit_msg>prettier syntax<commit_after><|endoftext|>