<commit_before>extern crate hyper;
extern crate openssl;
extern crate unix_socket;
extern crate url;

use hyper::{ Client, Url };
use hyper::method::Method;
use hyper::net::NetworkConnector;
use openssl::x509::X509FileType;
use std::io::{ Read, Write };
use std::{ env, result };
use std::path::Path;
use std::io::Error;
use unix_socket::UnixStream;
use url::{ Host, RelativeSchemeData, SchemeData };

pub type Result<T> = result::Result<T, Error>;

trait Transport {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String>;
}

pub struct Docker {
  transport: Box<Transport>
}

impl Transport for UnixStream {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String> {
     let method_str = match method {
       Method::Put    => "PUT",
       Method::Post   => "POST",
       Method::Delete => "DELETE",
                _     => "GET"
     };
     let req = format!("{} {} HTTP/1.0\r\n\r\n", method_str, endpoint);
     try!(self.write_all(req.as_bytes()));
     let mut result = String::new();
     self.read_to_string(&mut result).map(|_| result)
  }
}

impl<C: NetworkConnector> Transport for (Client<C>, String) {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String> {
    let uri = format!("{}{}", self.1, endpoint);
    let req = match method {
       Method::Put    => self.0.put(&uri[..]),
       Method::Post   => self.0.post(&uri[..]),
       Method::Delete => self.0.delete(&uri[..]),
                    _ => self.0.get(&uri[..])
    };
    let mut res = match req.send() {
      Ok(r) => r,
      Err(e) => panic!("failed request {:?}", e)
    };
    let mut body = String::new();
    res.read_to_string(&mut body).map(|_| body)
  }
}

pub struct Image<'a, 'b> {
  docker: &'a mut Docker,
  name: &'b str
}

impl<'a, 'b> Image<'a, 'b> {
  pub fn new(docker: &'a mut Docker, name: &'b str) -> Image<'a, 'b> {
    Image { docker: docker, name: name }
  }

  pub fn inspect(self) -> Result<String> {
    self.docker.get(&format!("/images/{}/json", self.name)[..])
  }

  pub fn history(self) -> Result<String> {
    self.docker.get(&format!("/images/{}/history", self.name)[..])
  }

  pub fn delete(self) -> Result<String> {
    self.docker.delete(&format!("/images/{}", self.name)[..])
  }
}

pub struct Images<'a> {
  docker: &'a mut Docker
}

impl<'a> Images<'a> {
  pub fn new(docker: &'a mut Docker) -> Images<'a> {
    Images { docker: docker }
  }

  pub fn list(self) -> Result<String> {
    self.docker.get("/images/json")
  }

  pub fn get(&'a mut self, name: &'a str) -> Image {
    Image::new(self.docker, name)
  }

  pub fn search(self, term: &str) -> Result<String> {
    self.docker.get(&format!("/images/search?term={}", term)[..])
  }
}

pub struct Container<'a, 'b> {
  docker: &'a mut Docker,
  id: &'b str
}

impl<'a, 'b> Container<'a, 'b> {
  pub fn new(docker: &'a mut Docker, id: &'b str) -> Container<'a, 'b> {
    Container { docker: docker, id: id }
  }

  pub fn inspect(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/json", self.id)[..])
  }
}

pub struct Containers<'a> {
  docker: &'a mut Docker
}

impl<'a> Containers<'a> {
  pub fn new(docker: &'a mut Docker) -> Containers<'a> {
    Containers { docker: docker }
  }

  pub fn list(self) -> Result<String> {
    self.docker.get("/containers/json")
  }

  pub fn get(&'a mut self, name: &'a str) -> Container {
    Container::new(self.docker, name)
  }
}

// https://docs.docker.com/reference/api/docker_remote_api_v1.17/
impl Docker {
  pub fn new() -> Docker {
    let host = env::var("DOCKER_HOST")
        .map(|h| Url::parse(&h).ok()
             .expect("invalid url"))
          .ok()
          .expect("expected host");
    let domain = match host.scheme_data {
        SchemeData::NonRelative(s) => s,
        SchemeData::Relative(RelativeSchemeData { host: host, .. }) =>
          match host {
              Host::Domain(s) => s,
              Host::Ipv6(a)   => a.to_string()
          }
    };
    match &host.scheme[..] {
      "unix" => {
        let stream =
          match UnixStream::connect(domain) {
            Err(_) => panic!("failed to connect to socket"),
            Ok(s) => s
          };
        Docker { transport: Box::new(stream) }
      },
          _  => {
        let mut client = Client::new();
        client.set_ssl_verifier(Box::new(|ssl_ctx| {
          match env::var("DOCKER_CERT_PATH").ok() {
            Some(ref certs) => {
              let cert = &format!("{}/cert.pem", certs);
              let key = &format!("{}/key.pem", certs);
              ssl_ctx.set_certificate_file(&Path::new(cert), X509FileType::PEM);
              ssl_ctx.set_private_key_file(&Path::new(key), X509FileType::PEM);
              match env::var("DOCKER_TLS_VERIFY").ok() {
                Some(_) => {
                  let ca = &format!("{}/ca.pem", certs);
                  ssl_ctx.set_CA_file(&Path::new(ca));
                }, _ => ()
              };
              ()
            },  _ => ()
          }
        }));
        let tup = (client, format!("https:{}", domain.to_string()));
        Docker { transport: Box::new(tup) }
      }
    }
  }

  pub fn images<'a>(&'a mut self) -> Images {
    Images::new(self)
  }

  pub fn containers<'a>(&'a mut self) -> Containers {
    Containers::new(self)
  }

  pub fn version(&mut self) -> Result<String> {
    self.get("/version")
  }

  pub fn info(&mut self) -> Result<String> {
    self.get("/info")
  }

  pub fn ping(&mut self) -> Result<String> {
    self.get("/_ping")
  }

  // todo stream
  pub fn events(&mut self) -> Result<String> {
    self.get("/events")
  }

  fn get(&mut self, endpoint: &str) -> Result<String> {
    (*self.transport).request(Method::Get, endpoint)
  }

  fn delete(&mut self, endpoint: &str) -> Result<String> {
     (*self.transport).request(Method::Delete, endpoint)
   }
}
<commit_msg>more methods<commit_after>extern crate hyper;
extern crate openssl;
extern crate unix_socket;
extern crate url;

use hyper::{ Client, Url };
use hyper::method::Method;
use hyper::net::NetworkConnector;
use openssl::x509::X509FileType;
use std::io::{ Read, Write };
use std::{ env, result };
use std::path::Path;
use std::io::Error;
use unix_socket::UnixStream;
use url::{ Host, RelativeSchemeData, SchemeData };

pub type Result<T> = result::Result<T, Error>;

trait Transport {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String>;
}

pub struct Docker {
  transport: Box<Transport>
}

impl Transport for UnixStream {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String> {
     let method_str = match method {
       Method::Put    => "PUT",
       Method::Post   => "POST",
       Method::Delete => "DELETE",
                _     => "GET"
     };
     let req = format!("{} {} HTTP/1.0\r\n\r\n", method_str, endpoint);
     try!(self.write_all(req.as_bytes()));
     let mut result = String::new();
     self.read_to_string(&mut result).map(|_| result)
  }
}

impl<C: NetworkConnector> Transport for (Client<C>, String) {
  fn request(&mut self, method: Method, endpoint: &str) -> Result<String> {
    let uri = format!("{}{}", self.1, endpoint);
    let req = match method {
       Method::Put    => self.0.put(&uri[..]),
       Method::Post   => self.0.post(&uri[..]),
       Method::Delete => self.0.delete(&uri[..]),
                    _ => self.0.get(&uri[..])
    };
    let mut res = match req.send() {
      Ok(r) => r,
      Err(e) => panic!("failed request {:?}", e)
    };
    let mut body = String::new();
    res.read_to_string(&mut body).map(|_| body)
  }
}

pub struct Image<'a, 'b> {
  docker: &'a mut Docker,
  name: &'b str
}

impl<'a, 'b> Image<'a, 'b> {
  pub fn new(docker: &'a mut Docker, name: &'b str) -> Image<'a, 'b> {
    Image { docker: docker, name: name }
  }

  pub fn inspect(self) -> Result<String> {
    self.docker.get(&format!("/images/{}/json", self.name)[..])
  }

  pub fn history(self) -> Result<String> {
    self.docker.get(&format!("/images/{}/history", self.name)[..])
  }

  pub fn delete(self) -> Result<String> {
    self.docker.delete(&format!("/images/{}", self.name)[..])
  }
}

pub struct Images<'a> {
  docker: &'a mut Docker
}

impl<'a> Images<'a> {
  pub fn new(docker: &'a mut Docker) -> Images<'a> {
    Images { docker: docker }
  }

  pub fn list(self) -> Result<String> {
    self.docker.get("/images/json")
  }

  pub fn get(&'a mut self, name: &'a str) -> Image {
    Image::new(self.docker, name)
  }

  pub fn search(self, term: &str) -> Result<String> {
    self.docker.get(&format!("/images/search?term={}", term)[..])
  }
}

pub struct Container<'a, 'b> {
  docker: &'a mut Docker,
  id: &'b str
}

impl<'a, 'b> Container<'a, 'b> {
  pub fn new(docker: &'a mut Docker, id: &'b str) -> Container<'a, 'b> {
    Container { docker: docker, id: id }
  }

  pub fn inspect(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/json", self.id)[..])
  }

  pub fn top(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/top", self.id)[..])
  }

  pub fn logs(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/logs", self.id)[..])
  }

  pub fn changes(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/changes", self.id)[..])
  }

  pub fn stats(self) -> Result<String> {
    self.docker.get(&format!("/containers/{}/stats", self.id)[..])
  }

  pub fn start(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/start", self.id)[..])
  }

  pub fn stop(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/stop", self.id)[..])
  }

  pub fn restart(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/restart", self.id)[..])
  }

  pub fn kill(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/kill", self.id)[..])
  }

  pub fn rename(self, name: &str) -> Result<String> {
    self.docker.post(&format!("/containers/{}/rename?name={}", self.id, name)[..])
  }

  pub fn pause(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/pause", self.id)[..])
  }

  pub fn unpause(self) -> Result<String> {
    self.docker.post(&format!("/containers/{}/unpause", self.id)[..])
  }
}

pub struct Containers<'a> {
  docker: &'a mut Docker
}

impl<'a> Containers<'a> {
  pub fn new(docker: &'a mut Docker) -> Containers<'a> {
    Containers { docker: docker }
  }

  pub fn list(self) -> Result<String> {
    self.docker.get("/containers/json")
  }

  pub fn get(&'a mut self, name: &'a str) -> Container {
    Container::new(self.docker, name)
  }
}

// https://docs.docker.com/reference/api/docker_remote_api_v1.17/
impl Docker {
  pub fn new() -> Docker {
    let host = env::var("DOCKER_HOST")
        .map(|h| Url::parse(&h).ok()
             .expect("invalid url"))
          .ok()
          .expect("expected host");
    let domain = match host.scheme_data {
        SchemeData::NonRelative(s) => s,
        SchemeData::Relative(RelativeSchemeData { host: host, .. }) =>
          match host {
              Host::Domain(s) => s,
              Host::Ipv6(a)   => a.to_string()
          }
    };
    match &host.scheme[..] {
      "unix" => {
        let stream =
          match UnixStream::connect(domain) {
            Err(_) => panic!("failed to connect to socket"),
            Ok(s) => s
          };
        Docker { transport: Box::new(stream) }
      },
          _  => {
        let mut client = Client::new();
        client.set_ssl_verifier(Box::new(|ssl_ctx| {
          match env::var("DOCKER_CERT_PATH").ok() {
            Some(ref certs) => {
              let cert = &format!("{}/cert.pem", certs);
              let key = &format!("{}/key.pem", certs);
              ssl_ctx.set_certificate_file(&Path::new(cert), X509FileType::PEM);
              ssl_ctx.set_private_key_file(&Path::new(key), X509FileType::PEM);
              match env::var("DOCKER_TLS_VERIFY").ok() {
                Some(_) => {
                  let ca = &format!("{}/ca.pem", certs);
                  ssl_ctx.set_CA_file(&Path::new(ca));
                }, _ => ()
              };
              ()
            },  _ => ()
          }
        }));
        let tup = (client, format!("https:{}", domain.to_string()));
        Docker { transport: Box::new(tup) }
      }
    }
  }

  pub fn images<'a>(&'a mut self) -> Images {
    Images::new(self)
  }

