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

		let mut cmd = Command::new("sh");
		cmd
			.arg(installer_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);

		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 tar directory<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;
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)))
	}
}
<|endoftext|>


<commit_before><commit_msg>Add tokio-tls echo example. (#541)<commit_after>// A tiny async TLS echo server with Tokio
extern crate native_tls;
extern crate tokio;
extern crate tokio_tls;

use native_tls::Identity;
use tokio::io;
use tokio::net::TcpListener;
use tokio::prelude::*;

fn main() {
    // Bind the server's socket
    let addr = "127.0.0.1:12345".parse().unwrap();
    let tcp = TcpListener::bind(&addr).unwrap();

    // Create the TLS acceptor.
    let der = include_bytes!("identity.p12");
    let cert = Identity::from_pkcs12(der, "mypass").unwrap();
    let tls_acceptor = tokio_tls::TlsAcceptor::from(
        native_tls::TlsAcceptor::builder(cert).build().unwrap());

    // Iterate incoming connections
    let server = tcp.incoming().for_each(move |tcp| {

        // Accept the TLS connection.
        let tls_accept = tls_acceptor.accept(tcp)
            .and_then(move |tls| {
                // Split up the read and write halves
                let (reader, writer) = tls.split();

                // Copy the data back to the client
                let conn = io::copy(reader, writer)
                    // print what happened
                    .map(|(n, _, _)| {
                        println!("wrote {} bytes", n)
                    })
                    // Handle any errors
                    .map_err(|err| {
                        println!("IO error {:?}", err)
                    });

                // Spawn the future as a concurrent task
                tokio::spawn(conn);

                Ok(())
            })
            .map_err(|err| {
                println!("TLS accept error: {:?}", err);
            });
        tokio::spawn(tls_accept);

        Ok(())
    }).map_err(|err| {
        println!("server error {:?}", err);
    });

    // Start the runtime and spin up the server
    tokio::run(server);
}
<|endoftext|>


<commit_before><commit_msg>add infobar<commit_after>// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

//! Report important messages to the user

use std::{ptr, cast};
use std::libc::{c_void, c_int};

use gtk::enums::GtkMessageType;
use traits::{GtkContainer, GtkWidget, GtkBox, GtkOrientable, Signal};
use utils::cast::GTK_INFOBAR;
use gtk;
use ffi;

/// InfoBar — Report important messages to the user
pub struct InfoBar {
    priv pointer:           *ffi::C_GtkWidget,
    priv can_drop:          bool,
    priv signal_handlers:   ~[~SignalHandler]
}

impl InfoBar {
    pub fn new() -> Option<InfoBar> {
        let tmp_pointer = unsafe { ffi::gtk_info_bar_new() };
        check_pointer!(tmp_pointer, InfoBar)
    }

    pub fn add_action_widget<T: GtkWidget>(&mut self, child: &T, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_add_action_widget(GTK_INFOBAR(self.pointer), child.get_widget(), response_id as c_int)
        }
    }

    pub fn add_button(&mut self, button_text: &str, response_id: i32) -> gtk::Button {
        let button = unsafe {
            button_text.with_c_str(|c_str| {
                ffi::gtk_info_bar_add_button(GTK_INFOBAR(self.pointer), c_str, response_id as c_int)
            })
        };
        GtkWidget::wrap_widget(button)
    }

    pub fn set_response_sensitive(&mut self, response_id: i32, setting: bool) -> () {
        match setting {
            true    => unsafe { ffi::gtk_info_bar_set_response_sensitive(GTK_INFOBAR(self.pointer), response_id as c_int, ffi::Gtrue) },
            false   => unsafe { ffi::gtk_info_bar_set_response_sensitive(GTK_INFOBAR(self.pointer), response_id as c_int, ffi::Gfalse) }
        }
    }

    pub fn set_default_response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_set_default_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn set_message_type(&mut self, message_type: GtkMessageType) -> () {
        unsafe {
            ffi::gtk_info_bar_set_message_type(GTK_INFOBAR(self.pointer), message_type);
        }
    }

    pub fn get_message_type(&mut self) -> GtkMessageType {
        unsafe {
            ffi::gtk_info_bar_get_message_type(GTK_INFOBAR(self.pointer))
        }
    }

    pub fn show_close_button(&mut self, show: bool) -> () {
         match show {
            true    => unsafe { ffi::gtk_info_bar_set_show_close_button(GTK_INFOBAR(self.pointer), ffi::Gtrue) },
            false   => unsafe { ffi::gtk_info_bar_set_show_close_button(GTK_INFOBAR(self.pointer), ffi::Gfalse) }
        }
    }

    pub fn get_show_close_button(&self) -> bool {
        match unsafe { ffi::gtk_info_bar_get_show_close_button(GTK_INFOBAR(self.pointer)) } {
            ffi::Gfalse     => false,
            _               => true
        }
    }
}

impl_GtkWidget!(InfoBar)
redirect_callback!(InfoBar)
redirect_callback_widget!(InfoBar)
struct_signal!(InfoBar)
impl_signals!(InfoBar)

impl GtkContainer for InfoBar {}
impl GtkBox for InfoBar {}
impl GtkOrientable for InfoBar {}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #2395 - RalfJung:upcast, r=RalfJung<commit_after>#![feature(trait_upcasting)]
#![allow(incomplete_features)]

fn main() {
    basic();
    diamond();
    struct_();
    replace_vptr();
}

fn basic() {
    trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
        fn a(&self) -> i32 {
            10
        }

        fn z(&self) -> i32 {
            11
        }

        fn y(&self) -> i32 {
            12
        }
    }

    trait Bar: Foo {
        fn b(&self) -> i32 {
            20
        }

        fn w(&self) -> i32 {
            21
        }
    }

    trait Baz: Bar {
        fn c(&self) -> i32 {
            30
        }
    }

    impl Foo for i32 {
        fn a(&self) -> i32 {
            100
        }
    }

    impl Bar for i32 {
        fn b(&self) -> i32 {
            200
        }
    }

    impl Baz for i32 {
        fn c(&self) -> i32 {
            300
        }
    }

    let baz: &dyn Baz = &1;
    let _: &dyn std::fmt::Debug = baz;
    assert_eq!(*baz, 1);
    assert_eq!(baz.a(), 100);
    assert_eq!(baz.b(), 200);
    assert_eq!(baz.c(), 300);
    assert_eq!(baz.z(), 11);
    assert_eq!(baz.y(), 12);
    assert_eq!(baz.w(), 21);

    let bar: &dyn Bar = baz;
    let _: &dyn std::fmt::Debug = bar;
    assert_eq!(*bar, 1);
    assert_eq!(bar.a(), 100);
    assert_eq!(bar.b(), 200);
    assert_eq!(bar.z(), 11);
    assert_eq!(bar.y(), 12);
    assert_eq!(bar.w(), 21);

    let foo: &dyn Foo = baz;
    let _: &dyn std::fmt::Debug = foo;
    assert_eq!(*foo, 1);
    assert_eq!(foo.a(), 100);
    assert_eq!(foo.z(), 11);
    assert_eq!(foo.y(), 12);

    let foo: &dyn Foo = bar;
    let _: &dyn std::fmt::Debug = foo;
    assert_eq!(*foo, 1);
    assert_eq!(foo.a(), 100);
    assert_eq!(foo.z(), 11);
    assert_eq!(foo.y(), 12);
}

fn diamond() {
    trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
        fn a(&self) -> i32 {
            10
        }

        fn z(&self) -> i32 {
            11
        }

        fn y(&self) -> i32 {
            12
        }
    }

    trait Bar1: Foo {
        fn b(&self) -> i32 {
            20
        }

        fn w(&self) -> i32 {
            21
        }
    }

    trait Bar2: Foo {
        fn c(&self) -> i32 {
            30
        }

        fn v(&self) -> i32 {
            31
        }
    }

    trait Baz: Bar1 + Bar2 {
        fn d(&self) -> i32 {
            40
        }
    }

    impl Foo for i32 {
        fn a(&self) -> i32 {
            100
        }
    }

    impl Bar1 for i32 {
        fn b(&self) -> i32 {
            200
        }
    }

    impl Bar2 for i32 {
        fn c(&self) -> i32 {
            300
        }
    }

    impl Baz for i32 {
        fn d(&self) -> i32 {
            400
        }
    }

    let baz: &dyn Baz = &1;
    let _: &dyn std::fmt::Debug = baz;
    assert_eq!(*baz, 1);
    assert_eq!(baz.a(), 100);
    assert_eq!(baz.b(), 200);
    assert_eq!(baz.c(), 300);
    assert_eq!(baz.d(), 400);
    assert_eq!(baz.z(), 11);
    assert_eq!(baz.y(), 12);
    assert_eq!(baz.w(), 21);
    assert_eq!(baz.v(), 31);

    let bar1: &dyn Bar1 = baz;
    let _: &dyn std::fmt::Debug = bar1;
    assert_eq!(*bar1, 1);
    assert_eq!(bar1.a(), 100);
    assert_eq!(bar1.b(), 200);
    assert_eq!(bar1.z(), 11);
    assert_eq!(bar1.y(), 12);
    assert_eq!(bar1.w(), 21);

    let bar2: &dyn Bar2 = baz;
    let _: &dyn std::fmt::Debug = bar2;
    assert_eq!(*bar2, 1);
    assert_eq!(bar2.a(), 100);
    assert_eq!(bar2.c(), 300);
    assert_eq!(bar2.z(), 11);
    assert_eq!(bar2.y(), 12);
    assert_eq!(bar2.v(), 31);

    let foo: &dyn Foo = baz;
    let _: &dyn std::fmt::Debug = foo;
    assert_eq!(*foo, 1);
    assert_eq!(foo.a(), 100);

    let foo: &dyn Foo = bar1;
    let _: &dyn std::fmt::Debug = foo;
    assert_eq!(*foo, 1);
    assert_eq!(foo.a(), 100);

    let foo: &dyn Foo = bar2;
    let _: &dyn std::fmt::Debug = foo;
    assert_eq!(*foo, 1);
    assert_eq!(foo.a(), 100);
}

fn struct_() {
    use std::rc::Rc;
    use std::sync::Arc;

    trait Foo: PartialEq<i32> + std::fmt::Debug + Send + Sync {
        fn a(&self) -> i32 {
            10
        }

        fn z(&self) -> i32 {
            11
        }

        fn y(&self) -> i32 {
            12
        }
    }

    trait Bar: Foo {
        fn b(&self) -> i32 {
            20
        }

        fn w(&self) -> i32 {
            21
        }
    }

    trait Baz: Bar {
        fn c(&self) -> i32 {
            30
        }
    }

    impl Foo for i32 {
        fn a(&self) -> i32 {
            100
        }
    }

    impl Bar for i32 {
        fn b(&self) -> i32 {
            200
        }
    }

    impl Baz for i32 {
        fn c(&self) -> i32 {
            300
        }
    }

    fn test_box() {
        let v = Box::new(1);

        let baz: Box<dyn Baz> = v.clone();
        assert_eq!(*baz, 1);
        assert_eq!(baz.a(), 100);
        assert_eq!(baz.b(), 200);
        assert_eq!(baz.c(), 300);
        assert_eq!(baz.z(), 11);
        assert_eq!(baz.y(), 12);
        assert_eq!(baz.w(), 21);

        let baz: Box<dyn Baz> = v.clone();
        let bar: Box<dyn Bar> = baz;
        assert_eq!(*bar, 1);
        assert_eq!(bar.a(), 100);
        assert_eq!(bar.b(), 200);
        assert_eq!(bar.z(), 11);
        assert_eq!(bar.y(), 12);
        assert_eq!(bar.w(), 21);

        let baz: Box<dyn Baz> = v.clone();
        let foo: Box<dyn Foo> = baz;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);

        let baz: Box<dyn Baz> = v.clone();
        let bar: Box<dyn Bar> = baz;
        let foo: Box<dyn Foo> = bar;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);
    }

    fn test_rc() {
        let v = Rc::new(1);

        let baz: Rc<dyn Baz> = v.clone();
        assert_eq!(*baz, 1);
        assert_eq!(baz.a(), 100);
        assert_eq!(baz.b(), 200);
        assert_eq!(baz.c(), 300);
        assert_eq!(baz.z(), 11);
        assert_eq!(baz.y(), 12);
        assert_eq!(baz.w(), 21);

        let baz: Rc<dyn Baz> = v.clone();
        let bar: Rc<dyn Bar> = baz;
        assert_eq!(*bar, 1);
        assert_eq!(bar.a(), 100);
        assert_eq!(bar.b(), 200);
        assert_eq!(bar.z(), 11);
        assert_eq!(bar.y(), 12);
        assert_eq!(bar.w(), 21);

        let baz: Rc<dyn Baz> = v.clone();
        let foo: Rc<dyn Foo> = baz;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);

        let baz: Rc<dyn Baz> = v.clone();
        let bar: Rc<dyn Bar> = baz;
        let foo: Rc<dyn Foo> = bar;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);
    }

    fn test_arc() {
        let v = Arc::new(1);

        let baz: Arc<dyn Baz> = v.clone();
        assert_eq!(*baz, 1);
        assert_eq!(baz.a(), 100);
        assert_eq!(baz.b(), 200);
        assert_eq!(baz.c(), 300);
        assert_eq!(baz.z(), 11);
        assert_eq!(baz.y(), 12);
        assert_eq!(baz.w(), 21);

        let baz: Arc<dyn Baz> = v.clone();
        let bar: Arc<dyn Bar> = baz;
        assert_eq!(*bar, 1);
        assert_eq!(bar.a(), 100);
        assert_eq!(bar.b(), 200);
        assert_eq!(bar.z(), 11);
        assert_eq!(bar.y(), 12);
        assert_eq!(bar.w(), 21);

        let baz: Arc<dyn Baz> = v.clone();
        let foo: Arc<dyn Foo> = baz;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);

        let baz: Arc<dyn Baz> = v.clone();
        let bar: Arc<dyn Bar> = baz;
        let foo: Arc<dyn Foo> = bar;
        assert_eq!(*foo, 1);
        assert_eq!(foo.a(), 100);
        assert_eq!(foo.z(), 11);
        assert_eq!(foo.y(), 12);
    }

    test_box();
    test_rc();
    test_arc();
}

fn replace_vptr() {
    trait A {
        fn foo_a(&self);
    }

    trait B {
        fn foo_b(&self);
    }

    trait C: A + B {
        fn foo_c(&self);
    }

    struct S(i32);

    impl A for S {
        fn foo_a(&self) {
            unreachable!();
        }
    }

    impl B for S {
        fn foo_b(&self) {
            assert_eq!(42, self.0);
        }
    }

    impl C for S {
        fn foo_c(&self) {
            unreachable!();
        }
    }

    fn invoke_inner(b: &dyn B) {
        b.foo_b();
    }

    fn invoke_outer(c: &dyn C) {
        invoke_inner(c);
    }

    let s = S(42);
    invoke_outer(&s);
}
<|endoftext|>


<commit_before><commit_msg>New codes<commit_after>/**
 * Snippets from the Dave Herman's presentation (2013-01-06)
 * http://www.infoq.com/presentations/Rust
 *
 * Dave Herman talks about Mozilla Rust and some of the features that make it safe, concurrent, and fast.
 */
struct Point {
	x: float,
	y: float
}
fn print_point(p: &Point) {
	match *p {
		Point {x, y} => println(fmt!("(%f, %f)", x, y))
	}
}
fn main() {
	// &T, in C++ : T&
	let p = Point{x:1.1, y:1.2};
	print_point(&p);
	// @T, in C++ : shared_ptr<T>
	let p2 = @Point{x:2.1, y:2.2};
	print_point(p2);
	// ~T, in C++ : unique_ptr<T>
	let p3 = ~Point{x:3.1, y:3.2};
	print_point(p3);
	/*
	let p4; // uninitialized
	print_point(p4); // error

	let p5 = ~Point {x:5.1, y:5.2};
	box.topLeft = move p5; // deinitialized
	print_point(p); // error
	*/
}
<|endoftext|>