  pub fn containers<'a>(&'a mut self) -> Containers {
    Containers::new(self)
  }

  pub fn version(&mut self) -> Result<String> {
    self.get("/version")
  }

  pub fn info(&mut self) -> Result<String> {
    self.get("/info")
  }

  pub fn ping(&mut self) -> Result<String> {
    self.get("/_ping")
  }

  // todo stream
  pub fn events(&mut self) -> Result<String> {
    self.get("/events")
  }

  fn get(&mut self, endpoint: &str) -> Result<String> {
    (*self.transport).request(Method::Get, endpoint)
  }

  fn post(&mut self, endpoint: &str) -> Result<String> {
    (*self.transport).request(Method::Post, endpoint)
  }

  fn delete(&mut self, endpoint: &str) -> Result<String> {
     (*self.transport).request(Method::Delete, endpoint)
   }
}
<|endoftext|>


<commit_before>extern crate nalgebra;

use nalgebra::{DMat, Zero, Indexable};
use std::ops::{Add, Sub};
use std::fmt::{Display};

/// This trait describes the type of values within a summed area table source.
/// Implementing this trait for your type allows it to become a value within a source.
pub trait SourceValue<T>: Display + Zero + Clone + Copy + Add<T,Output=T> + Sub<T,Output=T> {
}

/// This trait describes a generic source for a summed area table.
/// Implementing this trait for your type allows it to become the source for a summed area table calculation.
pub trait SummedAreaTableSource<T: SourceValue<T>>{

	/// Returns a matrix of source values of type T.
	/// The calculated summed area table will be based on these values.
	fn get_values(&self) -> &DMat<T>;

	/// Calculates and returns the summed area table for the source matrix.
	fn calculate_summed_area_table(&self) -> SummedAreaTable<T>{
		let vals = self.get_values();
		let mut table = DMat::new_zeros(vals.nrows(),vals.ncols());

		for row in (0 ..vals.nrows()) {
			for col in (0 ..vals.ncols()) {
				let mut sum = vals.at((row, col));

				if row>0 {
					sum = sum+ table.at((row-1, col));
				}
				if col>0 {
					sum = sum+ table.at((row, col-1));
				}
				if row>0 && col>0 {
					sum = sum - table.at((row-1, col-1));
				}
				table.set((row,col), sum);
			}
		}

		SummedAreaTable::<T>{table: table}
	}
}

/// This struct is the result of a summed area table calculation.
pub struct SummedAreaTable<T: SourceValue<T>> {
	table: DMat<T>,
}

impl <T: SourceValue<T>>SummedAreaTable<T> {

	/// Returns the sum for a given area.
	/// That is described by its upper left and lower right point.
	/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
	/// `to` is a x/y coordinate tuple for the lower right point (inclusive)
	fn get_sum(&self, from: (usize,usize), to: (usize,usize)) -> T{
		let (x1, y1) = from;
		let (x2, y2) = to;

		let mut sum = self.table.at((x2,y2));

		if x1 > 0 {
			sum = sum - self.table.at((x1-1,y2));
		}
		if y1 > 0 {
			sum = sum - self.table.at((x2,y1-1));
		}
		if x1 > 0 && y1 > 0 {
			sum = sum + self.table.at((x1-1,y1-1));
		}
		sum
	}
}

impl SourceValue<usize> for usize {
}

impl SummedAreaTableSource<usize> for DMat<usize>{
	fn get_values(&self) -> &DMat<usize> {
		self
	}
}

#[test]
fn zeros() {
	let src: DMat<usize> = DMat::new_zeros(100,100);
	let table = src.calculate_summed_area_table();
	assert_eq!(0, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(10000, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones_without_first_col_row() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(10000-199, table.get_sum((1,1),(99,99)));
}

#[test]
fn twos() {
	let src: DMat<usize> = DMat::from_elem(100,100,2);
	let table = src.calculate_summed_area_table();
	assert_eq!(20000, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones_quartered() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(2500, table.get_sum((0,0),(49,49)));
	assert_eq!(2500, table.get_sum((50,50),(99,99)));
	assert_eq!(2500, table.get_sum((50,0),(99,49)));
	assert_eq!(2500, table.get_sum((0,50),(49,99)));
}

#[test]
fn twos_quartered() {
	let src: DMat<usize> = DMat::from_elem(100,100,2);
	let table = src.calculate_summed_area_table();
	assert_eq!(5000, table.get_sum((0,0),(49,49)));
	assert_eq!(5000, table.get_sum((50,50),(99,99)));
	assert_eq!(5000, table.get_sum((50,0),(99,49)));
	assert_eq!(5000, table.get_sum((0,50),(49,99)));
}

<commit_msg>added two tests<commit_after>extern crate nalgebra;

use nalgebra::{DMat, Zero, Indexable};
use std::ops::{Add, Sub};
use std::fmt::{Display};

/// This trait describes the type of values within a summed area table source.
/// Implementing this trait for your type allows it to become a value within a source.
pub trait SourceValue<T>: Display + Zero + Clone + Copy + Add<T,Output=T> + Sub<T,Output=T> {
}

/// This trait describes a generic source for a summed area table.
/// Implementing this trait for your type allows it to become the source for a summed area table calculation.
pub trait SummedAreaTableSource<T: SourceValue<T>>{

	/// Returns a matrix of source values of type T.
	/// The calculated summed area table will be based on these values.
	fn get_values(&self) -> &DMat<T>;

	/// Calculates and returns the summed area table for the source matrix.
	fn calculate_summed_area_table(&self) -> SummedAreaTable<T>{
		let vals = self.get_values();
		let mut table = DMat::new_zeros(vals.nrows(),vals.ncols());

		for row in (0 ..vals.nrows()) {
			for col in (0 ..vals.ncols()) {
				let mut sum = vals.at((row, col));

				if row>0 {
					sum = sum+ table.at((row-1, col));
				}
				if col>0 {
					sum = sum+ table.at((row, col-1));
				}
				if row>0 && col>0 {
					sum = sum - table.at((row-1, col-1));
				}
				table.set((row,col), sum);
			}
		}

		SummedAreaTable::<T>{table: table}
	}
}

/// This struct is the result of a summed area table calculation.
pub struct SummedAreaTable<T: SourceValue<T>> {
	table: DMat<T>,
}

impl <T: SourceValue<T>>SummedAreaTable<T> {

	/// Returns the sum for a given area.
	/// That is described by its upper left and lower right point.
	/// `from` is a x/y coordinate tuple for the upper left point (inclusive)
	/// `to` is a x/y coordinate tuple for the lower right point (inclusive)
	fn get_sum(&self, from: (usize,usize), to: (usize,usize)) -> T{
		let (x1, y1) = from;
		let (x2, y2) = to;

		let mut sum = self.table.at((x2,y2));

		if x1 > 0 {
			sum = sum - self.table.at((x1-1,y2));
		}
		if y1 > 0 {
			sum = sum - self.table.at((x2,y1-1));
		}
		if x1 > 0 && y1 > 0 {
			sum = sum + self.table.at((x1-1,y1-1));
		}
		sum
	}
}

impl SourceValue<usize> for usize {
}

impl SummedAreaTableSource<usize> for DMat<usize>{
	fn get_values(&self) -> &DMat<usize> {
		self
	}
}

#[test]
fn zeros() {
	let src: DMat<usize> = DMat::new_zeros(100,100);
	let table = src.calculate_summed_area_table();
	assert_eq!(0, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(10000, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones_without_first_col_row() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(10000-199, table.get_sum((1,1),(99,99)));
}

#[test]
fn twos() {
	let src: DMat<usize> = DMat::from_elem(100,100,2);
	let table = src.calculate_summed_area_table();
	assert_eq!(20000, table.get_sum((0,0),(99,99)));
}

#[test]
fn ones_quartered() {
	let src: DMat<usize> = DMat::from_elem(100,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(2500, table.get_sum((0,0),(49,49)));
	assert_eq!(2500, table.get_sum((50,50),(99,99)));
	assert_eq!(2500, table.get_sum((50,0),(99,49)));
	assert_eq!(2500, table.get_sum((0,50),(49,99)));
}

#[test]
fn twos_quartered() {
	let src: DMat<usize> = DMat::from_elem(100,100,2);
	let table = src.calculate_summed_area_table();
	assert_eq!(5000, table.get_sum((0,0),(49,49)));
	assert_eq!(5000, table.get_sum((50,50),(99,99)));
	assert_eq!(5000, table.get_sum((50,0),(99,49)));
	assert_eq!(5000, table.get_sum((0,50),(49,99)));
}

#[test]
fn first_row() {
	let src: DMat<usize> = DMat::from_elem(100,50,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(50, table.get_sum((0,0),(49,0)));
}

#[test]
fn first_col() {
	let src: DMat<usize> = DMat::from_elem(50,100,1);
	let table = src.calculate_summed_area_table();
	assert_eq!(50, table.get_sum((0,0),(0,49)));
}

<|endoftext|>


<commit_before>//! # Cursive
//!
//! [Cursive] is a [TUI] library - it lets you easily build rich interfaces
//! for use in a terminal.
//!
//! [Cursive]: https://github.com/gyscos/Cursive
//! [TUI]: https://en.wikipedia.org/wiki/Text-based_user_interface
//!
//! ## Getting started
//!
//! * Every application should start with a [`Cursive`](struct.Cursive.html)
//!   object. It is the main entry-point to the library.
//! * A declarative phase then describes the structure of the UI by adding
//!   views and configuring their behaviours.
//! * Finally, the event loop is started by calling
//!   [`Cursive::run(&mut self)`](struct.Cursive.html#method.run).
//!
//! ## Views
//!
//! Views are the main components of a cursive interface.
//! The [`views`](./views/index.html) module contains many views to use in your
//! application; if you don't find what you need, you may also implement the
//! [`View`](view/trait.View.html) trait and build your own.
//!
//! ## Callbacks
//!
//! Cursive is a *reactive* UI: it *reacts* to events generated by user input.
//!
//! During the declarative phase, callbacks are set to trigger on specific
//! events. These functions usually take a `&mut Cursive` argument, allowing
//! them to modify the view tree at will.
//!
//! ## Examples
//!
//! ```rust
//! extern crate cursive;
//!
//! use cursive::Cursive;
//! use cursive::views::TextView;
//!
//! fn main() {
//!     let mut siv = Cursive::dummy();
//!
//!     siv.add_layer(TextView::new("Hello World!\nPress q to quit."));
//!
//!     siv.add_global_callback('q', |s| s.quit());
//!
//!     siv.run();
//! }
//! ```
//!
//! ## Debugging
//!
//! The `Cursive` root initializes the terminal on creation, and do cleanups
//! on drop. While it is alive, printing to the terminal will not work
//! as expected, making debugging a bit harder.
//!
//! One solution is to redirect stderr to a file when running the application,
//! and log to it instead of stdout.
//!
//! Or you can use gdb as usual.
#![deny(missing_docs)]

#[macro_use]
extern crate enum_map;
#[macro_use]
extern crate enumset;
#[macro_use]
extern crate log;
#[macro_use]
extern crate crossbeam_channel;

#[cfg(any(feature = "ncurses", feature = "pancurses"))]
#[macro_use]
extern crate maplit;

// We use chan_signal to detect SIGWINCH.
// It's not how windows work, so no need to use that.
#[cfg(unix)]
extern crate signal_hook;

extern crate libc;
extern crate num;
extern crate owning_ref;
extern crate toml;
extern crate unicode_segmentation;
extern crate unicode_width;
extern crate xi_unicode;

macro_rules! new_default(
    ($c:ty) => {
        impl Default for $c {
            fn default() -> Self {
                Self::new()
            }
        }
    }
);

pub mod traits;

pub mod event;
#[macro_use]
pub mod view;

#[macro_use]
pub mod utils;

pub mod align;
pub mod direction;
pub mod menu;
pub mod rect;
pub mod theme;
pub mod vec;
pub mod views;

// This probably doesn't need to be public?
mod cursive;
mod printer;
mod with;
mod xy;

mod div;
mod utf8;

#[doc(hidden)]
pub mod backend;

pub use cursive::{CbFunc, Cursive, ScreenId};
pub use printer::Printer;
pub use vec::Vec2;
pub use with::With;
pub use xy::XY;
<commit_msg>Rephrase doc<commit_after>//! # Cursive
//!
//! [Cursive] is a [TUI] library - it lets you easily build rich interfaces
//! for use in a terminal.
//!
//! [Cursive]: https://github.com/gyscos/Cursive
//! [TUI]: https://en.wikipedia.org/wiki/Text-based_user_interface
//!
//! ## Getting started
//!
//! * Every application should start with a [`Cursive`](struct.Cursive.html)
//!   object. It is the main entry-point to the library.
//! * A declarative phase then describes the structure of the UI by adding
//!   views and configuring their behaviours.
//! * Finally, the event loop is started by calling
//!   [`Cursive::run(&mut self)`](struct.Cursive.html#method.run).
//!
//! ## Views
//!
//! Views are the main components of a cursive interface.
//! The [`views`](./views/index.html) module contains many views to use in your
//! application; if you don't find what you need, you may also implement the
//! [`View`](view/trait.View.html) trait and build your own.
//!
//! ## Callbacks
//!
//! Cursive is callback-driven: it reacts to events generated by user input.
//!
//! During the declarative phase, callbacks are set to trigger on specific
//! events. These functions usually take a `&mut Cursive` argument, allowing
//! them to modify the view tree at will.
//!
//! ## Examples
//!
//! ```rust
//! extern crate cursive;
//!
//! use cursive::Cursive;
//! use cursive::views::TextView;
//!
//! fn main() {
//!     let mut siv = Cursive::dummy();
//!
//!     siv.add_layer(TextView::new("Hello World!\nPress q to quit."));
//!
//!     siv.add_global_callback('q', |s| s.quit());
//!
//!     siv.run();
//! }
//! ```
//!
//! ## Debugging
//!
//! The `Cursive` root initializes the terminal on creation, and do cleanups
//! on drop. While it is alive, printing to the terminal will not work
//! as expected, making debugging a bit harder.
//!
//! One solution is to redirect stderr to a file when running the application,
//! and log to it instead of stdout.
//!
//! Or you can use gdb as usual.
#![deny(missing_docs)]

#[macro_use]
extern crate enum_map;
#[macro_use]
extern crate enumset;
#[macro_use]
extern crate log;
#[macro_use]
extern crate crossbeam_channel;

#[cfg(any(feature = "ncurses", feature = "pancurses"))]
#[macro_use]
extern crate maplit;

// We use chan_signal to detect SIGWINCH.
// It's not how windows work, so no need to use that.
#[cfg(unix)]
extern crate signal_hook;

extern crate libc;
extern crate num;
extern crate owning_ref;
extern crate toml;
extern crate unicode_segmentation;
extern crate unicode_width;
extern crate xi_unicode;

macro_rules! new_default(
    ($c:ty) => {
        impl Default for $c {
            fn default() -> Self {
                Self::new()
            }
        }
    }
);

pub mod traits;

pub mod event;
#[macro_use]
pub mod view;

#[macro_use]
pub mod utils;

pub mod align;
pub mod direction;
pub mod menu;
pub mod rect;
pub mod theme;
pub mod vec;
pub mod views;

// This probably doesn't need to be public?
mod cursive;
mod printer;
mod with;
mod xy;

mod div;
mod utf8;

#[doc(hidden)]
pub mod backend;

pub use cursive::{CbFunc, Cursive, ScreenId};
pub use printer::Printer;
pub use vec::Vec2;
pub use with::With;
pub use xy::XY;
<|endoftext|>


<commit_before>extern crate num;
extern crate rand;
extern crate time;
extern crate openssl;
extern crate byteorder;
extern crate rustc_serialize;

pub mod apns;

pub use apns::APNS;
pub use apns::Payload;
pub use apns::PayloadAPS;
pub use apns::PayloadAPSAlert;
<commit_msg>compatible with the latest rust nightly<commit_after>#![feature(lookup_host)]
#![feature(ip_addr)]
#![feature(old_io)]

extern crate num;
extern crate rand;
extern crate time;
extern crate openssl;
extern crate byteorder;
extern crate rustc_serialize;

pub mod apns;

pub use apns::APNS;
pub use apns::Payload;
pub use apns::PayloadAPS;
pub use apns::PayloadAPSAlert;
<|endoftext|>


<commit_before>#![feature(
    rustc_private,
    decl_macro,
    type_alias_impl_trait,
    associated_type_bounds,
    never_type,
    try_blocks,
    box_patterns,
    hash_drain_filter
)]
#![warn(rust_2018_idioms)]
#![warn(unused_lifetimes)]
#![warn(unreachable_pub)]

extern crate snap;
#[macro_use]
extern crate rustc_middle;
extern crate rustc_ast;
extern crate rustc_codegen_ssa;
extern crate rustc_data_structures;
extern crate rustc_errors;
extern crate rustc_fs_util;
extern crate rustc_hir;
extern crate rustc_incremental;
extern crate rustc_index;
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_target;

// This prevents duplicating functions and statics that are already part of the host rustc process.
#[allow(unused_extern_crates)]
extern crate rustc_driver;

use std::any::Any;
use std::str::FromStr;

use rustc_codegen_ssa::traits::CodegenBackend;
use rustc_codegen_ssa::CodegenResults;
use rustc_errors::ErrorReported;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoader};
use rustc_middle::ty::query::Providers;
use rustc_session::config::OutputFilenames;
use rustc_session::Session;

use cranelift_codegen::settings::{self, Configurable};

use crate::constant::ConstantCx;
use crate::prelude::*;

mod abi;
mod allocator;
mod analyze;
mod archive;
mod backend;
mod base;
mod cast;
mod codegen_i128;
mod common;
mod constant;
mod debuginfo;
mod discriminant;
mod driver;
mod inline_asm;
mod intrinsics;
mod linkage;
mod main_shim;
mod metadata;
mod num;
mod optimize;
mod pointer;
mod pretty_clif;
mod toolchain;
mod trap;
mod unsize;
mod value_and_place;
mod vtable;

mod prelude {
    pub(crate) use std::convert::{TryFrom, TryInto};

    pub(crate) use rustc_span::Span;

    pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
    pub(crate) use rustc_middle::bug;
    pub(crate) use rustc_middle::mir::{self, *};
    pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
    pub(crate) use rustc_middle::ty::{
        self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
        TypeFoldable, UintTy,
    };
    pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};

    pub(crate) use rustc_data_structures::fx::FxHashMap;

    pub(crate) use rustc_index::vec::Idx;

    pub(crate) use cranelift_codegen::entity::EntitySet;
    pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
    pub(crate) use cranelift_codegen::ir::function::Function;
    pub(crate) use cranelift_codegen::ir::types;
    pub(crate) use cranelift_codegen::ir::{
        AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
        StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
    };
    pub(crate) use cranelift_codegen::isa::{self, CallConv};
    pub(crate) use cranelift_codegen::Context;
    pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
    pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module};

    pub(crate) use crate::abi::*;
    pub(crate) use crate::base::{codegen_operand, codegen_place};
    pub(crate) use crate::cast::*;
    pub(crate) use crate::common::*;
    pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
    pub(crate) use crate::pointer::Pointer;
    pub(crate) use crate::trap::*;
    pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
}

struct PrintOnPanic<F: Fn() -> String>(F);
impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
    fn drop(&mut self) {
        if ::std::thread::panicking() {
            println!("{}", (self.0)());
        }
    }
}

struct CodegenCx<'m, 'tcx: 'm> {
    tcx: TyCtxt<'tcx>,
    module: &'m mut dyn Module,
    global_asm: String,
    constants_cx: ConstantCx,
    cached_context: Context,
    vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
    debug_context: Option<DebugContext<'tcx>>,
    unwind_context: UnwindContext<'tcx>,
}