<commit_before><commit_msg>Fix: Remove default value for --verbose flag<commit_after><|endoftext|>


<commit_before><commit_msg>fetch/artifact: implement sha1 hash checking<commit_after><|endoftext|>


<commit_before><commit_msg>Fix ULP comparator bug (#92)<commit_after><|endoftext|>


<commit_before><commit_msg>:hammer: Make to return the Attachment struct<commit_after><|endoftext|>


<commit_before><commit_msg>Simplification/dedupe, fixed solver a bit<commit_after><|endoftext|>


<commit_before><commit_msg>added debug option<commit_after><|endoftext|>


<commit_before><commit_msg>Added some helpful comments<commit_after><|endoftext|>


<commit_before><commit_msg>Improve variable name<commit_after><|endoftext|>


<commit_before><commit_msg>rust_play : philosophers<commit_after>extern crate rand;

use std::thread;
use std::sync::{Mutex,Arc};
use rand::Rng;

struct Philosopher {
    name : String,
    left : usize,
    right : usize,
}

impl Philosopher {
    fn new(name : &str, left : usize, right : usize) -> Philosopher {
        Philosopher {
            name : name.to_string(),
            left : left,
            right : right,
        }
    }
    fn eat(&self, table : &Table) {
        let _left = table.forks[self.left].lock().unwrap();
        let _right = table.forks[self.right].lock().unwrap();
        let num = rand::thread_rng().gen_range(1,101) * 100;
        println!("{} L {} R {} is eating for {} ms",self.name,self.left,self.right,num);
        thread::sleep_ms(num);
        println!("{} is done eating",self.name);
    }
}

struct Table {
    forks : Vec<Mutex<()>>,
}
fn main() {
    println!("Dining philosophers");
    let table = Arc::new(Table { forks : vec![Mutex::new(()),
                                              Mutex::new(()),
                                              Mutex::new(()),
                                              Mutex::new(()),
                                              Mutex::new(()),
                                              ]});
    let philos = vec![Philosopher::new("Spinoza",0,1),
                      Philosopher::new("Marx",1,2),
                      Philosopher::new("Camus",2,3),
                      Philosopher::new("Hegel",3,4),
                      Philosopher::new("Nietzsche",0,4),
                      ];
    let handles :  Vec<_> = philos.into_iter().map(|p| {
        let tbl = table.clone();

        thread::spawn(move || {
            p.eat(&tbl);
        })
    }).collect();

    for h in handles {
        h.join().unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add error messages to piping, fix piping stdout, fexes #138<commit_after><|endoftext|>


<commit_before><commit_msg>Pick more appropriate int types for sha1<commit_after><|endoftext|>


<commit_before><commit_msg>Reducing redundant methods in uimf module.<commit_after><|endoftext|>


<commit_before><commit_msg>Keep old `nickel` example and add deprecation note<commit_after>//! **Note**: in-crate integration for Nickel is deprecated and will be removed in 0.11.0;
//! integration will be provided in the
//! [`multipart-nickel`](https://crates.io/crates/multipart-nickel)
//! crate for the foreseeable future.
extern crate multipart;
extern crate nickel;

use std::fs::File;
use std::io::Read;
use nickel::{HttpRouter, MiddlewareResult, Nickel, Request, Response};

use multipart::server::{Multipart, Entries, SaveResult};

fn handle_multipart<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> {
    match Multipart::from_request(req) {
        Ok(mut multipart) => {
            match multipart.save().temp() {
                SaveResult::Full(entries) => process_entries(res, entries),

                SaveResult::Partial(entries, e) => {
                    println!("Partial errors ... {:?}", e);
                    return process_entries(res, entries.keep_partial());
                },

                SaveResult::Error(e) => {
                    println!("There are errors in multipart POSTing ... {:?}", e);
                    res.set(nickel::status::StatusCode::InternalServerError);
                    return res.send(format!("Server could not handle multipart POST! {:?}", e));
                },
            }
        }
        Err(_) => {
            res.set(nickel::status::StatusCode::BadRequest);
            return res.send("Request seems not was a multipart request")
        }
    }
}

/// Processes saved entries from multipart request.
/// Returns an OK response or an error.
fn process_entries<'mw>(res: Response<'mw>, entries: Entries) -> MiddlewareResult<'mw> {
    for (name, field) in entries.fields {
        println!("Field {:?}: {:?}", name, field);
    }

    for (name, files) in entries.files {
        println!("Field {:?} has {} files:", name, files.len());

        for saved_file in files {
            match File::open(&saved_file.path) {
                Ok(mut file) => {
                    let mut contents = String::new();
                    if let Err(e) = file.read_to_string(&mut contents) {
                        println!("Could not read file {:?}. Error: {:?}", saved_file.filename, e);
                        return res.error(nickel::status::StatusCode::BadRequest, "The uploaded file was not readable")
                    }

                    println!("File {:?} ({:?}):", saved_file.filename, saved_file.content_type);
                    println!("{}", contents);
                    file
                }
                Err(e) => {
                    println!("Could open file {:?}. Error: {:?}", saved_file.filename, e);
                    return res.error(nickel::status::StatusCode::BadRequest, "The uploaded file was not readable")
                }
            };
        }
    }

    res.send("Ok")
}

fn main() {
    let mut srv = Nickel::new();

    srv.post("/multipart_upload/", handle_multipart);

    // Start this example via:
    //
    // `cargo run --example nickel --features nickel`
    //
    // And - if you are in the root of this repository - do an example
    // upload via:
    //
    // `curl -F file=@LICENSE 'http://localhost:6868/multipart_upload/'`
    srv.listen("127.0.0.1:6868").expect("Failed to bind server");
}
<|endoftext|>


<commit_before><commit_msg>removed unecessary method<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<%helpers:shorthand name="text-decoration"
                    engines="gecko servo-2013"
                    flags="SHORTHAND_IN_GETCS"
                    sub_properties="text-decoration-line
                    ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}"
                    spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration">

    % if engine == "gecko":
        use crate::values::specified;
        use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness};
        use crate::properties::{PropertyId, LonghandId};
    % endif
    use crate::properties::longhands::text_decoration_line;

    pub fn parse_value<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Longhands, ParseError<'i>> {
        % if engine == "gecko":
            let text_decoration_thickness_enabled =
                PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content();

            let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false);
        % else:
            let (mut line, mut any) = (None, false);
        % endif

        loop {
            macro_rules! parse_component {
                ($value:ident, $module:ident) => (
                    if $value.is_none() {
                        if let Ok(value) = input.try(|input| $module::parse(context, input)) {
                            $value = Some(value);
                            any = true;
                            continue;
                        }
                    }
                )
            }

            parse_component!(line, text_decoration_line);

            % if engine == "gecko":
                parse_component!(style, text_decoration_style);
                parse_component!(color, text_decoration_color);
                if text_decoration_thickness_enabled {
                    parse_component!(thickness, text_decoration_thickness);
                }
            % endif

            break;
        }

        if !any {
            return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
        }

        Ok(expanded! {
            text_decoration_line: unwrap_or_initial!(text_decoration_line, line),

            % if engine == "gecko":
                text_decoration_style: unwrap_or_initial!(text_decoration_style, style),
                text_decoration_color: unwrap_or_initial!(text_decoration_color, color),
                text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness),
            % endif
        })
    }

    impl<'a> ToCss for LonghandsToSerialize<'a>  {
        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
            self.text_decoration_line.to_css(dest)?;

            % if engine == "gecko":
                if *self.text_decoration_style != text_decoration_style::SpecifiedValue::Solid {
                    dest.write_str(" ")?;
                    self.text_decoration_style.to_css(dest)?;
                }

                if *self.text_decoration_color != specified::Color::CurrentColor {
                    dest.write_str(" ")?;
                    self.text_decoration_color.to_css(dest)?;
                }

                if let Some(text_decoration_thickness) = self.text_decoration_thickness {
                    if !text_decoration_thickness.is_auto() {
                        dest.write_str(" ")?;
                        self.text_decoration_thickness.to_css(dest)?;
                    }
                }
            % endif

            Ok(())
        }
    }
</%helpers:shorthand>
<commit_msg>style: Tweak the serialization of text-decoration.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

<%namespace name="helpers" file="/helpers.mako.rs" />

<%helpers:shorthand name="text-decoration"
                    engines="gecko servo-2013"
                    flags="SHORTHAND_IN_GETCS"
                    sub_properties="text-decoration-line
                    ${' text-decoration-style text-decoration-color text-decoration-thickness' if engine == 'gecko' else ''}"
                    spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration">

    % if engine == "gecko":
        use crate::values::specified;
        use crate::properties::longhands::{text_decoration_style, text_decoration_color, text_decoration_thickness};
        use crate::properties::{PropertyId, LonghandId};
    % endif
    use crate::properties::longhands::text_decoration_line;

    pub fn parse_value<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Longhands, ParseError<'i>> {
        % if engine == "gecko":
            let text_decoration_thickness_enabled =
                PropertyId::Longhand(LonghandId::TextDecorationThickness).enabled_for_all_content();

            let (mut line, mut style, mut color, mut thickness, mut any) = (None, None, None, None, false);
        % else:
            let (mut line, mut any) = (None, false);
        % endif

        loop {
            macro_rules! parse_component {
                ($value:ident, $module:ident) => (
                    if $value.is_none() {
                        if let Ok(value) = input.try(|input| $module::parse(context, input)) {
                            $value = Some(value);
                            any = true;
                            continue;
                        }
                    }
                )
            }

            parse_component!(line, text_decoration_line);

            % if engine == "gecko":
                parse_component!(style, text_decoration_style);
                parse_component!(color, text_decoration_color);
                if text_decoration_thickness_enabled {
                    parse_component!(thickness, text_decoration_thickness);
                }
            % endif

            break;
        }

        if !any {
            return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
        }

        Ok(expanded! {
            text_decoration_line: unwrap_or_initial!(text_decoration_line, line),

            % if engine == "gecko":
                text_decoration_style: unwrap_or_initial!(text_decoration_style, style),
                text_decoration_color: unwrap_or_initial!(text_decoration_color, color),
                text_decoration_thickness: unwrap_or_initial!(text_decoration_thickness, thickness),
            % endif
        })
    }

    impl<'a> ToCss for LonghandsToSerialize<'a>  {
        fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
            use crate::values::specified::TextDecorationLine;

            let (is_solid_style, is_current_color, is_auto_thickness) =
            (
            % if engine == "gecko":
                *self.text_decoration_style == text_decoration_style::SpecifiedValue::Solid,
                *self.text_decoration_color == specified::Color::CurrentColor,
                self.text_decoration_thickness.map_or(true, |t| t.is_auto())
            % else:
                true, true, true
            % endif
            );

            let mut has_value = false;
            let is_none = *self.text_decoration_line == TextDecorationLine::none();
            if (is_solid_style && is_current_color && is_auto_thickness) || !is_none {
                self.text_decoration_line.to_css(dest)?;
                has_value = true;
            }

            % if engine == "gecko":
            if !is_solid_style {
                if has_value {
                    dest.write_str(" ")?;
                }
                self.text_decoration_style.to_css(dest)?;
                has_value = true;
            }

            if !is_current_color {
                if has_value {
                    dest.write_str(" ")?;
                }
                self.text_decoration_color.to_css(dest)?;
                has_value = true;
            }

            if !is_auto_thickness {
                if has_value {
                    dest.write_str(" ")?;
                }
                self.text_decoration_thickness.to_css(dest)?;
            }
            % endif

            Ok(())
        }
    }
</%helpers:shorthand>
<|endoftext|>


<commit_before><commit_msg>fixed trait name<commit_after>use progress::Graph;
use communication::Pullable;
use communication::channels::Data;
use communication::exchange::{ParallelizationContract, Pipeline};
use communication::observer::ObserverSessionExt;
use example::stream::Stream;
use example::unary::UnaryExt;

// a trait enabling the "select" method
pub trait SelectExt<G: Graph, D1: Data, D2: Data> {
    fn select<L: Fn(D1) -> D2+'static>(&mut self, logic: L) -> Stream<G, D2>;
}

// implement the extension trait for Streams
impl<G: Graph, D1: Data, D2: Data> SelectExt<G, D1, D2> for Stream<G, D1> {
    fn select<L: Fn(D1) -> D2+'static>(&mut self, logic: L) -> Stream<G, D2> {
        let (sender, receiver) = Pipeline.connect(&mut self.graph.communicator());
        self.unary(sender, receiver, format!("Select"), move |handle| {
            while let Some((time, data)) = handle.input.pull() {
                let mut session = handle.output.session(&time);
                for datum in data {
                    session.push(&logic(datum));
                }
            }
        })
    }
}
<|endoftext|>


<commit_before>import libc::{c_void, c_int, c_char};

export surface;
export surface_flag;
export swsurface, hwsurface, asyncblit;
export video_mode_flag;
export anyformat, hwpalette, doublebuf, fullscreen, opengl,
       openglblit, resizable, noframe;
export set_video_mode, free_surface;
export load_bmp;
export display_format;
export blit_surface;
export flip;
export create_rgb_surface;

type rw_ops = c_void;

type surface = {
    flags: u32,
    format: *c_void,
    w: c_int,
    h: c_int,
    pitch: u16,
    pixels: *c_void,
    offset: c_int
    // FIXME: Remaining are unlisted
};

type rect = {
    x: i16,
    y: i16,
    w: u16,
    h: u16
};

enum surface_flag {
    swsurface = 0x00000000,
    hwsurface = 0x00000001,
    asyncblit = 0x00000004,
}

enum video_mode_flag {
    anyformat  = 0x10000000,
    hwpalette  = 0x20000000,
    doublebuf  = 0x40000000,
    fullscreen = 0x80000000,
    opengl     = 0x00000002,
    openglblit = 0x0000000A,
    resizable  = 0x00000010,
    noframe    = 0x00000020,
}

fn set_video_mode(
    width: int,
    height: int,
    bitsperpixel: int,
    surface_flags: [surface_flag],
    video_mode_flags: [video_mode_flag]
) -> *surface {
    let flags = vec::foldl(0u32, surface_flags) {|flags, flag|
        flags | flag as u32
    };
    let flags = vec::foldl(flags, video_mode_flags) {|flags, flag|
        flags | flag as u32
    };
    SDL::SDL_SetVideoMode(width as c_int, height as c_int,
                          bitsperpixel as c_int, flags)
}

fn free_surface(surface: *surface) {
    SDL::SDL_FreeSurface(surface)
}

fn load_bmp(file: str) -> *surface unsafe {
    str::as_buf(file) {|buf|
        let  buf = unsafe::reinterpret_cast(buf);
        str::as_buf("rb") {|rbbuf|
            let rbbuf = unsafe::reinterpret_cast(rbbuf);
            SDL::SDL_LoadBMP_RW(SDL::SDL_RWFromFile(buf, rbbuf), 1 as c_int)
        }
    }
}

fn display_format(surface: *surface) -> *surface {
    SDL::SDL_DisplayFormat(surface)
}

fn blit_surface(src: *surface, srcrect: *rect,
                dst: *surface, dstrect: *rect) -> bool {
    let res = SDL::SDL_UpperBlit(src, srcrect, dst, dstrect);
    ret res == 0 as c_int;
}

fn flip(screen: *surface) -> bool {
    SDL::SDL_Flip(screen) == 0 as c_int
}

fn create_rgb_surface(
    surface_flags: [surface_flag],
    width: int, height: int, bits_per_pixel: int,
    rmask: u32, gmask: u32, bmask: u32, amask: u32) -> *surface {

    let flags = vec::foldl(0u32, surface_flags) {|flags, flag|
        flags | flag as u32
    };
    SDL::SDL_CreateRGBSurface(
        flags, width as c_int, height as c_int, bits_per_pixel as c_int,
        rmask, gmask, bmask, amask)
}