impl<'m, 'tcx> CodegenCx<'m, 'tcx> {
    fn new(
        tcx: TyCtxt<'tcx>,
        backend_config: BackendConfig,
        module: &'m mut dyn Module,
        debug_info: bool,
    ) -> Self {
        let unwind_context = UnwindContext::new(
            tcx,
            module.isa(),
            matches!(backend_config.codegen_mode, CodegenMode::Aot),
        );
        let debug_context =
            if debug_info { Some(DebugContext::new(tcx, module.isa())) } else { None };
        CodegenCx {
            tcx,
            module,
            global_asm: String::new(),
            constants_cx: ConstantCx::default(),
            cached_context: Context::new(),
            vtables: FxHashMap::default(),
            debug_context,
            unwind_context,
        }
    }

    fn finalize(self) -> (String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
        self.constants_cx.finalize(self.tcx, self.module);
        (self.global_asm, self.debug_context, self.unwind_context)
    }
}

#[derive(Copy, Clone, Debug)]
pub enum CodegenMode {
    Aot,
    Jit,
    JitLazy,
}

impl Default for CodegenMode {
    fn default() -> Self {
        CodegenMode::Aot
    }
}

impl FromStr for CodegenMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "aot" => Ok(CodegenMode::Aot),
            "jit" => Ok(CodegenMode::Jit),
            "jit-lazy" => Ok(CodegenMode::JitLazy),
            _ => Err(format!("Unknown codegen mode `{}`", s)),
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
pub struct BackendConfig {
    pub codegen_mode: CodegenMode,
}

impl BackendConfig {
    fn from_opts(opts: &[String]) -> Result<Self, String> {
        let mut config = BackendConfig::default();
        for opt in opts {
            if let Some((name, value)) = opt.split_once('=') {
                match name {
                    "mode" => config.codegen_mode = value.parse()?,
                    _ => return Err(format!("Unknown option `{}`", name)),
                }
            } else {
                return Err(format!("Invalid option `{}`", opt));
            }
        }
        Ok(config)
    }
}

pub struct CraneliftCodegenBackend {
    pub config: Option<BackendConfig>,
}

impl CodegenBackend for CraneliftCodegenBackend {
    fn init(&self, sess: &Session) {
        if sess.lto() != rustc_session::config::Lto::No && sess.opts.cg.embed_bitcode {
            sess.warn("LTO is not supported. You may get a linker error.");
        }
    }

    fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
        Box::new(crate::metadata::CraneliftMetadataLoader)
    }

    fn provide(&self, _providers: &mut Providers) {}
    fn provide_extern(&self, _providers: &mut Providers) {}

    fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
        vec![]
    }

    fn codegen_crate(
        &self,
        tcx: TyCtxt<'_>,
        metadata: EncodedMetadata,
        need_metadata_module: bool,
    ) -> Box<dyn Any> {
        let config = if let Some(config) = self.config {
            config
        } else {
            BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
                .unwrap_or_else(|err| tcx.sess.fatal(&err))
        };
        driver::codegen_crate(tcx, metadata, need_metadata_module, config)
    }

    fn join_codegen(
        &self,
        ongoing_codegen: Box<dyn Any>,
        _sess: &Session,
    ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
        Ok(*ongoing_codegen
            .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
            .unwrap())
    }

    fn link(
        &self,
        sess: &Session,
        codegen_results: CodegenResults,
        outputs: &OutputFilenames,
    ) -> Result<(), ErrorReported> {
        use rustc_codegen_ssa::back::link::link_binary;

        let target_cpu = crate::target_triple(sess).to_string();
        link_binary::<crate::archive::ArArchiveBuilder<'_>>(
            sess,
            &codegen_results,
            outputs,
            &codegen_results.crate_name.as_str(),
            &target_cpu,
        );

        Ok(())
    }
}

fn target_triple(sess: &Session) -> target_lexicon::Triple {
    sess.target.llvm_target.parse().unwrap()
}

fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
    use target_lexicon::BinaryFormat;

    let target_triple = crate::target_triple(sess);

    let mut flags_builder = settings::builder();
    flags_builder.enable("is_pic").unwrap();
    flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
    let enable_verifier =
        cfg!(debug_assertions) || std::env::var("CG_CLIF_ENABLE_VERIFIER").is_ok();
    flags_builder.set("enable_verifier", if enable_verifier { "true" } else { "false" }).unwrap();

    let tls_model = match target_triple.binary_format {
        BinaryFormat::Elf => "elf_gd",
        BinaryFormat::Macho => "macho",
        BinaryFormat::Coff => "coff",
        _ => "none",
    };
    flags_builder.set("tls_model", tls_model).unwrap();

    flags_builder.set("enable_simd", "true").unwrap();

    flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();

    use rustc_session::config::OptLevel;
    match sess.opts.optimize {
        OptLevel::No => {
            flags_builder.set("opt_level", "none").unwrap();
        }
        OptLevel::Less | OptLevel::Default => {}
        OptLevel::Aggressive => {
            flags_builder.set("opt_level", "speed_and_size").unwrap();
        }
        OptLevel::Size | OptLevel::SizeMin => {
            sess.warn("Optimizing for size is not supported. Just ignoring the request");
        }
    }

    let flags = settings::Flags::new(flags_builder);

    let variant = cranelift_codegen::isa::BackendVariant::MachInst;
    let mut isa_builder = cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
    // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
    // is interpreted as `bsr`.
    isa_builder.enable("nehalem").unwrap();
    isa_builder.finish(flags)
}

/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
#[no_mangle]
pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
    Box::new(CraneliftCodegenBackend { config: None })
}
<commit_msg>Suppress an unnecessary warning and fix an incorrect warning<commit_after>#![feature(
    rustc_private,
    decl_macro,
    type_alias_impl_trait,
    associated_type_bounds,
    never_type,
    try_blocks,
    box_patterns,
    hash_drain_filter
)]
#![warn(rust_2018_idioms)]
#![warn(unused_lifetimes)]
#![warn(unreachable_pub)]

extern crate snap;
#[macro_use]
extern crate rustc_middle;
extern crate rustc_ast;
extern crate rustc_codegen_ssa;
extern crate rustc_data_structures;
extern crate rustc_errors;
extern crate rustc_fs_util;
extern crate rustc_hir;
extern crate rustc_incremental;
extern crate rustc_index;
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_target;

// This prevents duplicating functions and statics that are already part of the host rustc process.
#[allow(unused_extern_crates)]
extern crate rustc_driver;

use std::any::Any;
use std::str::FromStr;

use rustc_codegen_ssa::traits::CodegenBackend;
use rustc_codegen_ssa::CodegenResults;
use rustc_errors::ErrorReported;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoader};
use rustc_middle::ty::query::Providers;
use rustc_session::config::OutputFilenames;
use rustc_session::Session;

use cranelift_codegen::settings::{self, Configurable};

use crate::constant::ConstantCx;
use crate::prelude::*;

mod abi;
mod allocator;
mod analyze;
mod archive;
mod backend;
mod base;
mod cast;
mod codegen_i128;
mod common;
mod constant;
mod debuginfo;
mod discriminant;
mod driver;
mod inline_asm;
mod intrinsics;
mod linkage;
mod main_shim;
mod metadata;
mod num;
mod optimize;
mod pointer;
mod pretty_clif;
mod toolchain;
mod trap;
mod unsize;
mod value_and_place;
mod vtable;

mod prelude {
    pub(crate) use std::convert::{TryFrom, TryInto};

    pub(crate) use rustc_span::Span;

    pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE};
    pub(crate) use rustc_middle::bug;
    pub(crate) use rustc_middle::mir::{self, *};
    pub(crate) use rustc_middle::ty::layout::{self, TyAndLayout};
    pub(crate) use rustc_middle::ty::{
        self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
        TypeFoldable, UintTy,
    };
    pub(crate) use rustc_target::abi::{Abi, LayoutOf, Scalar, Size, VariantIdx};

    pub(crate) use rustc_data_structures::fx::FxHashMap;

    pub(crate) use rustc_index::vec::Idx;

    pub(crate) use cranelift_codegen::entity::EntitySet;
    pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
    pub(crate) use cranelift_codegen::ir::function::Function;
    pub(crate) use cranelift_codegen::ir::types;
    pub(crate) use cranelift_codegen::ir::{
        AbiParam, Block, ExternalName, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc,
        StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value,
    };
    pub(crate) use cranelift_codegen::isa::{self, CallConv};
    pub(crate) use cranelift_codegen::Context;
    pub(crate) use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
    pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module};

    pub(crate) use crate::abi::*;
    pub(crate) use crate::base::{codegen_operand, codegen_place};
    pub(crate) use crate::cast::*;
    pub(crate) use crate::common::*;
    pub(crate) use crate::debuginfo::{DebugContext, UnwindContext};
    pub(crate) use crate::pointer::Pointer;
    pub(crate) use crate::trap::*;
    pub(crate) use crate::value_and_place::{CPlace, CPlaceInner, CValue};
}

struct PrintOnPanic<F: Fn() -> String>(F);
impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
    fn drop(&mut self) {
        if ::std::thread::panicking() {
            println!("{}", (self.0)());
        }
    }
}

struct CodegenCx<'m, 'tcx: 'm> {
    tcx: TyCtxt<'tcx>,
    module: &'m mut dyn Module,
    global_asm: String,
    constants_cx: ConstantCx,
    cached_context: Context,
    vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
    debug_context: Option<DebugContext<'tcx>>,
    unwind_context: UnwindContext<'tcx>,
}

impl<'m, 'tcx> CodegenCx<'m, 'tcx> {
    fn new(
        tcx: TyCtxt<'tcx>,
        backend_config: BackendConfig,
        module: &'m mut dyn Module,
        debug_info: bool,
    ) -> Self {
        let unwind_context = UnwindContext::new(
            tcx,
            module.isa(),
            matches!(backend_config.codegen_mode, CodegenMode::Aot),
        );
        let debug_context =
            if debug_info { Some(DebugContext::new(tcx, module.isa())) } else { None };
        CodegenCx {
            tcx,
            module,
            global_asm: String::new(),
            constants_cx: ConstantCx::default(),
            cached_context: Context::new(),
            vtables: FxHashMap::default(),
            debug_context,
            unwind_context,
        }
    }

    fn finalize(self) -> (String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
        self.constants_cx.finalize(self.tcx, self.module);
        (self.global_asm, self.debug_context, self.unwind_context)
    }
}

#[derive(Copy, Clone, Debug)]
pub enum CodegenMode {
    Aot,
    Jit,
    JitLazy,
}

impl Default for CodegenMode {
    fn default() -> Self {
        CodegenMode::Aot
    }
}

impl FromStr for CodegenMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "aot" => Ok(CodegenMode::Aot),
            "jit" => Ok(CodegenMode::Jit),
            "jit-lazy" => Ok(CodegenMode::JitLazy),
            _ => Err(format!("Unknown codegen mode `{}`", s)),
        }
    }
}

#[derive(Copy, Clone, Debug, Default)]
pub struct BackendConfig {
    pub codegen_mode: CodegenMode,
}

impl BackendConfig {
    fn from_opts(opts: &[String]) -> Result<Self, String> {
        let mut config = BackendConfig::default();
        for opt in opts {
            if let Some((name, value)) = opt.split_once('=') {
                match name {
                    "mode" => config.codegen_mode = value.parse()?,
                    _ => return Err(format!("Unknown option `{}`", name)),
                }
            } else {
                return Err(format!("Invalid option `{}`", opt));
            }
        }
        Ok(config)
    }
}

pub struct CraneliftCodegenBackend {
    pub config: Option<BackendConfig>,
}

impl CodegenBackend for CraneliftCodegenBackend {
    fn init(&self, sess: &Session) {
        use rustc_session::config::Lto;
        match sess.lto() {
            Lto::No | Lto::ThinLocal => {}
            Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."),
        }
    }

    fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
        Box::new(crate::metadata::CraneliftMetadataLoader)
    }

    fn provide(&self, _providers: &mut Providers) {}
    fn provide_extern(&self, _providers: &mut Providers) {}

    fn target_features(&self, _sess: &Session) -> Vec<rustc_span::Symbol> {
        vec![]
    }

    fn codegen_crate(
        &self,
        tcx: TyCtxt<'_>,
        metadata: EncodedMetadata,
        need_metadata_module: bool,
    ) -> Box<dyn Any> {
        let config = if let Some(config) = self.config {
            config
        } else {
            BackendConfig::from_opts(&tcx.sess.opts.cg.llvm_args)
                .unwrap_or_else(|err| tcx.sess.fatal(&err))
        };
        driver::codegen_crate(tcx, metadata, need_metadata_module, config)
    }

    fn join_codegen(
        &self,
        ongoing_codegen: Box<dyn Any>,
        _sess: &Session,
    ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
        Ok(*ongoing_codegen
            .downcast::<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)>()
            .unwrap())
    }

    fn link(
        &self,
        sess: &Session,
        codegen_results: CodegenResults,
        outputs: &OutputFilenames,
    ) -> Result<(), ErrorReported> {
        use rustc_codegen_ssa::back::link::link_binary;

        let target_cpu = crate::target_triple(sess).to_string();
        link_binary::<crate::archive::ArArchiveBuilder<'_>>(
            sess,
            &codegen_results,
            outputs,
            &codegen_results.crate_name.as_str(),
            &target_cpu,
        );

        Ok(())
    }
}

fn target_triple(sess: &Session) -> target_lexicon::Triple {
    sess.target.llvm_target.parse().unwrap()
}

fn build_isa(sess: &Session) -> Box<dyn isa::TargetIsa + 'static> {
    use target_lexicon::BinaryFormat;

    let target_triple = crate::target_triple(sess);

    let mut flags_builder = settings::builder();
    flags_builder.enable("is_pic").unwrap();
    flags_builder.set("enable_probestack", "false").unwrap(); // __cranelift_probestack is not provided
    let enable_verifier =
        cfg!(debug_assertions) || std::env::var("CG_CLIF_ENABLE_VERIFIER").is_ok();
    flags_builder.set("enable_verifier", if enable_verifier { "true" } else { "false" }).unwrap();

    let tls_model = match target_triple.binary_format {
        BinaryFormat::Elf => "elf_gd",
        BinaryFormat::Macho => "macho",
        BinaryFormat::Coff => "coff",
        _ => "none",
    };
    flags_builder.set("tls_model", tls_model).unwrap();

    flags_builder.set("enable_simd", "true").unwrap();

    flags_builder.set("enable_llvm_abi_extensions", "true").unwrap();

    use rustc_session::config::OptLevel;
    match sess.opts.optimize {
        OptLevel::No => {
            flags_builder.set("opt_level", "none").unwrap();
        }
        OptLevel::Less | OptLevel::Default => {}
        OptLevel::Size | OptLevel::SizeMin | OptLevel::Aggressive => {
            flags_builder.set("opt_level", "speed_and_size").unwrap();
        }
    }

    let flags = settings::Flags::new(flags_builder);

    let variant = cranelift_codegen::isa::BackendVariant::MachInst;
    let mut isa_builder = cranelift_codegen::isa::lookup_variant(target_triple, variant).unwrap();
    // Don't use "haswell", as it implies `has_lzcnt`.macOS CI is still at Ivy Bridge EP, so `lzcnt`
    // is interpreted as `bsr`.
    isa_builder.enable("nehalem").unwrap();
    isa_builder.finish(flags)
}

/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
#[no_mangle]
pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
    Box::new(CraneliftCodegenBackend { config: None })
}
<|endoftext|>


<commit_before>#![feature(generators, generator_trait, conservative_impl_trait, proc_macro)]

extern crate futures_await as futures;

use std::ops::{Generator, GeneratorState};
use futures::prelude::{async, await};

struct AsyncGenerator<T>
where T: Generator
{
    generator: T
}

impl<T> AsyncGenerator<T>
where T: Generator
{
    fn new(generator: T) -> Self {
        AsyncGenerator {
            generator: generator
        }
    }

    #[async]
    fn resume(&mut self) -> GeneratorState<T::Yield, T::Return> {
        unimplemented!()
    }
}

trait IntoAsync<T>
where T: Generator
{
    fn into_async(self) -> AsyncGenerator<T>;
}

impl<T> IntoAsync<T> for T
where T: Generator
{
    fn into_async(self) -> AsyncGenerator<T> {
        AsyncGenerator::new(self)
    }
}

impl<T> Iterator for AsyncGenerator<T>
where T: Generator
{
    type Item = T::Yield;

    fn next(&mut self) -> Option<Self::Item> {
        match await!(self.resume()) {
            Ok(GeneratorState::Yielded(next_item))=> next_item,
            _ => None
        }
    }
}

#[cfg(test)]
mod tests {
    fn dummy_generator() -> impl Generator {
        || {
            yield 1;
            yield 2;
            yield 3;
            return "done";
        }
    }

    #[test]
    fn it_works() {
        let test : Vec<_> = dummy_generator().into_async().collect();
    }
}
<commit_msg>First compiling version<commit_after>#![feature(generators, generator_trait, conservative_impl_trait, proc_macro)]

extern crate futures_await as futures;

use std::ops::Generator;
use futures::prelude::*;

struct AsyncGenerator<T>
where T: Generator
{
    generator: T,
    values: Vec<T::Yield>
}

impl<T> AsyncGenerator<T>
where T: Generator + 'static
{
    fn new(generator: T) -> Self {
        AsyncGenerator {
            generator: generator,
            values: Vec::new()
        }
    }

    #[async]
    fn resume(&mut self) -> Result<T::Yield, T::Return> {
        unimplemented!()
    }
}

trait IntoAsync<T>
where T: Generator
{
    fn into_async(self) -> AsyncGenerator<T>;
}

impl<T> IntoAsync<T> for T
where T: Generator + 'static
{
    fn into_async(self) -> AsyncGenerator<T> {
        AsyncGenerator::new(self)
    }
}

impl<T> Iterator for AsyncGenerator<T>
where T: Generator + 'static
{
    type Item = T::Yield;

    fn next(&mut self) -> Option<Self::Item> {
        let future = async_block! {
            await!(self.resume())
        };
        match future.wait() {
            Ok(next_value) => Some(next_value),
            Err(_) => None
        }
    }
}

#[cfg(test)]
mod tests {
    use std::ops::Generator;
    use IntoAsync;

    fn dummy_generator() -> impl Generator<Yield=u32, Return=()> {
        || {
            yield 1;
            yield 2;
            yield 3;
            return;
        }
    }

    #[test]
    fn it_works() {
        let test : Vec<_> = dummy_generator().into_async().collect();

        assert_eq!(vec![1u32, 2, 3], test);
    }
}
<|endoftext|>