native mod SDL {
    fn SDL_SetVideoMode(width: c_int, height: c_int,
                        bitsperpixel: c_int, flags: u32) -> *surface;
    fn SDL_FreeSurface(surface: *surface);
    fn SDL_LoadBMP_RW(src: *rw_ops, freesrc: c_int) -> *surface;
    fn SDL_RWFromFile(file: *c_char, mode: *c_char) -> *rw_ops;
    fn SDL_DisplayFormat(surface: *surface) -> *surface;
    fn SDL_UpperBlit(src: *surface, srcrect: *rect,
                     dst: *surface, dstrect: *rect) -> c_int;
    fn SDL_Flip(screen: *surface) -> c_int;
    fn SDL_CreateRGBSurface(flags: u32, width: c_int, height: c_int,
                            bitsPerPixel: c_int,
                            Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) -> *surface;
}
<commit_msg>Add fill_rect, lock_surface, unlock_surface<commit_after>import libc::{c_void, c_int, c_char};

export surface;
export surface_flag;
export swsurface, hwsurface, asyncblit;
export video_mode_flag;
export anyformat, hwpalette, doublebuf, fullscreen, opengl,
       openglblit, resizable, noframe;
export set_video_mode, free_surface;
export load_bmp;
export display_format;
export blit_surface;
export flip;
export create_rgb_surface;
export fill_rect;
export lock_surface;
export unlock_surface;

type rw_ops = c_void;

type surface = {
    flags: u32,
    format: *c_void,
    w: c_int,
    h: c_int,
    pitch: u16,
    pixels: *c_void,
    offset: c_int
    // FIXME: Remaining are unlisted
};

type rect = {
    x: i16,
    y: i16,
    w: u16,
    h: u16
};

enum surface_flag {
    swsurface = 0x00000000,
    hwsurface = 0x00000001,
    asyncblit = 0x00000004,
}

enum video_mode_flag {
    anyformat  = 0x10000000,
    hwpalette  = 0x20000000,
    doublebuf  = 0x40000000,
    fullscreen = 0x80000000,
    opengl     = 0x00000002,
    openglblit = 0x0000000A,
    resizable  = 0x00000010,
    noframe    = 0x00000020,
}

fn set_video_mode(
    width: int,
    height: int,
    bitsperpixel: int,
    surface_flags: [surface_flag],
    video_mode_flags: [video_mode_flag]
) -> *surface {
    let flags = vec::foldl(0u32, surface_flags) {|flags, flag|
        flags | flag as u32
    };
    let flags = vec::foldl(flags, video_mode_flags) {|flags, flag|
        flags | flag as u32
    };
    SDL::SDL_SetVideoMode(width as c_int, height as c_int,
                          bitsperpixel as c_int, flags)
}

fn free_surface(surface: *surface) {
    SDL::SDL_FreeSurface(surface)
}

fn load_bmp(file: str) -> *surface unsafe {
    str::as_buf(file) {|buf|
        let  buf = unsafe::reinterpret_cast(buf);
        str::as_buf("rb") {|rbbuf|
            let rbbuf = unsafe::reinterpret_cast(rbbuf);
            SDL::SDL_LoadBMP_RW(SDL::SDL_RWFromFile(buf, rbbuf), 1 as c_int)
        }
    }
}

fn display_format(surface: *surface) -> *surface {
    SDL::SDL_DisplayFormat(surface)
}

fn blit_surface(src: *surface, srcrect: *rect,
                dst: *surface, dstrect: *rect) -> bool {
    let res = SDL::SDL_UpperBlit(src, srcrect, dst, dstrect);
    ret res == 0 as c_int;
}

fn flip(screen: *surface) -> bool {
    SDL::SDL_Flip(screen) == 0 as c_int
}

fn create_rgb_surface(
    surface_flags: [surface_flag],
    width: int, height: int, bits_per_pixel: int,
    rmask: u32, gmask: u32, bmask: u32, amask: u32) -> *surface {

    let flags = vec::foldl(0u32, surface_flags) {|flags, flag|
        flags | flag as u32
    };
    SDL::SDL_CreateRGBSurface(
        flags, width as c_int, height as c_int, bits_per_pixel as c_int,
        rmask, gmask, bmask, amask)
}

fn fill_rect(surface: *surface, rect: *rect, color: u32) {
    SDL::SDL_FillRect(surface, rect, color);
}

fn lock_surface(surface: *surface) {
    SDL::SDL_LockSurface(surface);
}

fn unlock_surface(surface: *surface) {
    SDL::SDL_UnlockSurface(surface);
}

native mod SDL {
    fn SDL_SetVideoMode(width: c_int, height: c_int,
                        bitsperpixel: c_int, flags: u32) -> *surface;
    fn SDL_FreeSurface(surface: *surface);
    fn SDL_LoadBMP_RW(src: *rw_ops, freesrc: c_int) -> *surface;
    fn SDL_RWFromFile(file: *c_char, mode: *c_char) -> *rw_ops;
    fn SDL_DisplayFormat(surface: *surface) -> *surface;
    fn SDL_UpperBlit(src: *surface, srcrect: *rect,
                     dst: *surface, dstrect: *rect) -> c_int;
    fn SDL_Flip(screen: *surface) -> c_int;
    fn SDL_CreateRGBSurface(flags: u32, width: c_int, height: c_int,
                            bitsPerPixel: c_int,
                            Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) -> *surface;
    fn SDL_FillRect(dst: *surface, dstrect: *rect, color: u32);
    fn SDL_LockSurface(surface: *surface);
    fn SDL_UnlockSurface(surface: *surface);
}
<|endoftext|>


<commit_before><commit_msg>use new range function<commit_after><|endoftext|>


<commit_before>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

#[miri_run]
fn call() -> i32 {
    fn increment(x: i32) -> i32 {
        x + 1
    }
    increment(1)
}

#[miri_run]
fn factorial_recursive() -> i64 {
    fn fact(n: i64) -> i64 {
        if n == 0 {
            1
        } else {
            n * fact(n - 1)
        }
    }
    fact(10)
}

#[miri_run]
fn call_generic() -> (i16, bool) {
    fn id<T>(t: T) -> T { t }
    (id(42), id(true))
}

// Test calling a very simple function from the standard library.
#[miri_run]
fn cross_crate_fn_call() -> i64 {
    if 1i32.is_positive() { 1 } else { 0 }
}

#[miri_run]
fn main() {
    assert_eq!(call(), 2);
    assert_eq!(factorial_recursive(), 3628800);
    assert_eq!(call_generic(), (42, true));
    assert_eq!(cross_crate_fn_call(), 1);
}
<commit_msg>add a const fn test<commit_after>#![feature(custom_attribute, const_fn)]
#![allow(dead_code, unused_attributes)]

#[miri_run]
fn call() -> i32 {
    fn increment(x: i32) -> i32 {
        x + 1
    }
    increment(1)
}

#[miri_run]
fn factorial_recursive() -> i64 {
    fn fact(n: i64) -> i64 {
        if n == 0 {
            1
        } else {
            n * fact(n - 1)
        }
    }
    fact(10)
}

#[miri_run]
fn call_generic() -> (i16, bool) {
    fn id<T>(t: T) -> T { t }
    (id(42), id(true))
}

// Test calling a very simple function from the standard library.
#[miri_run]
fn cross_crate_fn_call() -> i64 {
    if 1i32.is_positive() { 1 } else { 0 }
}

const fn foo(i: i64) -> i64 { *&i + 1 }

#[miri_run]
fn const_fn_call() -> i64 {
    let x = 5 + foo(5);
    assert_eq!(x, 11);
    x
}

#[miri_run]
fn main() {
    assert_eq!(call(), 2);
    assert_eq!(factorial_recursive(), 3628800);
    assert_eq!(call_generic(), (42, true));
    assert_eq!(cross_crate_fn_call(), 1);
}
<|endoftext|>