<commit_before>use std::io::File;
use std::collections::BTreeMap;

fn main() {
    let chain = load_chain_from_file(&Path::new(".test"));
    println!("Chain {}", chain);
}

fn load_content_from_file(path: &Path) -> String {
    match File::open(path).read_to_string() {
        Ok(c)  => c,
        Err(e) => panic!("failed because of {}", e),
    }
}

fn load_chain_from_file(path: &Path) -> BTreeMap<String, BTreeMap<String, uint>> {
    let file_content = load_content_from_file(path);
    let mut table: BTreeMap<String, BTreeMap<String, uint>> = BTreeMap::new();
    let mut previous_word: String = "".to_string();
    for word in file_content.split_str(" ".as_slice()) {
        if !table.contains_key(&word.into_string()) {
            table.insert(word.to_string(), BTreeMap::new());
        }
        if previous_word.as_slice() != "".as_slice() {
            let mut val = table.get_mut(&previous_word.to_string()).unwrap();
            if val.contains_key(&word.to_string()) {
                let count = val.remove(&word.to_string()).unwrap();
                val.insert(word.to_string(), count + 1u);
            } else {
                val.insert(word.to_string(), 1u);
            }
        }
        previous_word = word.to_string();
    }
    table
}

fn iter_for_word(word: String, chain: BTreeMap<String, BTreeMap<String, uint>>) {
    println!("String {}", word);

}<commit_msg>Updated to latest Rust<commit_after>#![allow(unstable)]

use std::io::File;
use std::collections::BTreeMap;

fn main() {
    let chain = load_chain_from_file(&Path::new(".test"));
    println!("Chain {:?}", chain);
}

fn load_content_from_file(path: &Path) -> String {
    match File::open(path).read_to_string() {
        Ok(c)  => c,
        Err(e) => panic!("failed because of {:?}", e),
    }
}

fn load_chain_from_file(path: &Path) -> BTreeMap<String, BTreeMap<String, usize>> {
    let file_content = load_content_from_file(path);
    let mut table: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
    let mut previous_word: String = "".to_string();
    for word in file_content.split_str(" ".as_slice()) {
        if !table.contains_key(&word.to_string()) {
            table.insert(word.to_string(), BTreeMap::new());
        }
        if previous_word.as_slice() != "".as_slice() {
            let mut val = table.get_mut(&previous_word.to_string()).unwrap();
            if val.contains_key(&word.to_string()) {
                let count = val.remove(&word.to_string()).unwrap();
                val.insert(word.to_string(), count + 1us);
            } else {
                val.insert(word.to_string(), 1us);
            }
        }
        previous_word = word.to_string();
    }
    table
}

fn iter_for_word(word: String, chain: BTreeMap<String, BTreeMap<String, usize>>) {
    println!("String {}", word);

}<|endoftext|>


<commit_before>
extern crate python3_sys as py_ffi;
extern crate numpy_sys as np_ffi;
extern crate cpython;
<commit_msg>Add pointer access<commit_after>
extern crate python3_sys as py_ffi;
extern crate numpy_sys as np_ffi;
extern crate cpython;

use cpython::PyObject;

pub struct PyArray(PyObject);

impl PyArray {
    pub fn as_ptr(&self) -> *mut np_ffi::PyArrayObject {
        self.0.as_ptr() as *mut np_ffi::PyArrayObject
    }
    pub fn steal_ptr(self) -> *mut np_ffi::PyArrayObject {
        self.0.steal_ptr() as *mut np_ffi::PyArrayObject
    }
}
<|endoftext|>


<commit_before>#![crate_type = "lib"]
#![crate_name = "lolog"]

///
/// Work in progress, don't use it.
///
///     lolog::init(log::LogLevel::Info, std::io::stderr());
///
extern crate log;
extern crate time;

use std::io;

use log::{LogRecord, LogLevel, LogMetadata, SetLoggerError};
use std::sync::{Arc, Mutex};

pub struct Logger<Writer: io::Write + Send> {
    max_level: LogLevel,
    output: Arc<Mutex<Writer>>,
}

impl<W: io::Write + Send> log::Log for Logger<W> {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.max_level
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            let o = self.output.clone();
            let mut f = o.lock().unwrap();

            let line = format!("{} {}\n", time::now().rfc3339(), record.args());
            f.write_all(line.as_bytes())
             .expect("Couldn't write to log file");
        }
    }
}

impl<W: io::Write + Send> Logger<W> {
    pub fn new(max_level: LogLevel, writer: W) -> Self {
        Logger {
            max_level: max_level,
            output: Arc::new(Mutex::new(writer)),
        }
    }
}

pub fn install<W: 'static + io::Write + Send>(logger: Logger<W>) -> Result<(), SetLoggerError> {
    log::set_logger(move |max_log_level| {
        max_log_level.set(logger.max_level.to_log_level_filter());
        Box::new(logger)
    })
}

pub fn init<W: 'static + io::Write + Send>(level: LogLevel,
                                           output: W)
                                           -> Result<(), SetLoggerError> {
    log::set_logger(move |max_log_level| {
        max_log_level.set(level.to_log_level_filter());
        Box::new(Logger::new(level, output))
    })
}

#[cfg(test)]
mod test {
    #[test]
    fn it_works() {}
}
<commit_msg>Remove \n at the end<commit_after>#![crate_type = "lib"]
#![crate_name = "lolog"]

///
/// Work in progress, don't use it.
///
///     lolog::init(log::LogLevel::Info, std::io::stderr());
///
extern crate log;
extern crate time;

use std::io;

use log::{LogRecord, LogLevel, LogMetadata, SetLoggerError};
use std::sync::{Arc, Mutex};

pub struct Logger<Writer: io::Write + Send> {
    max_level: LogLevel,
    output: Arc<Mutex<Writer>>,
}

impl<W: io::Write + Send> log::Log for Logger<W> {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.max_level
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            let o = self.output.clone();
            let mut f = o.lock().unwrap();

            let line = format!("{} {}", time::now().rfc3339(), record.args());
            f.write_all(line.as_bytes())
             .expect("Couldn't write to log file");
        }
    }
}

impl<W: io::Write + Send> Logger<W> {
    pub fn new(max_level: LogLevel, writer: W) -> Self {
        Logger {
            max_level: max_level,
            output: Arc::new(Mutex::new(writer)),
        }
    }
}

pub fn install<W: 'static + io::Write + Send>(logger: Logger<W>) -> Result<(), SetLoggerError> {
    log::set_logger(move |max_log_level| {
        max_log_level.set(logger.max_level.to_log_level_filter());
        Box::new(logger)
    })
}

pub fn init<W: 'static + io::Write + Send>(level: LogLevel,
                                           output: W)
                                           -> Result<(), SetLoggerError> {
    log::set_logger(move |max_log_level| {
        max_log_level.set(level.to_log_level_filter());
        Box::new(Logger::new(level, output))
    })
}

#[cfg(test)]
mod test {
    #[test]
    fn it_works() {}
}
<|endoftext|>


<commit_before>// Copyright 2013-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

//! # **glib**, **gobject** and **gio** bindings for Rust
//!
//! This library contains
//!
//! - bindings to some essential GLib, GObject, GIO types and APIs,
//!
//! - common building blocks used in both handmade and machine generated
//! bindings to GTK+ and other GLib-based libraries.
//!
//! It is the foundation for higher level libraries with uniform Rusty (safe and
//! strongly typed) APIs. It avoids exposing GLib-specific data types where
//! possible and is not meant to provide comprehensive GLib bindings, which
//! would often amount to duplicating the Rust Standard Library or other utility
//! crates.
//!
//! The library is a work in progress: expect missing functionality and breaking
//! changes.
//!
//! # Dynamic typing
//!
//! Most types in the GLib family have type identifiers
//! ([`Type`](types/enum.Type.html)). Their corresponding Rust types implement
//! the [`StaticType`](types/trait.StaticType.html) trait.
//!
//! Dynamically typed [`Value`](value/index.html) can carry values of any `T:
//! StaticType`.
//!
//! [`Variant`](variant/index.html) can carry values of `T: StaticVariantType`.
//!
//! # Errors
//!
//! Errors are represented by [`Error`](error/struct.Error.html), which can
//! carry values from various [error
//! domains](error/trait.ErrorDomain.html#implementors) (such as
//! [`FileError`](enum.FileError.html)).
//!
//! # Objects
//!
//! Each class and interface has a corresponding smart pointer struct
//! representing an instance of that type (e.g. `Object` for `GObject`,
//! `gtk::Widget` for `GtkWidget`). They are reference counted and feature
//! interior mutability similarly to Rust's `Rc<RefCell<T>>` idiom.
//! Consequently, cloning objects is cheap and their methods never require
//! mutable borrows. Two smart pointers are equal iff they point to the same
//! object.
//!
//! The root of the object hierarchy is [`Object`](object/struct.Object.html).
//! Inheritance and subtyping is denoted with the [`IsA`](object/trait.IsA.html)
//! marker trait. The [`Cast`](object/trait.Cast.html) trait enables upcasting
//! and downcasting.
//!
//! Interfaces and non-leaf classes also have corresponding traits (e.g.
//! `ObjectExt` and `gtk::WidgetExt`), which are blanketly implemented for all
//! their subtypes.
//!
//! For creating new subclasses of `Object` or other object types this crate has to be compiled
//! with the `subclassing` feature to enable the [`subclass`](subclass/index.html) module. Check
//! the module's documentation for further details and a code example.
//!
//! # Under the hood
//!
//! GLib-based libraries largely operate on pointers to various boxed or
//! reference counted structures so the bindings have to implement corresponding
//! smart pointers (wrappers), which encapsulate resource management and safety
//! checks. Such wrappers are defined via the
//! [`glib_wrapper!`](macro.glib_wrapper!.html) macro, which uses abstractions
//! defined in the [`wrapper`](wrapper/index.html), [`boxed`](boxed/index.html),
//! [`shared`](shared/index.html) and [`object`](object/index.html) modules.
//!
//! The [`translate`](translate/index.html) module defines and partly implements
//! conversions between high level Rust types (including the aforementioned
//! wrappers) and their FFI counterparts.

#![allow(clippy::doc_markdown)]
#![allow(clippy::unreadable_literal)]
#![cfg_attr(feature = "futures", feature(futures_api, arbitrary_self_types))]

#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate lazy_static;
extern crate libc;

#[doc(hidden)]
pub extern crate glib_sys;
#[doc(hidden)]
pub extern crate gobject_sys;

#[cfg(feature = "futures")]
pub extern crate futures;

use std::ffi::CStr;
pub use bytes::Bytes;
pub use string::String;
pub use closure::Closure;
pub use error::{Error, BoolError};
pub use file_error::FileError;
pub use object::{
    Cast,
    IsA,
    IsClassFor,
    Object,
    ObjectExt,
    ObjectClass,
    ObjectType,
    InitiallyUnowned,
    InitiallyUnownedClass,
    WeakRef,
    SendWeakRef,
};
pub use signal::{
    SignalHandlerId,
    signal_handler_block,
    signal_handler_disconnect,
    signal_handler_unblock,
    signal_stop_emission_by_name
};

pub use types::{
    StaticType,
    Type,
};
pub use value::{
    ToValue,
    ToSendValue,
    TypedValue,
    SendValue,
    Value,
};
pub use variant::{
    StaticVariantType,
    ToVariant,
    Variant,
};
pub use variant_type::{
    VariantTy,
    VariantType,
};
pub use time_val::{
    TimeVal,
    get_current_time,
};
pub use enums::{
    UserDirectory,
    EnumClass,
    EnumValue,
    FlagsClass,
    FlagsValue,
    FlagsBuilder,
};

#[macro_use]
pub mod wrapper;
#[macro_use]
pub mod boxed;
#[macro_use]
pub mod shared;
#[macro_use]
pub mod error;
#[macro_use]
pub mod object;

pub use auto::*;
pub use auto::functions::*;
#[allow(clippy::let_and_return)]
#[allow(clippy::let_unit_value)]
#[allow(clippy::too_many_arguments)]
#[allow(non_upper_case_globals)]
mod auto;

pub use gobject::*;
mod gobject;

mod bytes;
mod string;
pub mod char;
pub use char::*;
mod checksum;
pub mod closure;
mod enums;
mod file_error;
mod key_file;
pub mod prelude;
pub mod signal;
pub mod source;
pub use source::*;
mod time_val;
#[macro_use]
pub mod translate;
mod gstring;
pub use gstring::GString;
pub mod types;
mod utils;
pub use utils::*;
pub mod value;
pub mod variant;
mod variant_type;
mod main_context;
mod main_context_channel;
pub use main_context_channel::{Sender, SyncSender, Receiver};
mod date;
pub use date::Date;
mod value_array;
pub use value_array::ValueArray;
mod param_spec;
pub use param_spec::ParamSpec;
mod quark;
pub use quark::Quark;