<commit_before>#![feature(macro_rules)]

#![crate_name="sdl2_image"]
#![crate_type = "lib"]
#![desc = "SDL2_image bindings and wrappers"]
#![comment = "SDL2_image bindings and wrappers"]
#![license = "MIT"]

extern crate sdl2;
extern crate libc;

use libc::{c_int, c_char};
use std::ptr;
use sdl2::surface::Surface;
use sdl2::render::Texture;
use sdl2::render::Renderer;
use sdl2::rwops::RWops;
use sdl2::version::Version;
use sdl2::get_error;
use sdl2::SdlResult;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_image")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_image")]
    extern {}
}

#[cfg(target_os="win32")]
#[cfg(target_os="linux")]
#[cfg(target_os="freebsd")]
mod others {
    #[link(name="SDL2_image")]
    extern {}
}

#[allow(non_camel_case_types, dead_code)]
mod ffi;

/// InitFlags are passed to init() to control which subsystem
/// functionality to load.
bitflags!(flags InitFlag : u32 {
    static InitJpg = ffi::IMG_INIT_JPG as u32,
    static InitPng = ffi::IMG_INIT_PNG as u32,
    static InitTif = ffi::IMG_INIT_TIF as u32,
    static InitWebp = ffi::IMG_INIT_WEBP as u32
})

/// Static method extensions for creating Surfaces
pub trait LoadSurface {
    // Self is only returned here to type hint to the compiler.
    // The syntax for type hinting in this case is not yet defined.
    // The intended return value is SdlResult<~Surface>.
    fn from_file(filename: &Path) -> SdlResult<Self>;
    fn from_xpm_array(xpm: *const *const i8) -> SdlResult<Self>;
}

/// Method extensions to Surface for saving to disk
pub trait SaveSurface {
    fn save(&self, filename: &Path) -> SdlResult<()>;
    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()>;
}

impl LoadSurface for Surface {
    fn from_file(filename: &Path) -> SdlResult<Surface> {
        //! Loads an SDL Surface from a file
        unsafe {
            let raw = ffi::IMG_Load(filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw, true))
            }
        }
    }

    fn from_xpm_array(xpm: *const *const i8) -> SdlResult<Surface> {
        //! Loads an SDL Surface from XPM data
        unsafe {
            let raw = ffi::IMG_ReadXPMFromArray(xpm as *const *const c_char);
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw, true))
            }
        }
    }
}

impl SaveSurface for Surface {
    fn save(&self, filename: &Path) -> SdlResult<()> {
        //! Saves an SDL Surface to a file
        unsafe {
            let status = ffi::IMG_SavePNG(self.raw(),
                                          filename.to_c_str().unwrap());
            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }

    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()> {
        //! Saves an SDL Surface to an RWops
        unsafe {
            let status = ffi::IMG_SavePNG_RW(self.raw(), dst.raw(), 0);

            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Method extensions for creating Textures from a Renderer
pub trait LoadTexture {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture>;
}

impl<T> LoadTexture for Renderer<T> {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture> {
        //! Loads an SDL Texture from a file
        unsafe {
            let raw = ffi::IMG_LoadTexture(self.raw(),
                                           filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Texture{ raw: raw, owned: true })
            }
        }
    }
}

pub fn init(flags: InitFlag) -> InitFlag {
    //! Initializes SDL2_image with InitFlags and returns which
    //! InitFlags were actually used.
    unsafe {
        let used = ffi::IMG_Init(flags.bits() as c_int);
        InitFlag::from_bits_truncate(used as u32)
    }
}

pub fn quit() {
    //! Teardown the SDL2_Image subsystem
    unsafe { ffi::IMG_Quit(); }
}

pub fn get_linked_version() -> Version {
    //! Returns the version of the dynamically linked SDL_image library
    unsafe {
        Version::from_ll(ffi::IMG_Linked_Version())
    }
}

#[inline]
fn to_surface_result(raw: *const sdl2::surface::ll::SDL_Surface) -> SdlResult<Surface> {
    if raw == ptr::null() {
        Err(get_error())
    } else {
        unsafe { Ok(Surface::from_ll(raw, true)) }
    }
}

pub trait ImageRWops {
    /// load as a surface. except TGA
    fn load(&self) -> SdlResult<Surface>;
    /// load as a surface. This can load all supported image formats.
    fn load_typed(&self, _type: &str) -> SdlResult<Surface>;

    fn load_cur(&self) -> SdlResult<Surface>;
    fn load_ico(&self) -> SdlResult<Surface>;
    fn load_bmp(&self) -> SdlResult<Surface>;
    fn load_pnm(&self) -> SdlResult<Surface>;
    fn load_xpm(&self) -> SdlResult<Surface>;
    fn load_xcf(&self) -> SdlResult<Surface>;
    fn load_pcx(&self) -> SdlResult<Surface>;
    fn load_gif(&self) -> SdlResult<Surface>;
    fn load_jpg(&self) -> SdlResult<Surface>;
    fn load_tif(&self) -> SdlResult<Surface>;
    fn load_png(&self) -> SdlResult<Surface>;
    fn load_tga(&self) -> SdlResult<Surface>;
    fn load_lbm(&self) -> SdlResult<Surface>;
    fn load_xv(&self)  -> SdlResult<Surface>;
    fn load_webp(&self) -> SdlResult<Surface>;

    fn is_cur(&self) -> bool;
    fn is_ico(&self) -> bool;
    fn is_bmp(&self) -> bool;
    fn is_pnm(&self) -> bool;
    fn is_xpm(&self) -> bool;
    fn is_xcf(&self) -> bool;
    fn is_pcx(&self) -> bool;
    fn is_gif(&self) -> bool;
    fn is_jpg(&self) -> bool;
    fn is_tif(&self) -> bool;
    fn is_png(&self) -> bool;
    fn is_lbm(&self) -> bool;
    fn is_xv(&self)  -> bool;
    fn is_webp(&self) -> bool;
}

impl ImageRWops for RWops {
    fn load(&self) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_Load_RW(self.raw(), 0)
        };
        to_surface_result(raw)
    }
    fn load_typed(&self, _type: &str) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_LoadTyped_RW(self.raw(), 0, _type.to_c_str().unwrap())
        };
        to_surface_result(raw)
    }

    fn load_cur(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadCUR_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_ico(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadICO_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_bmp(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadBMP_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pnm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xpm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXPM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xcf(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXCF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pcx(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPCX_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_gif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadGIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_jpg(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadJPG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_png(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tga(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTGA_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_lbm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadLBM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xv(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXV_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_webp(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadWEBP_RW(self.raw()) };
        to_surface_result(raw)
    }

    fn is_cur(&self) -> bool {
        unsafe { ffi::IMG_isCUR(self.raw()) == 1 }
    }
    fn is_ico(&self) -> bool {
        unsafe { ffi::IMG_isICO(self.raw()) == 1 }
    }
    fn is_bmp(&self) -> bool {
        unsafe { ffi::IMG_isBMP(self.raw()) == 1 }
    }
    fn is_pnm(&self) -> bool {
        unsafe { ffi::IMG_isPNM(self.raw()) == 1 }
    }
    fn is_xpm(&self) -> bool {
        unsafe { ffi::IMG_isXPM(self.raw()) == 1 }
    }
    fn is_xcf(&self) -> bool {
        unsafe { ffi::IMG_isXCF(self.raw()) == 1 }
    }
    fn is_pcx(&self) -> bool {
        unsafe { ffi::IMG_isPCX(self.raw()) == 1 }
    }
    fn is_gif(&self) -> bool {
        unsafe { ffi::IMG_isGIF(self.raw()) == 1 }
    }
    fn is_jpg(&self) -> bool {
        unsafe { ffi::IMG_isJPG(self.raw()) == 1 }
    }
    fn is_tif(&self) -> bool {
        unsafe { ffi::IMG_isTIF(self.raw()) == 1 }
    }
    fn is_png(&self) -> bool {
        unsafe { ffi::IMG_isPNG(self.raw()) == 1 }
    }
    fn is_lbm(&self) -> bool {
        unsafe { ffi::IMG_isLBM(self.raw()) == 1 }
    }
    fn is_xv(&self)  -> bool {
        unsafe { ffi::IMG_isXV(self.raw())  == 1 }
    }
    fn is_webp(&self) -> bool {
        unsafe { ffi::IMG_isWEBP(self.raw())  == 1 }
    }
}
<commit_msg>Fix wrong Windows target OS label.<commit_after>#![feature(macro_rules)]

#![crate_name="sdl2_image"]
#![crate_type = "lib"]
#![desc = "SDL2_image bindings and wrappers"]
#![comment = "SDL2_image bindings and wrappers"]
#![license = "MIT"]

extern crate sdl2;
extern crate libc;

use libc::{c_int, c_char};
use std::ptr;
use sdl2::surface::Surface;
use sdl2::render::Texture;
use sdl2::render::Renderer;
use sdl2::rwops::RWops;
use sdl2::version::Version;
use sdl2::get_error;
use sdl2::SdlResult;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_image")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_image")]
    extern {}
}

#[cfg(target_os="windows")]
#[cfg(target_os="linux")]
#[cfg(target_os="freebsd")]
mod others {
    #[link(name="SDL2_image")]
    extern {}
}

#[allow(non_camel_case_types, dead_code)]
mod ffi;

/// InitFlags are passed to init() to control which subsystem
/// functionality to load.
bitflags!(flags InitFlag : u32 {
    static InitJpg = ffi::IMG_INIT_JPG as u32,
    static InitPng = ffi::IMG_INIT_PNG as u32,
    static InitTif = ffi::IMG_INIT_TIF as u32,
    static InitWebp = ffi::IMG_INIT_WEBP as u32
})

/// Static method extensions for creating Surfaces
pub trait LoadSurface {
    // Self is only returned here to type hint to the compiler.
    // The syntax for type hinting in this case is not yet defined.
    // The intended return value is SdlResult<~Surface>.
    fn from_file(filename: &Path) -> SdlResult<Self>;
    fn from_xpm_array(xpm: *const *const i8) -> SdlResult<Self>;
}

/// Method extensions to Surface for saving to disk
pub trait SaveSurface {
    fn save(&self, filename: &Path) -> SdlResult<()>;
    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()>;
}

impl LoadSurface for Surface {
    fn from_file(filename: &Path) -> SdlResult<Surface> {
        //! Loads an SDL Surface from a file
        unsafe {
            let raw = ffi::IMG_Load(filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw, true))
            }
        }
    }

    fn from_xpm_array(xpm: *const *const i8) -> SdlResult<Surface> {
        //! Loads an SDL Surface from XPM data
        unsafe {
            let raw = ffi::IMG_ReadXPMFromArray(xpm as *const *const c_char);
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface::from_ll(raw, true))
            }
        }
    }
}