pub mod send_unique;
pub use send_unique::{
    SendUniqueCell,
    SendUnique,
};

#[cfg(feature="futures")]
mod main_context_futures;
#[cfg(feature="futures")]
mod source_futures;
#[cfg(feature="futures")]
pub use source_futures::*;

// Actual thread IDs can be reused by the OS once the old thread finished.
// This works around it by using our own counter for threads.
//
// Taken from the fragile crate
use std::sync::atomic::{AtomicUsize, Ordering};
fn next_thread_id() -> usize {
    static mut COUNTER: AtomicUsize = AtomicUsize::new(0);
    unsafe { COUNTER.fetch_add(1, Ordering::SeqCst) }
}

pub(crate) fn get_thread_id() -> usize {
    thread_local!(static THREAD_ID: usize = next_thread_id());
    THREAD_ID.with(|&x| x)
}

#[macro_use]
#[cfg(any(feature = "dox", feature="subclassing"))]
pub mod subclass;
<commit_msg>Remove #![feature] gate for futures<commit_after>// Copyright 2013-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

//! # **glib**, **gobject** and **gio** bindings for Rust
//!
//! This library contains
//!
//! - bindings to some essential GLib, GObject, GIO types and APIs,
//!
//! - common building blocks used in both handmade and machine generated
//! bindings to GTK+ and other GLib-based libraries.
//!
//! It is the foundation for higher level libraries with uniform Rusty (safe and
//! strongly typed) APIs. It avoids exposing GLib-specific data types where
//! possible and is not meant to provide comprehensive GLib bindings, which
//! would often amount to duplicating the Rust Standard Library or other utility
//! crates.
//!
//! The library is a work in progress: expect missing functionality and breaking
//! changes.
//!
//! # Dynamic typing
//!
//! Most types in the GLib family have type identifiers
//! ([`Type`](types/enum.Type.html)). Their corresponding Rust types implement
//! the [`StaticType`](types/trait.StaticType.html) trait.
//!
//! Dynamically typed [`Value`](value/index.html) can carry values of any `T:
//! StaticType`.
//!
//! [`Variant`](variant/index.html) can carry values of `T: StaticVariantType`.
//!
//! # Errors
//!
//! Errors are represented by [`Error`](error/struct.Error.html), which can
//! carry values from various [error
//! domains](error/trait.ErrorDomain.html#implementors) (such as
//! [`FileError`](enum.FileError.html)).
//!
//! # Objects
//!
//! Each class and interface has a corresponding smart pointer struct
//! representing an instance of that type (e.g. `Object` for `GObject`,
//! `gtk::Widget` for `GtkWidget`). They are reference counted and feature
//! interior mutability similarly to Rust's `Rc<RefCell<T>>` idiom.
//! Consequently, cloning objects is cheap and their methods never require
//! mutable borrows. Two smart pointers are equal iff they point to the same
//! object.
//!
//! The root of the object hierarchy is [`Object`](object/struct.Object.html).
//! Inheritance and subtyping is denoted with the [`IsA`](object/trait.IsA.html)
//! marker trait. The [`Cast`](object/trait.Cast.html) trait enables upcasting
//! and downcasting.
//!
//! Interfaces and non-leaf classes also have corresponding traits (e.g.
//! `ObjectExt` and `gtk::WidgetExt`), which are blanketly implemented for all
//! their subtypes.
//!
//! For creating new subclasses of `Object` or other object types this crate has to be compiled
//! with the `subclassing` feature to enable the [`subclass`](subclass/index.html) module. Check
//! the module's documentation for further details and a code example.
//!
//! # Under the hood
//!
//! GLib-based libraries largely operate on pointers to various boxed or
//! reference counted structures so the bindings have to implement corresponding
//! smart pointers (wrappers), which encapsulate resource management and safety
//! checks. Such wrappers are defined via the
//! [`glib_wrapper!`](macro.glib_wrapper!.html) macro, which uses abstractions
//! defined in the [`wrapper`](wrapper/index.html), [`boxed`](boxed/index.html),
//! [`shared`](shared/index.html) and [`object`](object/index.html) modules.
//!
//! The [`translate`](translate/index.html) module defines and partly implements
//! conversions between high level Rust types (including the aforementioned
//! wrappers) and their FFI counterparts.

#![allow(clippy::doc_markdown)]
#![allow(clippy::unreadable_literal)]

#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate lazy_static;
extern crate libc;

#[doc(hidden)]
pub extern crate glib_sys;
#[doc(hidden)]
pub extern crate gobject_sys;

#[cfg(feature = "futures")]
pub extern crate futures;

use std::ffi::CStr;
pub use bytes::Bytes;
pub use string::String;
pub use closure::Closure;
pub use error::{Error, BoolError};
pub use file_error::FileError;
pub use object::{
    Cast,
    IsA,
    IsClassFor,
    Object,
    ObjectExt,
    ObjectClass,
    ObjectType,
    InitiallyUnowned,
    InitiallyUnownedClass,
    WeakRef,
    SendWeakRef,
};
pub use signal::{
    SignalHandlerId,
    signal_handler_block,
    signal_handler_disconnect,
    signal_handler_unblock,
    signal_stop_emission_by_name
};

pub use types::{
    StaticType,
    Type,
};
pub use value::{
    ToValue,
    ToSendValue,
    TypedValue,
    SendValue,
    Value,
};
pub use variant::{
    StaticVariantType,
    ToVariant,
    Variant,
};
pub use variant_type::{
    VariantTy,
    VariantType,
};
pub use time_val::{
    TimeVal,
    get_current_time,
};
pub use enums::{
    UserDirectory,
    EnumClass,
    EnumValue,
    FlagsClass,
    FlagsValue,
    FlagsBuilder,
};

#[macro_use]
pub mod wrapper;
#[macro_use]
pub mod boxed;
#[macro_use]
pub mod shared;
#[macro_use]
pub mod error;
#[macro_use]
pub mod object;

pub use auto::*;
pub use auto::functions::*;
#[allow(clippy::let_and_return)]
#[allow(clippy::let_unit_value)]
#[allow(clippy::too_many_arguments)]
#[allow(non_upper_case_globals)]
mod auto;

pub use gobject::*;
mod gobject;

mod bytes;
mod string;
pub mod char;
pub use char::*;
mod checksum;
pub mod closure;
mod enums;
mod file_error;
mod key_file;
pub mod prelude;
pub mod signal;
pub mod source;
pub use source::*;
mod time_val;
#[macro_use]
pub mod translate;
mod gstring;
pub use gstring::GString;
pub mod types;
mod utils;
pub use utils::*;
pub mod value;
pub mod variant;
mod variant_type;
mod main_context;
mod main_context_channel;
pub use main_context_channel::{Sender, SyncSender, Receiver};
mod date;
pub use date::Date;
mod value_array;
pub use value_array::ValueArray;
mod param_spec;
pub use param_spec::ParamSpec;
mod quark;
pub use quark::Quark;

pub mod send_unique;
pub use send_unique::{
    SendUniqueCell,
    SendUnique,
};

#[cfg(feature="futures")]
mod main_context_futures;
#[cfg(feature="futures")]
mod source_futures;
#[cfg(feature="futures")]
pub use source_futures::*;

// Actual thread IDs can be reused by the OS once the old thread finished.
// This works around it by using our own counter for threads.
//
// Taken from the fragile crate
use std::sync::atomic::{AtomicUsize, Ordering};
fn next_thread_id() -> usize {
    static mut COUNTER: AtomicUsize = AtomicUsize::new(0);
    unsafe { COUNTER.fetch_add(1, Ordering::SeqCst) }
}

pub(crate) fn get_thread_id() -> usize {
    thread_local!(static THREAD_ID: usize = next_thread_id());
    THREAD_ID.with(|&x| x)
}

#[macro_use]
#[cfg(any(feature = "dox", feature="subclassing"))]
pub mod subclass;
<|endoftext|>


<commit_before>use super::{Point, LatLon};
use projection::Projection;
use layer::Layer;

///
/// Represents a map view
///
/// A map uses three coordinate systems:
///
/// * Latitude/longitude
/// * Map coordinates: Map coordinates are in arbitrary units, as defined by the projection.
///   The only constraint on map coordinates is that the X coordinate increases going right
///   and the Y coordinate increases going up.
/// * Display coordinates: Display coordinates are in pixels, with the X coordinate increasing
///   going right and the Y coordinate increasing going up. The origin is located at the
///   lower left corner of the viewport.
///
/// The map's projection converts between latitude/longitude and map coordinates. The map's
/// view projection converts between map coordinates and display coordinates.
///
pub struct Map {
    /// The projection
    projection: Box<Projection>,
    /// The view projection
    view_projection: ViewProjection,
    /// The layers
    layers: Vec<Box<Layer>>,
}

impl Map {
    ///
    /// Creates a new map using a given projection
    ///
    pub fn new<P>(projection: P) -> Map where P: 'static + Projection {
        Map {
            projection: Box::new(projection),
            view_projection: ViewProjection {
                center: Point::origin(),
                zoom: 1f64,
            },
            layers: Vec::new(),
        }
    }

    ///
    /// Sets the projection that this map should use
    ///
    pub fn set_projection<P>(&mut self, projection: P) where P: 'static + Projection {
        self.projection = Box::new(projection)
    }

    ///
    /// Adds a layer to this map. The new layer will be drawn on top of the existing layers.
    ///
    pub fn add_layer<L>(&mut self, layer: L) where L: 'static + Layer {
        self.layers.push(Box::new(layer))
    }

    ///
    /// Removes all layers from this map
    ///
    pub fn clear_layers(&mut self) {
        self.layers.clear()
    }

    ///
    /// Draws this map with its upper left corner at (x, y) with the specified width and height
    ///
    pub fn draw(&self, x: i32, y: i32, width: i32, height: i32) {
        let combined = CombinedProjection::new(self.projection.as_ref(), &self.view_projection, width, height);
        for layer in self.layers.iter() {
            layer.draw(&combined, x, y, width, height);
        }
    }
}

///
/// A linear projection that maps between map coordinates and display coordinates
///
struct ViewProjection {
    /// The location, in map coordinates, where the center of the viewport is located
    center: Point<f64>,
    /// The ratio of the size of a display unit to the size of a map coordinate unit
    zoom: f64,
}

impl ViewProjection {
    /// Projects a point in map coordinates to a point in screen coordinates
    pub fn project(&self, map: &Point<f64>, viewport_width: i32, viewport_height: i32) -> Point<f64> {
        // Calculate the vector from the center point to the map point
        let mut map_vector = map.clone() - self.center.clone();
        // Scale by the zoom ratio
        map_vector = map_vector * self.zoom;
        // map_vector is now the screen position relative to the center
        // Shift it to make it relative to the corner
        map_vector = map_vector + Point { x: (viewport_width / 2) as f64, y: (viewport_height / 2) as f64 };
        map_vector
    }
    /// Unprojects a point from screen coordinates to a point in map coordinates
    pub fn unproject(&self, screen: &Point<f64>, viewport_width: i32, viewport_height: i32) -> Point<f64> {
        // Shift to make it relative to the center
        let mut map_vector = screen.clone() - Point { x: (viewport_width / 2) as f64, y: (viewport_height / 2) as f64 };
        // Scale by inverse zoom ratio
        map_vector = map_vector * (1f64 / self.zoom);
        // Make relative to center point
        map_vector = map_vector + self.center.clone();
        map_vector
    }
}

///
/// A Projection implementation for a combination of a Projection and a ViewProjection
///
struct CombinedProjection<'a, 'b> {
    /// The primary projection
    projection: &'a Projection,
    /// The view projection
    view_projection: &'b ViewProjection,
    /// The width of the viewport in pixels
    viewport_width: i32,
    /// The height of the viewport in pixels
    viewport_height: i32,
}

impl<'a, 'b> CombinedProjection<'a, 'b> {
    pub fn new(projection: &'a Projection, view_projection: &'b ViewProjection, viewport_width: i32, viewport_height: i32) -> CombinedProjection<'a, 'b> {
        CombinedProjection {
            projection: projection,
            view_projection: view_projection,
            viewport_width: viewport_width,
            viewport_height: viewport_height,
        }
    }
}

impl<'a, 'b> Projection for CombinedProjection<'a, 'b> {
    fn project(&self, position: &LatLon) -> Point<f64> {
        let map = self.projection.project(position);
        self.view_projection.project(&map, self.viewport_width, self.viewport_height)
    }
    fn unproject(&self, position: &Point<f64>) -> LatLon {
        let map = self.view_projection.unproject(position, self.viewport_width, self.viewport_height);
        self.projection.unproject(&map)
    }
}
<commit_msg>Various changes<commit_after>use super::{Point, LatLon};
use projection::Projection;
use layer::Layer;