impl SaveSurface for Surface {
    fn save(&self, filename: &Path) -> SdlResult<()> {
        //! Saves an SDL Surface to a file
        unsafe {
            let status = ffi::IMG_SavePNG(self.raw(),
                                          filename.to_c_str().unwrap());
            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }

    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()> {
        //! Saves an SDL Surface to an RWops
        unsafe {
            let status = ffi::IMG_SavePNG_RW(self.raw(), dst.raw(), 0);

            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Method extensions for creating Textures from a Renderer
pub trait LoadTexture {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture>;
}

impl<T> LoadTexture for Renderer<T> {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture> {
        //! Loads an SDL Texture from a file
        unsafe {
            let raw = ffi::IMG_LoadTexture(self.raw(),
                                           filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Texture{ raw: raw, owned: true })
            }
        }
    }
}

pub fn init(flags: InitFlag) -> InitFlag {
    //! Initializes SDL2_image with InitFlags and returns which
    //! InitFlags were actually used.
    unsafe {
        let used = ffi::IMG_Init(flags.bits() as c_int);
        InitFlag::from_bits_truncate(used as u32)
    }
}

pub fn quit() {
    //! Teardown the SDL2_Image subsystem
    unsafe { ffi::IMG_Quit(); }
}

pub fn get_linked_version() -> Version {
    //! Returns the version of the dynamically linked SDL_image library
    unsafe {
        Version::from_ll(ffi::IMG_Linked_Version())
    }
}

#[inline]
fn to_surface_result(raw: *const sdl2::surface::ll::SDL_Surface) -> SdlResult<Surface> {
    if raw == ptr::null() {
        Err(get_error())
    } else {
        unsafe { Ok(Surface::from_ll(raw, true)) }
    }
}

pub trait ImageRWops {
    /// load as a surface. except TGA
    fn load(&self) -> SdlResult<Surface>;
    /// load as a surface. This can load all supported image formats.
    fn load_typed(&self, _type: &str) -> SdlResult<Surface>;

    fn load_cur(&self) -> SdlResult<Surface>;
    fn load_ico(&self) -> SdlResult<Surface>;
    fn load_bmp(&self) -> SdlResult<Surface>;
    fn load_pnm(&self) -> SdlResult<Surface>;
    fn load_xpm(&self) -> SdlResult<Surface>;
    fn load_xcf(&self) -> SdlResult<Surface>;
    fn load_pcx(&self) -> SdlResult<Surface>;
    fn load_gif(&self) -> SdlResult<Surface>;
    fn load_jpg(&self) -> SdlResult<Surface>;
    fn load_tif(&self) -> SdlResult<Surface>;
    fn load_png(&self) -> SdlResult<Surface>;
    fn load_tga(&self) -> SdlResult<Surface>;
    fn load_lbm(&self) -> SdlResult<Surface>;
    fn load_xv(&self)  -> SdlResult<Surface>;
    fn load_webp(&self) -> SdlResult<Surface>;

    fn is_cur(&self) -> bool;
    fn is_ico(&self) -> bool;
    fn is_bmp(&self) -> bool;
    fn is_pnm(&self) -> bool;
    fn is_xpm(&self) -> bool;
    fn is_xcf(&self) -> bool;
    fn is_pcx(&self) -> bool;
    fn is_gif(&self) -> bool;
    fn is_jpg(&self) -> bool;
    fn is_tif(&self) -> bool;
    fn is_png(&self) -> bool;
    fn is_lbm(&self) -> bool;
    fn is_xv(&self)  -> bool;
    fn is_webp(&self) -> bool;
}

impl ImageRWops for RWops {
    fn load(&self) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_Load_RW(self.raw(), 0)
        };
        to_surface_result(raw)
    }
    fn load_typed(&self, _type: &str) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_LoadTyped_RW(self.raw(), 0, _type.to_c_str().unwrap())
        };
        to_surface_result(raw)
    }

    fn load_cur(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadCUR_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_ico(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadICO_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_bmp(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadBMP_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pnm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xpm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXPM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xcf(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXCF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_pcx(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPCX_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_gif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadGIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_jpg(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadJPG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTIF_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_png(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNG_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_tga(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTGA_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_lbm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadLBM_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_xv(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXV_RW(self.raw()) };
        to_surface_result(raw)
    }
    fn load_webp(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadWEBP_RW(self.raw()) };
        to_surface_result(raw)
    }

    fn is_cur(&self) -> bool {
        unsafe { ffi::IMG_isCUR(self.raw()) == 1 }
    }
    fn is_ico(&self) -> bool {
        unsafe { ffi::IMG_isICO(self.raw()) == 1 }
    }
    fn is_bmp(&self) -> bool {
        unsafe { ffi::IMG_isBMP(self.raw()) == 1 }
    }
    fn is_pnm(&self) -> bool {
        unsafe { ffi::IMG_isPNM(self.raw()) == 1 }
    }
    fn is_xpm(&self) -> bool {
        unsafe { ffi::IMG_isXPM(self.raw()) == 1 }
    }
    fn is_xcf(&self) -> bool {
        unsafe { ffi::IMG_isXCF(self.raw()) == 1 }
    }
    fn is_pcx(&self) -> bool {
        unsafe { ffi::IMG_isPCX(self.raw()) == 1 }
    }
    fn is_gif(&self) -> bool {
        unsafe { ffi::IMG_isGIF(self.raw()) == 1 }
    }
    fn is_jpg(&self) -> bool {
        unsafe { ffi::IMG_isJPG(self.raw()) == 1 }
    }
    fn is_tif(&self) -> bool {
        unsafe { ffi::IMG_isTIF(self.raw()) == 1 }
    }
    fn is_png(&self) -> bool {
        unsafe { ffi::IMG_isPNG(self.raw()) == 1 }
    }
    fn is_lbm(&self) -> bool {
        unsafe { ffi::IMG_isLBM(self.raw()) == 1 }
    }
    fn is_xv(&self)  -> bool {
        unsafe { ffi::IMG_isXV(self.raw())  == 1 }
    }
    fn is_webp(&self) -> bool {
        unsafe { ffi::IMG_isWEBP(self.raw())  == 1 }
    }
}
<|endoftext|>


<commit_before><commit_msg>notify tx<commit_after><|endoftext|>


<commit_before><commit_msg>Initial commit for uninstallation.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Correct description of homeserver discovery endpoint.<commit_after><|endoftext|>


<commit_before><commit_msg>update exotic pagerank<commit_after>// #![feature(scoped)]
// #![feature(collections)]

extern crate mmap;
extern crate time;
extern crate timely;
extern crate columnar;
extern crate dataflow_join;

extern crate docopt;
use docopt::Docopt;

use std::thread;

use dataflow_join::graph::{GraphTrait, GraphMMap};

use timely::progress::timestamp::RootTimestamp;
use timely::progress::scope::Scope;
use timely::progress::nested::Summary::Local;
use timely::example_static::*;
use timely::communication::*;
use timely::communication::pact::Exchange;

use timely::networking::initialize_networking;
use timely::networking::initialize_networking_from_file;

use timely::drain::DrainExt;

static USAGE: &'static str = "
Usage: pagerank <source> [options] [<arguments>...]

Options:
    -w <arg>, --workers <arg>    number of workers per process [default: 1]
    -p <arg>, --processid <arg>  identity of this process      [default: 0]
    -n <arg>, --processes <arg>  number of processes involved  [default: 1]
    -h <arg>, --hosts <arg>      list of host:port for workers
";

fn main () {
    let args = Docopt::new(USAGE).and_then(|dopt| dopt.parse()).unwrap_or_else(|e| e.exit());

    // let workers = if let Ok(threads) = args.get_str("<workers>").parse() { threads }
    //               else { panic!("invalid setting for workers: {}", args.get_str("<workers>")) };
    // println!("starting pagerank dataflow with {:?} worker{}", workers, if workers == 1 { "" } else { "s" });
    let source = args.get_str("<source>").to_owned();

    let workers: u64 = if let Ok(threads) = args.get_str("-w").parse() { threads }
                       else { panic!("invalid setting for --workers: {}", args.get_str("-t")) };
    let process_id: u64 = if let Ok(proc_id) = args.get_str("-p").parse() { proc_id }
                          else { panic!("invalid setting for --processid: {}", args.get_str("-p")) };
    let processes: u64 = if let Ok(processes) = args.get_str("-n").parse() { processes }
                         else { panic!("invalid setting for --processes: {}", args.get_str("-n")) };

    println!("Starting pagerank dataflow with");
    println!("\tworkers:\t{}", workers);
    println!("\tprocesses:\t{}", processes);
    println!("\tprocessid:\t{}", process_id);

    // vector holding communicators to use; one per local worker.
    if processes > 1 {
        println!("Initializing BinaryCommunicator");

        let hosts = args.get_str("-h");
        let communicators = if hosts != "" {
            initialize_networking_from_file(hosts, process_id, workers).ok().expect("error initializing networking")
        }
        else {
            let addresses = (0..processes).map(|index| format!("localhost:{}", 2101 + index).to_string()).collect();
            initialize_networking(addresses, process_id, workers).ok().expect("error initializing networking")
        };

        pagerank_multi(communicators, source);
    }
    else if workers > 1 {
        println!("Initializing ProcessCommunicator");
        pagerank_multi(ProcessCommunicator::new_vector(workers), source);
    }
    else {
        println!("Initializing ThreadCommunicator");
        pagerank_multi(vec![ThreadCommunicator], source);
    };
}

fn pagerank_multi<C>(communicators: Vec<C>, filename: String)
where C: Communicator+Send {
    let mut guards = Vec::new();
    let workers = communicators.len();
    for communicator in communicators.into_iter() {
        let filename = filename.clone();
        guards.push(thread::Builder::new().name(format!("timely worker {}", communicator.index()))
                                          .spawn(move || pagerank(communicator, filename, workers))
                                          .unwrap());
    }

    for guard in guards { guard.join().unwrap(); }
}

fn pagerank<C>(communicator: C, filename: String, workers: usize)
where C: Communicator {
    let index = communicator.index() as usize;
    let peers = communicator.peers() as usize;

    let mut root = GraphRoot::new(communicator);

    {   // new scope avoids long borrow on root
        let mut builder = root.new_subgraph();

        // establish the beginnings of a loop,
        // 20 iterations, each time around += 1.
        let (helper, stream) = builder.loop_variable::<(u32, f32)>(RootTimestamp::new(20), Local(1));

        let graph = GraphMMap::<u32>::new(&filename);

        let nodes = graph.nodes();

        let mut src = vec![1.0; 1 + (nodes / peers as usize)];  // local rank accumulation
        // let mut dst = vec![0.0; nodes];                         // local rank accumulation

        let mut start = time::precise_time_s();

        // from feedback, place an operator that
        // aggregates and broadcasts ranks along edges.
        let ranks = stream.enable(builder).unary_notify(

            Exchange::new(|x: &(u32, f32)| x.0 as u64),     // 1. how data should be exchanged
            format!("PageRank"),                            // 2. a tasteful, descriptive name
            vec![RootTimestamp::new(0)],                    // 3. indicate an initial capability
            move |input, output, iterator| {                // 4. provide the operator logic

                while let Some((iter, _)) = iterator.next() {

                    let mut session = output.session(&iter);

                    // /---- should look familiar! ----\
                    for node in 0..src.len() {
                        src[node] = 0.15 + 0.85 * src[node];
                    }

                    for node in 0..src.len() {
                        let edges = graph.edges(index + peers * node);
                        let value = src[node] / edges.len() as f32;
                        for &b in edges {
                            session.give((b, value));
                        }
                    }
                    // \------ end familiar part ------/

                    println!("iteration {:?}: {}s", iter, time::precise_time_s() - start);
                    start = time::precise_time_s();
                }

                while let Some((iter, data)) = input.pull() {
                    iterator.notify_at(&iter);
                    for (node, rank) in data.drain_temp() {
                        src[node as usize / peers] += rank;
                    }
                }
            }
        );

        // let local_index = index as usize % workers;
        // let mut acc = vec![0.0; 1 + (nodes / workers)];

        ranks
        // .unary_notify(
        //     Exchange::new(move |x: &(u32, f32)| (workers * (index / workers)) as u64 + (x.0 as u64 % workers as u64)),
        //     format!("Aggregation"),
        //     vec![],
        //     move |input, output, iterator| {
        //         while let Some((iter, data)) = input.pull() {
        //             iterator.notify_at(&iter);
        //             for (node, rank) in data.drain_temp() {
        //                 acc[node as usize / workers] += rank;
        //             }
        //         }
        //
        //         while let Some((item, _)) = iterator.next() {
        //
        //             output.give_at(&item, acc.drain_temp().enumerate().filter(|x| x.1 != 0.0)
        //                                      .map(|(u,f)| (((u * workers + local_index) as u32), f)));
        //
        //             for _ in 0..(1 + (nodes/workers)) { acc.push(0.0); }
        //             assert!(acc.len() == (1 + (nodes/workers)));
        //         }
        //     }
        // )
        .connect_loop(helper);
    }

    while root.step() { }
}
<|endoftext|>