///
/// Represents a map view
///
/// A map uses three coordinate systems:
///
/// * Latitude/longitude
/// * Map coordinates: Map coordinates are in arbitrary units, as defined by the projection.
///   The only constraint on map coordinates is that the X coordinate increases going right
///   and the Y coordinate increases going up.
/// * Display coordinates: Display coordinates are in pixels, with the X coordinate increasing
///   going right and the Y coordinate increasing going up. The origin is located at the
///   lower left corner of the viewport.
///
/// The map's projection converts between latitude/longitude and map coordinates. The map's
/// view projection converts between map coordinates and display coordinates.
///
pub struct Map {
    /// The projection
    projection: Box<Projection>,
    /// The view projection
    view_projection: ViewProjection,
    /// The layers
    layers: Vec<Box<Layer>>,
    /// The X location of the lower left corner of the map, in pixels
    x: i32,
    /// The Y location of the lower left corner of the map, in pixels
    y: i32,
    /// The width of the map, in pixels
    width: i32,
    /// The height of the map, in pixels
    height: i32,
}

impl Map {
    ///
    /// Creates a new map using a given projection
    ///
    pub fn new<P>(projection: P, x: i32, y: i32, width: i32, height: i32) -> Map where P: 'static + Projection {
        Map {
            projection: Box::new(projection),
            view_projection: ViewProjection {
                center: Point::origin(),
                zoom: 1f64,
            },
            layers: Vec::new(),
            x: x,
            y: y,
            width: width,
            height: height,
        }
    }

    ///
    /// Sets the projection that this map should use
    ///
    pub fn set_projection<P>(&mut self, projection: P) where P: 'static + Projection {
        self.projection = Box::new(projection)
    }

    ///
    /// Adds a layer to this map. The new layer will be drawn on top of the existing layers.
    ///
    pub fn add_layer<L>(&mut self, layer: L) where L: 'static + Layer {
        self.layers.push(Box::new(layer))
    }

    ///
    /// Removes all layers from this map
    ///
    pub fn clear_layers(&mut self) {
        self.layers.clear()
    }

    ///
    /// Returns the current zoom level
    ///
    pub fn zoom(&self) -> f64 {
        self.view_projection.zoom
    }

    ///
    /// Sets the map zoom level
    ///
    pub fn set_zoom(&mut self, zoom: f64) {
        self.view_projection.zoom = zoom
    }

    ///
    /// Sets the geometry of this map view
    ///
    /// x and y are the coordinates of the lower left corner of the map view, in pixels.
    ///
    /// width and height are its width and height in pixels.
    ///
    pub fn set_geometry(&mut self, x: i32, y: i32, width: i32, height: i32) {
        self.x = x;
        self.y = y;
        self.width = width;
        self.height = height;
    }

    ///
    /// Scrolls the map by a specified amount in pixels
    ///
    pub fn scroll(&mut self, dx: i32, dy: i32) {
        let map_delta = self.view_projection.unproject(&Point { x: dx as f64, y: dy as f64 }, self.width, self.height);
        self.view_projection.center = self.view_projection.center.clone() + map_delta;
    }

    ///
    /// Draws this map
    ///
    pub fn draw(&self) {
        let combined = CombinedProjection::new(self.projection.as_ref(), &self.view_projection, self.width, self.height);
        for layer in self.layers.iter() {
            layer.draw(&combined, self.x, self.y, self.width, self.height);
        }
    }
}

///
/// A linear projection that maps between map coordinates and display coordinates
///
struct ViewProjection {
    /// The location, in map coordinates, where the center of the viewport is located
    center: Point<f64>,
    /// The ratio of the size of a display unit to the size of a map coordinate unit
    zoom: f64,
}

impl ViewProjection {
    /// Projects a point in map coordinates to a point in screen coordinates
    pub fn project(&self, map: &Point<f64>, viewport_width: i32, viewport_height: i32) -> Point<f64> {
        // Calculate the vector from the center point to the map point
        let mut map_vector = map.clone() - self.center.clone();
        // Scale by the zoom ratio
        map_vector = map_vector * self.zoom;
        // map_vector is now the screen position relative to the center
        // Shift it to make it relative to the corner
        map_vector = map_vector + Point { x: (viewport_width / 2) as f64, y: (viewport_height / 2) as f64 };
        map_vector
    }
    /// Unprojects a point from screen coordinates to a point in map coordinates
    pub fn unproject(&self, screen: &Point<f64>, viewport_width: i32, viewport_height: i32) -> Point<f64> {
        // Shift to make it relative to the center
        let mut map_vector = screen.clone() - Point { x: (viewport_width / 2) as f64, y: (viewport_height / 2) as f64 };
        // Scale by inverse zoom ratio
        map_vector = map_vector * (1f64 / self.zoom);
        // Make relative to center point
        map_vector = map_vector + self.center.clone();
        map_vector
    }
}

///
/// A Projection implementation for a combination of a Projection and a ViewProjection
///
struct CombinedProjection<'a, 'b> {
    /// The primary projection
    projection: &'a Projection,
    /// The view projection
    view_projection: &'b ViewProjection,
    /// The width of the viewport in pixels
    viewport_width: i32,
    /// The height of the viewport in pixels
    viewport_height: i32,
}

impl<'a, 'b> CombinedProjection<'a, 'b> {
    pub fn new(projection: &'a Projection, view_projection: &'b ViewProjection, viewport_width: i32, viewport_height: i32) -> CombinedProjection<'a, 'b> {
        CombinedProjection {
            projection: projection,
            view_projection: view_projection,
            viewport_width: viewport_width,
            viewport_height: viewport_height,
        }
    }
}

impl<'a, 'b> Projection for CombinedProjection<'a, 'b> {
    fn project(&self, position: &LatLon) -> Point<f64> {
        let map = self.projection.project(position);
        self.view_projection.project(&map, self.viewport_width, self.viewport_height)
    }
    fn unproject(&self, position: &Point<f64>) -> LatLon {
        let map = self.view_projection.unproject(position, self.viewport_width, self.viewport_height);
        self.projection.unproject(&map)
    }
}
<|endoftext|>


<commit_before>pub fn primitive_types_main() {
    println!("///*** Primitive Types ***\\\\\\\n");

    arrays();
    bools();
    chars();
    f32s();

    println!("");
}

fn arrays() {
    println!("*** Arrays ***");

    let mut array: [i32; 3] = [0; 3];

    array[1] = 1;
    array[2] = 2;

    assert_eq!([1, 2], &array[1..]);

    // only if array has 32 of fever elements
    for x in &array {
        print!("{} ", x);
    }
    println!("");

    // any size
    for x in array.iter() {
        print!("{} ", x);
    }
    println!("");

    println!("");
}

fn bools() {
    println!("*** Bools ***");

    // binary operations
    let bool_val = true & false | false;
    assert!(!bool_val);

    // simple usage

    let praise_the_borrow_checker = true;

    if praise_the_borrow_checker {
        println!("yeah!");
    } else {
        println!("what?!");
    }

    match praise_the_borrow_checker {
        true => println!("keep praising!"),
        false => println!("you should praise!"),
    }

    // casting to a number

    assert_eq!(true as i32, 1);
    assert_eq!(false as i32, 0);

    // bool from a string

    use std::str::FromStr;

    assert_eq!(FromStr::from_str("true"), Ok(true));
    assert_eq!(FromStr::from_str("false"), Ok(false));
    assert!(<bool as FromStr>::from_str("not even a bool").is_err());

    assert_eq!("true".parse(), Ok(true));
    assert_eq!("false".parse(), Ok(false));
    assert!("not even a bool".parse::<bool>().is_err());

    println!("");
}

fn chars() {
    println!("*** Chars ***");

    use std;

    // char is always 4 bytes in size
    let v = vec!['h', 'e', 'l', 'l', 'o'];

    assert_eq!(20, v.len() * std::mem::size_of::<char>());

    let s = String::from("hello");

    // five elements, one byte per element
    assert_eq!(5, s.len() * std::mem::size_of::<u8>());

    assert!('1'.is_digit(10));
    assert!('f'.is_digit(16));
    assert!(!'f'.is_digit(10));

    assert_eq!('1'.to_digit(10), Some(1));
    assert_eq!('f'.to_digit(16), Some(15));

    assert_eq!('f'.to_digit(10), None);
    assert_eq!('z'.to_digit(16), None);

    println!("Unicode escape sequence for X: {}", 'X'.escape_unicode());

    // experimental api
    println!("Debug escape for \\n: {}", '\n'.escape_debug());

    println!("default escape for '\"': {}", '"'.escape_default());

    assert_eq!(1, 'A'.len_utf8());
    assert_eq!(2, 'ß'.len_utf8());

    assert_eq!(1, 'ß'.len_utf16());

    // encoding as utfs

    let mut b = [0; 2];
    let result = 'ß'.encode_utf8(&mut b);

    assert_eq!(result, "ß");
    assert_eq!(result.len(), 2);

    assert!('a'.is_alphabetic());

    assert!('a'.is_lowercase());
    assert!('ß'.is_lowercase());

    assert!('A'.is_uppercase());

    assert!(' '.is_whitespace());
    assert!(!'x'.is_whitespace());

    assert!('x'.is_alphanumeric());
    assert!('1'.is_alphanumeric());

    assert!('\r'.is_control());
    assert!(!'x'.is_control());

    assert!('8'.is_numeric());
    assert!(!'a'.is_numeric());

    println!("'X' to lowercase is: {}", 'X'.to_lowercase());
    assert_eq!('C'.to_lowercase().to_string(), "c");

    println!("'a' to uppercase is: {}", 'a'.to_uppercase());
    assert_eq!('a'.to_uppercase().to_string(), "A");

    println!("");
}

fn f32s() {
    println!("*** f32 ***");

    use std::f32;

    let nan = f32::NAN;
    assert!(nan.is_nan());
    assert!(!89_f32.is_nan());

    let inf = f32::INFINITY;
    let n_inf = f32::NEG_INFINITY;

    assert!(!89_f32.is_infinite());
    assert!(!nan.is_infinite());

    assert!(inf.is_infinite());
    assert!(n_inf.is_infinite());

    assert!(89_f32.is_finite());
    assert!(!inf.is_finite());
    assert!(!n_inf.is_finite());
    assert!(!nan.is_finite());

    let min = f32::MIN_POSITIVE;
    let max = f32::MAX;

    let lower_than_min = 1.0e-40_f32;
    let zero = 0.0_f32;

    assert!(min.is_normal());
    assert!(max.is_normal());

    assert!(!zero.is_normal());
    assert!(!f32::NAN.is_normal());
    assert!(!f32::INFINITY.is_normal());

    // values between 0 and min are Subnormal
    assert!(!lower_than_min.is_normal());

    use std::num::FpCategory;

    assert_eq!(12.4_f32.classify(), FpCategory::Normal);
    assert_eq!(f32::INFINITY.classify(), FpCategory::Infinite);

    assert_eq!(3.99_f32.floor(), 3.0);

    assert_eq!(3.01_f32.ceil(), 4.0);

    assert_eq!(3.3_f32.round(), 3.0);
    assert_eq!(3.5_f32.round(), 4.0);

    assert_eq!(3.3_f32.trunc(), 3.0);
    assert_eq!(3.9_f32.trunc(), 3.0);

    assert_eq!(3.5_f32.fract(), 0.5);
    assert_eq!(3.0_f32.fract(), 0.0);

    assert_eq!(3.5_f32.abs(), 3.5);
    assert_eq!((-3.5_f32).abs(), 3.5);

    assert_eq!(1.0, 3.5_f32.signum());
    assert_eq!(-1.0, (-3.5_f32).signum());

    assert!(f32::NAN.signum().is_nan());

    assert!(7.0_f32.is_sign_positive());
    assert!(!(-7.0_f32).is_sign_positive());

    assert!((-7.0_f32).is_sign_negative());
    assert!(!7.0_f32.is_sign_negative());

    assert!(!f32::NAN.is_sign_positive() && !f32::NAN.is_sign_negative());

    println!("10.0 * 2.0 + 0.5 = {}", 10.0_f32.mul_add(2.0, 0.5));

    assert_eq!(0.25, 4.0_f32.recip());

    assert_eq!(32.0, 2.0_f32.powi(5));

    assert_eq!(32.0, 2.0_f32.powf(5.0));

    assert_eq!(4.0, 16.0_f32.sqrt());

    println!("e^2 = {}", 2.0_f32.exp());

    println!("2^6 = {}", 6.0_f32.exp2());

    // natural logarithm
    println!("ln(10) = {}", 10.0_f32.ln());

    println!("log(10, 2) = {}", 10.0_f32.log(2.0));

    println!("log2(10) = {}", 10.0_f32.log2());

    println!("log10(20) = {}", 20.0_f32.log10());

    println!("pi to degrees: {}", f32::consts::PI.to_degrees());

    println!("180 deg to radians: {}", 180.0_f32.to_radians());

    assert_eq!(3.0, 1.0_f32.max(3.0));
    assert_eq!(1.0, 1.0_f32.min(3.0));

    assert_eq!(3.0, 27.0_f32.cbrt());

    println!("hypot of 2.0 and 3.0 = {}", 2.0_f32.hypot(3.0));

    // radians
    println!("sin of 3: {}", 3.0_f32.sin());
    println!("cos of 3: {}", 3.0_f32.cos());
    println!("tan of 3: {}", 3.0_f32.tan());

    println!("asin of 0.8: {}", 0.8_f32.asin());
    println!("acos of 0.8: {}", 0.8_f32.acos());
    println!("atan of 0.8: {}", 0.8_f32.atan());
    println!("atan2 of 3.0 and 0.5: {}", 3.0_f32.atan2(0.5));

    println!("sin and cos of 3: {:?}", 3.0_f32.sin_cos());

    println!("e^2-1 is {}", 2.0_f32.exp_m1());

    println!("ln_1p of 2.5: {}", 2.5_f32.ln_1p());

    println!("sinh of 3: {}", 3.0_f32.sinh());
    println!("cosh of 3: {}", 3.0_f32.cosh());
    println!("tanh of 3: {}", 3.0_f32.tanh());

    println!("asinh of 3: {}", 3.0_f32.asinh());
    println!("acosh of 3: {}", 3.0_f32.acosh());
    println!("atanh of 0.8: {}", 0.8_f32.atanh());

    println!("");
}
<commit_msg>[Rust] STD Library - Primitive Types - i32<commit_after>pub fn primitive_types_main() {
    println!("///*** Primitive Types ***\\\\\\\n");

    arrays();
    bools();
    chars();
    f32s();
    i32s();

    println!("");
}

fn arrays() {
    println!("*** Arrays ***");

    let mut array: [i32; 3] = [0; 3];

    array[1] = 1;
    array[2] = 2;

    assert_eq!([1, 2], &array[1..]);

    // only if array has 32 of fever elements
    for x in &array {
        print!("{} ", x);
    }
    println!("");

    // any size
    for x in array.iter() {
        print!("{} ", x);
    }
    println!("");

    println!("");
}

fn bools() {
    println!("*** Bools ***");

    // binary operations
    let bool_val = true & false | false;
    assert!(!bool_val);

    // simple usage

    let praise_the_borrow_checker = true;

    if praise_the_borrow_checker {
        println!("yeah!");
    } else {
        println!("what?!");
    }

    match praise_the_borrow_checker {
        true => println!("keep praising!"),
        false => println!("you should praise!"),
    }

    // casting to a number

    assert_eq!(true as i32, 1);
    assert_eq!(false as i32, 0);

    // bool from a string

    use std::str::FromStr;

    assert_eq!(FromStr::from_str("true"), Ok(true));
    assert_eq!(FromStr::from_str("false"), Ok(false));
    assert!(<bool as FromStr>::from_str("not even a bool").is_err());

    assert_eq!("true".parse(), Ok(true));
    assert_eq!("false".parse(), Ok(false));
    assert!("not even a bool".parse::<bool>().is_err());

    println!("");
}

fn chars() {
    println!("*** Chars ***");

    use std;

    // char is always 4 bytes in size
    let v = vec!['h', 'e', 'l', 'l', 'o'];

    assert_eq!(20, v.len() * std::mem::size_of::<char>());

    let s = String::from("hello");

    // five elements, one byte per element
    assert_eq!(5, s.len() * std::mem::size_of::<u8>());

    assert!('1'.is_digit(10));
    assert!('f'.is_digit(16));
    assert!(!'f'.is_digit(10));

    assert_eq!('1'.to_digit(10), Some(1));
    assert_eq!('f'.to_digit(16), Some(15));

    assert_eq!('f'.to_digit(10), None);
    assert_eq!('z'.to_digit(16), None);

    println!("Unicode escape sequence for X: {}", 'X'.escape_unicode());

    // experimental api
    println!("Debug escape for \\n: {}", '\n'.escape_debug());

    println!("default escape for '\"': {}", '"'.escape_default());

    assert_eq!(1, 'A'.len_utf8());
    assert_eq!(2, 'ß'.len_utf8());

    assert_eq!(1, 'ß'.len_utf16());

    // encoding as utfs

    let mut b = [0; 2];
    let result = 'ß'.encode_utf8(&mut b);

    assert_eq!(result, "ß");
    assert_eq!(result.len(), 2);

    assert!('a'.is_alphabetic());

    assert!('a'.is_lowercase());
    assert!('ß'.is_lowercase());

    assert!('A'.is_uppercase());

    assert!(' '.is_whitespace());
    assert!(!'x'.is_whitespace());

    assert!('x'.is_alphanumeric());
    assert!('1'.is_alphanumeric());

    assert!('\r'.is_control());
    assert!(!'x'.is_control());

    assert!('8'.is_numeric());
    assert!(!'a'.is_numeric());

    println!("'X' to lowercase is: {}", 'X'.to_lowercase());
    assert_eq!('C'.to_lowercase().to_string(), "c");

    println!("'a' to uppercase is: {}", 'a'.to_uppercase());
    assert_eq!('a'.to_uppercase().to_string(), "A");

    println!("");
}

fn f32s() {
    println!("*** f32 ***");

    use std::f32;

    let nan = f32::NAN;
    assert!(nan.is_nan());
    assert!(!89_f32.is_nan());

    let inf = f32::INFINITY;
    let n_inf = f32::NEG_INFINITY;

    assert!(!89_f32.is_infinite());
    assert!(!nan.is_infinite());

    assert!(inf.is_infinite());
    assert!(n_inf.is_infinite());

    assert!(89_f32.is_finite());
    assert!(!inf.is_finite());
    assert!(!n_inf.is_finite());
    assert!(!nan.is_finite());

    let min = f32::MIN_POSITIVE;
    let max = f32::MAX;

    let lower_than_min = 1.0e-40_f32;
    let zero = 0.0_f32;

    assert!(min.is_normal());
    assert!(max.is_normal());

    assert!(!zero.is_normal());
    assert!(!f32::NAN.is_normal());
    assert!(!f32::INFINITY.is_normal());

    // values between 0 and min are Subnormal
    assert!(!lower_than_min.is_normal());

    use std::num::FpCategory;

    assert_eq!(12.4_f32.classify(), FpCategory::Normal);
    assert_eq!(f32::INFINITY.classify(), FpCategory::Infinite);

    assert_eq!(3.99_f32.floor(), 3.0);

    assert_eq!(3.01_f32.ceil(), 4.0);

    assert_eq!(3.3_f32.round(), 3.0);
    assert_eq!(3.5_f32.round(), 4.0);

    assert_eq!(3.3_f32.trunc(), 3.0);
    assert_eq!(3.9_f32.trunc(), 3.0);

    assert_eq!(3.5_f32.fract(), 0.5);
    assert_eq!(3.0_f32.fract(), 0.0);

    assert_eq!(3.5_f32.abs(), 3.5);
    assert_eq!((-3.5_f32).abs(), 3.5);

    assert_eq!(1.0, 3.5_f32.signum());
    assert_eq!(-1.0, (-3.5_f32).signum());

    assert!(f32::NAN.signum().is_nan());

    assert!(7.0_f32.is_sign_positive());
    assert!(!(-7.0_f32).is_sign_positive());

    assert!((-7.0_f32).is_sign_negative());
    assert!(!7.0_f32.is_sign_negative());

    assert!(!f32::NAN.is_sign_positive() && !f32::NAN.is_sign_negative());

    println!("10.0 * 2.0 + 0.5 = {}", 10.0_f32.mul_add(2.0, 0.5));

    assert_eq!(0.25, 4.0_f32.recip());

    assert_eq!(32.0, 2.0_f32.powi(5));

    assert_eq!(32.0, 2.0_f32.powf(5.0));

    assert_eq!(4.0, 16.0_f32.sqrt());

    println!("e^2 = {}", 2.0_f32.exp());

    println!("2^6 = {}", 6.0_f32.exp2());

    // natural logarithm
    println!("ln(10) = {}", 10.0_f32.ln());

    println!("log(10, 2) = {}", 10.0_f32.log(2.0));

    println!("log2(10) = {}", 10.0_f32.log2());

    println!("log10(20) = {}", 20.0_f32.log10());

    println!("pi to degrees: {}", f32::consts::PI.to_degrees());

    println!("180 deg to radians: {}", 180.0_f32.to_radians());

    assert_eq!(3.0, 1.0_f32.max(3.0));
    assert_eq!(1.0, 1.0_f32.min(3.0));

    assert_eq!(3.0, 27.0_f32.cbrt());

    println!("hypot of 2.0 and 3.0 = {}", 2.0_f32.hypot(3.0));

    // radians
    println!("sin of 3: {}", 3.0_f32.sin());
    println!("cos of 3: {}", 3.0_f32.cos());
    println!("tan of 3: {}", 3.0_f32.tan());

    println!("asin of 0.8: {}", 0.8_f32.asin());
    println!("acos of 0.8: {}", 0.8_f32.acos());
    println!("atan of 0.8: {}", 0.8_f32.atan());
    println!("atan2 of 3.0 and 0.5: {}", 3.0_f32.atan2(0.5));

    println!("sin and cos of 3: {:?}", 3.0_f32.sin_cos());

    println!("e^2-1 is {}", 2.0_f32.exp_m1());

    println!("ln_1p of 2.5: {}", 2.5_f32.ln_1p());

    println!("sinh of 3: {}", 3.0_f32.sinh());
    println!("cosh of 3: {}", 3.0_f32.cosh());
    println!("tanh of 3: {}", 3.0_f32.tanh());

    println!("asinh of 3: {}", 3.0_f32.asinh());
    println!("acosh of 3: {}", 3.0_f32.acosh());
    println!("atanh of 0.8: {}", 0.8_f32.atanh());

    println!("");
}

fn i32s() {
    println!("*** i32s ***");

    assert_eq!(i8::min_value(), -128);
    assert_eq!(i8::max_value(), 127);

    assert_eq!(i32::from_str_radix("A", 16), Ok(10));

    assert_eq!(1, (-0b1000_0000i8).count_ones());
    assert_eq!(7, (-0b1000_0000i8).count_zeros());

    assert_eq!(0, (-1_i16).leading_zeros());
    assert_eq!(2, (-4_i8).trailing_zeros());

    println!("{:b}", (0b1001010_i64).rotate_left(1));
    println!("{:b}", (0b1001010_i64).rotate_right(1));

    println!("{:x}", 0x01234567i64.swap_bytes());

    assert_eq!(Some(32767), 7_i16.checked_add(32760));
    assert_eq!(None, 8_i16.checked_add(32760));

    assert_eq!(Some(-128), (-127_i8).checked_sub(1));
    assert_eq!(None, (-128_i8).checked_sub(1));

    assert_eq!(Some(126), 6_i8.checked_mul(21));
    assert_eq!(Some(127), (-127_i8).checked_div(-1));
    assert_eq!((1_i8).checked_div(0), None);

    assert_eq!(Some(1), 5_i32.checked_rem(2));
    assert_eq!(None, 5_i32.checked_rem(0));

    use std::i32;

    assert_eq!(Some(-5), 5_i32.checked_neg());
    assert_eq!(None, i32::MIN.checked_neg());

    assert_eq!(Some(0x100), 0x10_i32.checked_shl(4));
    assert_eq!(Some(0x1), 0x10_i32.checked_shr(4));

    assert_eq!(Some(5), (-5_i32).checked_abs());

    assert_eq!(100_i8.saturating_add(1), 101);
    assert_eq!(100_i8.saturating_add(127), 127);

    // there are saturating variants for everything else too

    assert_eq!(100_i8.wrapping_add(27), 127);
    assert_eq!(100_i8.wrapping_add(127), -29);

    // there are wrapping variants for everything else too

    assert_eq!((7, false), 5_i32.overflowing_add(2));
    assert_eq!((i32::MIN, true), i32::MAX.overflowing_add(1));

    // there are overflowing variants for everything else too

    assert_eq!(16, 2_i32.pow(4));
    assert_eq!(7, 7_i32.abs());
    assert_eq!(7, (-7_i32).abs());

    assert_eq!(1, 10_i8.signum());
    assert_eq!(0, 0_i8.signum());
    assert_eq!(-1, (-10_i8).signum());

    assert!(10_i8.is_positive());

    assert!((-10_i8).is_negative());

    println!("");
}
<|endoftext|>